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 958k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c46c46c1f4c709d35888c5eb3d047bbc9d4d31c | 351 | py | Python | src/code-challenges/codewars/5KYU/productFib/test_productFib.py | maltewirz/code-challenges | 97777b10963f19bc587ddd984f0526b221c081f8 | [
"MIT"
] | 1 | 2020-08-30T07:52:20.000Z | 2020-08-30T07:52:20.000Z | src/code-challenges/codewars/5KYU/productFib/test_productFib.py | maltewirz/code-challenges | 97777b10963f19bc587ddd984f0526b221c081f8 | [
"MIT"
] | 6 | 2020-08-12T07:05:04.000Z | 2021-08-23T06:10:10.000Z | src/code-challenges/codewars/5KYU/productFib/test_productFib.py | maltewirz/code-challenges | 97777b10963f19bc587ddd984f0526b221c081f8 | [
"MIT"
] | null | null | null | from productFib import productFib
import unittest
class Test(unittest.TestCase):
def test_1(self):
result = productFib(4895)
self.assertEqual(result, [55, 89, True])
# def test_2(self):
# result = productFib(5895)
# self.assertEqual(result, [89, 144, False])
if __name__ == "__main__":
unittest.main()
| 20.647059 | 52 | 0.641026 | from productFib import productFib
import unittest
class Test(unittest.TestCase):
def test_1(self):
result = productFib(4895)
self.assertEqual(result, [55, 89, True])
if __name__ == "__main__":
unittest.main()
| true | true |
1c46c4949b4efa2afa8ed0d4db1bfe2610a1a4ad | 622 | py | Python | generateFileList.py | mrzhu666/USCL | 8a4741046ef8f337b1e9439d1575db670a11355c | [
"MIT"
] | null | null | null | generateFileList.py | mrzhu666/USCL | 8a4741046ef8f337b1e9439d1575db670a11355c | [
"MIT"
] | null | null | null | generateFileList.py | mrzhu666/USCL | 8a4741046ef8f337b1e9439d1575db670a11355c | [
"MIT"
] | null | null | null | import cv2
import os
import pickle
from numpy.core.fromnumeric import shape
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from typing import Tuple
from collections import defaultdict
from sklearn.model_selection import train_test_split
from IgAModel66.setting import config
# 添加文件名单到 result/csv里
files=os.listdir(config['server_path']+'IgAModel/test/M0/')
files.extend(os.listdir(config['server_path']+'IgAModel/test/M1/') )
eval_All=pd.read_csv('result/eval_All_0.73.csv',header=0)
eval_All['file']=files
eval_All.to_csv('result/eval_All_0.73_file.csv',index=False) | 23.037037 | 68 | 0.803859 | import cv2
import os
import pickle
from numpy.core.fromnumeric import shape
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from typing import Tuple
from collections import defaultdict
from sklearn.model_selection import train_test_split
from IgAModel66.setting import config
files=os.listdir(config['server_path']+'IgAModel/test/M0/')
files.extend(os.listdir(config['server_path']+'IgAModel/test/M1/') )
eval_All=pd.read_csv('result/eval_All_0.73.csv',header=0)
eval_All['file']=files
eval_All.to_csv('result/eval_All_0.73_file.csv',index=False) | true | true |
1c46c54cd215d2279abe7d5e268fcf2822b63cd3 | 903 | py | Python | ultimatepython/data_structures/dict.py | Benczus/ultimate-python | 2bcc8233af7b21388b587812d3e5124189b8cdec | [
"MIT"
] | 1 | 2020-09-07T12:50:18.000Z | 2020-09-07T12:50:18.000Z | ultimatepython/data_structures/dict.py | Benczus/ultimate-python | 2bcc8233af7b21388b587812d3e5124189b8cdec | [
"MIT"
] | null | null | null | ultimatepython/data_structures/dict.py | Benczus/ultimate-python | 2bcc8233af7b21388b587812d3e5124189b8cdec | [
"MIT"
] | null | null | null | def main():
# Let's create a dictionary with student keys and GPA values
student_gpa = {"john": 3.5,
"jane": 4.0,
"bob": 2.8,
"mary": 3.2}
# There are four student records in this dictionary
assert len(student_gpa) == 4
# Each student has a name key and a GPA value
assert len(student_gpa.keys()) == len(student_gpa.values())
# We can get the names in isolation
for student in student_gpa.keys():
assert len(student) > 2
# We can get the GPAs in isolation
for gpa in student_gpa.values():
assert gpa > 2.0
# We can get the GPA for a specific student
assert student_gpa["john"] == 3.5
# We can access the student and GPA simultaneously
for student, gpa in student_gpa.items():
print(f"Student {student} has a {gpa} GPA")
if __name__ == "__main__":
main()
| 28.21875 | 64 | 0.601329 | def main():
student_gpa = {"john": 3.5,
"jane": 4.0,
"bob": 2.8,
"mary": 3.2}
# There are four student records in this dictionary
assert len(student_gpa) == 4
# Each student has a name key and a GPA value
assert len(student_gpa.keys()) == len(student_gpa.values())
# We can get the names in isolation
for student in student_gpa.keys():
assert len(student) > 2
# We can get the GPAs in isolation
for gpa in student_gpa.values():
assert gpa > 2.0
# We can get the GPA for a specific student
assert student_gpa["john"] == 3.5
# We can access the student and GPA simultaneously
for student, gpa in student_gpa.items():
print(f"Student {student} has a {gpa} GPA")
if __name__ == "__main__":
main()
| true | true |
1c46c6c3ff147c8e547e3aaf58bce039d6e667a5 | 5,134 | py | Python | SCons/Scanner/DirTests.py | jcassagnol-public/scons | 8eaf585a893757e68c9e4a6e25d375021fa5eab7 | [
"MIT"
] | null | null | null | SCons/Scanner/DirTests.py | jcassagnol-public/scons | 8eaf585a893757e68c9e4a6e25d375021fa5eab7 | [
"MIT"
] | null | null | null | SCons/Scanner/DirTests.py | jcassagnol-public/scons | 8eaf585a893757e68c9e4a6e25d375021fa5eab7 | [
"MIT"
] | null | null | null | # MIT License
#
# Copyright The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import os.path
import unittest
import TestCmd
import SCons.Node.FS
import SCons.Scanner.Dir
from SCons.SConsign import current_sconsign_filename
#class DummyNode:
# def __init__(self, name, fs):
# self.name = name
# self.abspath = test.workpath(name)
# self.fs = fs
# def __str__(self):
# return self.name
# def Entry(self, name):
# return self.fs.Entry(name)
class DummyEnvironment:
def __init__(self, root):
self.fs = SCons.Node.FS.FS(root)
def Dir(self, name):
return self.fs.Dir(name)
def Entry(self, name):
return self.fs.Entry(name)
def File(self, name):
return self.fs.File(name)
def get_factory(self, factory):
return factory or self.fs.Entry
class DirScannerTestBase(unittest.TestCase):
def setUp(self):
self.test = TestCmd.TestCmd(workdir = '')
self.test.subdir('dir', ['dir', 'sub'])
sconsign = current_sconsign_filename()
self.test.write(['dir', 'f1'], "dir/f1\n")
self.test.write(['dir', 'f2'], "dir/f2\n")
self.test.write(['dir', '{}'.format(sconsign)], "dir/{}\n".format(sconsign))
self.test.write(['dir', '{}.bak'.format(sconsign)], "dir/{}.bak\n".format(sconsign))
self.test.write(['dir', '{}.dat'.format(sconsign)], "dir/{}.dat\n".format(sconsign))
self.test.write(['dir', '{}.db'.format(sconsign)], "dir/{}.db\n".format(sconsign))
self.test.write(['dir', '{}.dblite'.format(sconsign)], "dir/{}.dblite\n".format(sconsign))
self.test.write(['dir', '{}.dir'.format(sconsign)], "dir/{}.dir\n".format(sconsign))
self.test.write(['dir', '{}.pag'.format(sconsign)], "dir/{}.pag\n".format(sconsign))
self.test.write(['dir', 'sub', 'f3'], "dir/sub/f3\n")
self.test.write(['dir', 'sub', 'f4'], "dir/sub/f4\n")
self.test.write(['dir', 'sub', '{}'.format(sconsign)], "dir/{}\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.bak'.format(sconsign)], "dir/{}.bak\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.dat'.format(sconsign)], "dir/{}.dat\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.dblite'.format(sconsign)], "dir/{}.dblite\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.dir'.format(sconsign)], "dir/{}.dir\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.pag'.format(sconsign)], "dir/{}.pag\n".format(sconsign))
class DirScannerTestCase(DirScannerTestBase):
def runTest(self):
env = DummyEnvironment(self.test.workpath())
s = SCons.Scanner.Dir.DirScanner()
expect = [
os.path.join('dir', 'f1'),
os.path.join('dir', 'f2'),
os.path.join('dir', 'sub'),
]
deps = s(env.Dir('dir'), env, ())
sss = list(map(str, deps))
assert sss == expect, "Found {}, expected {}".format(sss, expect)
expect = [
os.path.join('dir', 'sub', 'f3'),
os.path.join('dir', 'sub', 'f4'),
]
deps = s(env.Dir('dir/sub'), env, ())
sss = list(map(str, deps))
assert sss == expect, "Found {}, expected {}".format(sss, expect)
class DirEntryScannerTestCase(DirScannerTestBase):
def runTest(self):
env = DummyEnvironment(self.test.workpath())
s = SCons.Scanner.Dir.DirEntryScanner()
deps = s(env.Dir('dir'), env, ())
sss = list(map(str, deps))
assert sss == [], "Found {}, expected {}".format(sss, [])
deps = s(env.Dir('dir/sub'), env, ())
sss = list(map(str, deps))
assert sss == [], "Found {}, expected {}".format(sss, [])
# Make sure we don't blow up if handed a non-Dir node.
deps = s(env.File('dir/f1'), env, ())
sss = list(map(str, deps))
assert sss == [], "Found {}, expected {}".format(sss, [])
if __name__ == "__main__":
unittest.main()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| 39.19084 | 105 | 0.614725 |
import os.path
import unittest
import TestCmd
import SCons.Node.FS
import SCons.Scanner.Dir
from SCons.SConsign import current_sconsign_filename
class DummyEnvironment:
def __init__(self, root):
self.fs = SCons.Node.FS.FS(root)
def Dir(self, name):
return self.fs.Dir(name)
def Entry(self, name):
return self.fs.Entry(name)
def File(self, name):
return self.fs.File(name)
def get_factory(self, factory):
return factory or self.fs.Entry
class DirScannerTestBase(unittest.TestCase):
def setUp(self):
self.test = TestCmd.TestCmd(workdir = '')
self.test.subdir('dir', ['dir', 'sub'])
sconsign = current_sconsign_filename()
self.test.write(['dir', 'f1'], "dir/f1\n")
self.test.write(['dir', 'f2'], "dir/f2\n")
self.test.write(['dir', '{}'.format(sconsign)], "dir/{}\n".format(sconsign))
self.test.write(['dir', '{}.bak'.format(sconsign)], "dir/{}.bak\n".format(sconsign))
self.test.write(['dir', '{}.dat'.format(sconsign)], "dir/{}.dat\n".format(sconsign))
self.test.write(['dir', '{}.db'.format(sconsign)], "dir/{}.db\n".format(sconsign))
self.test.write(['dir', '{}.dblite'.format(sconsign)], "dir/{}.dblite\n".format(sconsign))
self.test.write(['dir', '{}.dir'.format(sconsign)], "dir/{}.dir\n".format(sconsign))
self.test.write(['dir', '{}.pag'.format(sconsign)], "dir/{}.pag\n".format(sconsign))
self.test.write(['dir', 'sub', 'f3'], "dir/sub/f3\n")
self.test.write(['dir', 'sub', 'f4'], "dir/sub/f4\n")
self.test.write(['dir', 'sub', '{}'.format(sconsign)], "dir/{}\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.bak'.format(sconsign)], "dir/{}.bak\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.dat'.format(sconsign)], "dir/{}.dat\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.dblite'.format(sconsign)], "dir/{}.dblite\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.dir'.format(sconsign)], "dir/{}.dir\n".format(sconsign))
self.test.write(['dir', 'sub', '{}.pag'.format(sconsign)], "dir/{}.pag\n".format(sconsign))
class DirScannerTestCase(DirScannerTestBase):
def runTest(self):
env = DummyEnvironment(self.test.workpath())
s = SCons.Scanner.Dir.DirScanner()
expect = [
os.path.join('dir', 'f1'),
os.path.join('dir', 'f2'),
os.path.join('dir', 'sub'),
]
deps = s(env.Dir('dir'), env, ())
sss = list(map(str, deps))
assert sss == expect, "Found {}, expected {}".format(sss, expect)
expect = [
os.path.join('dir', 'sub', 'f3'),
os.path.join('dir', 'sub', 'f4'),
]
deps = s(env.Dir('dir/sub'), env, ())
sss = list(map(str, deps))
assert sss == expect, "Found {}, expected {}".format(sss, expect)
class DirEntryScannerTestCase(DirScannerTestBase):
def runTest(self):
env = DummyEnvironment(self.test.workpath())
s = SCons.Scanner.Dir.DirEntryScanner()
deps = s(env.Dir('dir'), env, ())
sss = list(map(str, deps))
assert sss == [], "Found {}, expected {}".format(sss, [])
deps = s(env.Dir('dir/sub'), env, ())
sss = list(map(str, deps))
assert sss == [], "Found {}, expected {}".format(sss, [])
deps = s(env.File('dir/f1'), env, ())
sss = list(map(str, deps))
assert sss == [], "Found {}, expected {}".format(sss, [])
if __name__ == "__main__":
unittest.main()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| true | true |
1c46c7815098b0d623f6f7a150989694f53aa6f2 | 877 | py | Python | show/gearbox.py | sg893052/sonic-utilities | fdb79b8d65b8ca22232f4e6b140f593dd01613d5 | [
"Apache-2.0"
] | 91 | 2016-03-23T14:24:41.000Z | 2022-03-18T20:25:37.000Z | show/gearbox.py | sg893052/sonic-utilities | fdb79b8d65b8ca22232f4e6b140f593dd01613d5 | [
"Apache-2.0"
] | 1,495 | 2017-02-15T10:49:10.000Z | 2022-03-31T18:49:56.000Z | show/gearbox.py | sg893052/sonic-utilities | fdb79b8d65b8ca22232f4e6b140f593dd01613d5 | [
"Apache-2.0"
] | 466 | 2016-04-25T09:31:23.000Z | 2022-03-31T06:54:17.000Z | import click
import utilities_common.cli as clicommon
@click.group(cls=clicommon.AliasedGroup)
def gearbox():
"""Show gearbox info"""
pass
# 'phys' subcommand ("show gearbox phys")
@gearbox.group(cls=clicommon.AliasedGroup)
def phys():
"""Show external PHY information"""
pass
# 'status' subcommand ("show gearbox phys status")
@phys.command()
@click.pass_context
def status(ctx):
"""Show gearbox phys status"""
clicommon.run_command("gearboxutil phys status")
# 'interfaces' subcommand ("show gearbox interfaces")
@gearbox.group(cls=clicommon.AliasedGroup)
def interfaces():
"""Show gearbox interfaces information"""
pass
# 'status' subcommand ("show gearbox interfaces status")
@interfaces.command()
@click.pass_context
def status(ctx):
"""Show gearbox interfaces status"""
clicommon.run_command("gearboxutil interfaces status")
| 25.057143 | 58 | 0.729761 | import click
import utilities_common.cli as clicommon
@click.group(cls=clicommon.AliasedGroup)
def gearbox():
pass
@gearbox.group(cls=clicommon.AliasedGroup)
def phys():
pass
@phys.command()
@click.pass_context
def status(ctx):
clicommon.run_command("gearboxutil phys status")
@gearbox.group(cls=clicommon.AliasedGroup)
def interfaces():
pass
@interfaces.command()
@click.pass_context
def status(ctx):
clicommon.run_command("gearboxutil interfaces status")
| true | true |
1c46c7dc238b0a632c7b17c278cc27218f17eb00 | 6,095 | py | Python | software/metax/WeightDBUtilities.py | adellanno/MetaXcan | cfc9e369bbf5630e0c9488993cd877f231c5d02e | [
"MIT"
] | 83 | 2016-07-19T20:14:52.000Z | 2022-03-28T17:02:39.000Z | software/metax/WeightDBUtilities.py | adellanno/MetaXcan | cfc9e369bbf5630e0c9488993cd877f231c5d02e | [
"MIT"
] | 75 | 2016-02-25T16:43:17.000Z | 2022-03-30T14:19:03.000Z | software/metax/WeightDBUtilities.py | adellanno/MetaXcan | cfc9e369bbf5630e0c9488993cd877f231c5d02e | [
"MIT"
] | 71 | 2016-02-11T17:10:32.000Z | 2022-03-30T20:15:19.000Z | __author__ = 'heroico'
import sqlite3
import os
from collections import OrderedDict
from . import Exceptions
class GeneEntry:
def __init__(self, gene, gene_name, n_snps, R2, pval,qval):
self.gene = gene
self.gene_name = gene_name
self.n_snps = n_snps
self.pred_perf_R2 = R2
self.pred_perf_pval = pval
self.pred_perf_qval = qval
class WeightDBEntry:
def __init__(self, rsid=None, gene=None, weight=None, ref_allele=None, eff_allele=None, pval=None, N=None, cis=None):
"""Warning: many db's have empty 'N', 'cis' and 'pval'"""
self.rsid = rsid
self.gene = gene
self.weight = weight
self.ref_allele = ref_allele
self.eff_allele = eff_allele
self.pval = pval
self.N = N
self.cis = cis
class WDBQF(object):
"Weight DB weight Query Format"
RSID=0
GENE=1
WEIGHT=2
REF_ALLELE=3
EFF_ALLELE=4
class WDBEQF(object):
"Weight DB extra table Query Format"
GENE=0
GENE_NAME=1
N_SNP_IN_MODEL=2
PRED_PERF_R2=3
PRED_PERF_PVAL=4
PRED_PERF_QVAL=5
class WeightDB(object):
def __init__(self, file_name , create_if_absent=False):
self.connection = None
self.cursor = None
self.file_name = file_name
self.create_if_absent = create_if_absent
def __del__(self):
self.closeDB()
def openDBIfNecessary(self):
if not self.connection:
if not self.create_if_absent and not os.path.exists(self.file_name):
raise RuntimeError("Weight file doesn't exist")
self.connection = sqlite3.connect(self.file_name)
self.cursor = self.connection.cursor()
def closeDB(self):
if self.connection:
self.connection.close()
self.connection = None
self.cursor = None
def weightEntriesFromResults(self, results, extra, result_callback=None):
weights = []
for result in results:
weight = WeightDBEntry(result[WDBQF.RSID],
result[WDBQF.GENE],
result[WDBQF.WEIGHT],
result[WDBQF.REF_ALLELE],
result[WDBQF.EFF_ALLELE])
weights.append(weight)
if result_callback:
result_callback(weight, extra)
return weights
def loadFromDB(self, callback=None, gene_key=None):
self.openDBIfNecessary()
extra = self.loadExtraColumnData()
extra = {e.gene:e for e in extra}
if gene_key is None:
results = self.cursor.execute("SELECT rsid, gene, weight, ref_allele, eff_allele FROM weights;")
else:
results = self.cursor.execute("SELECT rsid, gene, weight, ref_allele, eff_allele FROM weights where gene = ?;", (gene_key))
weights = self.weightEntriesFromResults(results, extra, callback)
return weights
def loadExtraColumnData(self, gene_key=None):
self.openDBIfNecessary()
try:
if gene_key is None:
results = self.cursor.execute("SELECT gene, genename, `n.snps.in.model`, `pred.perf.R2`, `pred.perf.pval`, `pred.perf.qval` FROM extra;")
else:
results = self.cursor.execute("SELECT gene, genename, `n.snps.in.model`, `pred.perf.R2`, `pred.perf.pval`, `pred.perf.qval` FROM extra WHERE gene = ?;", (gene_key,))
except sqlite3.OperationalError as e:
print(str(e))
raise Exceptions.ReportableException("Could not read input tissue database. Please try updating the tissue model files.")
except Exception as e:
raise e
extra = [GeneEntry(x[WDBEQF.GENE], x[WDBEQF.GENE_NAME], x[WDBEQF.N_SNP_IN_MODEL], x[WDBEQF.PRED_PERF_R2], x[WDBEQF.PRED_PERF_PVAL], x[WDBEQF.PRED_PERF_QVAL]) for x in results]
return extra
def loadGeneNamesFromDB(self):
self.openDBIfNecessary()
names = []
results = self.cursor.execute("SELECT DISTINCT gene FROM weights;")
for result in results:
name = result[0]
names.append(name)
return names
class WeightDBEntryLogic(object):
def __init__(self, db_file_name):
self.weights_by_gene = OrderedDict()#{}
self.genes_for_an_rsid = OrderedDict()#{}
self.gene_data_for_gene = OrderedDict()#{}
self._loadData(db_file_name)
def anEntryWithRSID(self, rsid):
entry = None
if not rsid in self.genes_for_an_rsid:
return entry
genes = self.genes_for_an_rsid[rsid]
gene = genes[0]
weights = self.weights_by_gene[gene]
entry = weights[rsid]
return entry
def _loadData(self, db_file_name):
weights_db = WeightDB(db_file_name)
class ByNameCallback(object):
"""Helper class to group weights by gene name"""
def __init__(self, weights_by_gene, genes_for_an_rsid, gene_data_for_gene):
self.weights_by_gene = weights_by_gene
self.genes_for_an_rsid = genes_for_an_rsid
self.gene_data_for_gene = gene_data_for_gene
def __call__(self, weight, extra):
if weight.gene in self.weights_by_gene:
weights = self.weights_by_gene[weight.gene]
else:
weights = OrderedDict()
self.weights_by_gene[weight.gene] = weights
weights[weight.rsid]= weight
if not weight.rsid in self.genes_for_an_rsid:
self.genes_for_an_rsid[weight.rsid] = []
genes = self.genes_for_an_rsid[weight.rsid]
if not weight.gene in genes:
genes.append(weight.gene)
gene_entry = extra[weight.gene]
self.gene_data_for_gene[weight.gene] = gene_entry
callback = ByNameCallback(self.weights_by_gene, self.genes_for_an_rsid, self.gene_data_for_gene)
weights_db.loadFromDB(callback)
| 35.643275 | 183 | 0.612961 | __author__ = 'heroico'
import sqlite3
import os
from collections import OrderedDict
from . import Exceptions
class GeneEntry:
def __init__(self, gene, gene_name, n_snps, R2, pval,qval):
self.gene = gene
self.gene_name = gene_name
self.n_snps = n_snps
self.pred_perf_R2 = R2
self.pred_perf_pval = pval
self.pred_perf_qval = qval
class WeightDBEntry:
def __init__(self, rsid=None, gene=None, weight=None, ref_allele=None, eff_allele=None, pval=None, N=None, cis=None):
self.rsid = rsid
self.gene = gene
self.weight = weight
self.ref_allele = ref_allele
self.eff_allele = eff_allele
self.pval = pval
self.N = N
self.cis = cis
class WDBQF(object):
RSID=0
GENE=1
WEIGHT=2
REF_ALLELE=3
EFF_ALLELE=4
class WDBEQF(object):
GENE=0
GENE_NAME=1
N_SNP_IN_MODEL=2
PRED_PERF_R2=3
PRED_PERF_PVAL=4
PRED_PERF_QVAL=5
class WeightDB(object):
def __init__(self, file_name , create_if_absent=False):
self.connection = None
self.cursor = None
self.file_name = file_name
self.create_if_absent = create_if_absent
def __del__(self):
self.closeDB()
def openDBIfNecessary(self):
if not self.connection:
if not self.create_if_absent and not os.path.exists(self.file_name):
raise RuntimeError("Weight file doesn't exist")
self.connection = sqlite3.connect(self.file_name)
self.cursor = self.connection.cursor()
def closeDB(self):
if self.connection:
self.connection.close()
self.connection = None
self.cursor = None
def weightEntriesFromResults(self, results, extra, result_callback=None):
weights = []
for result in results:
weight = WeightDBEntry(result[WDBQF.RSID],
result[WDBQF.GENE],
result[WDBQF.WEIGHT],
result[WDBQF.REF_ALLELE],
result[WDBQF.EFF_ALLELE])
weights.append(weight)
if result_callback:
result_callback(weight, extra)
return weights
def loadFromDB(self, callback=None, gene_key=None):
self.openDBIfNecessary()
extra = self.loadExtraColumnData()
extra = {e.gene:e for e in extra}
if gene_key is None:
results = self.cursor.execute("SELECT rsid, gene, weight, ref_allele, eff_allele FROM weights;")
else:
results = self.cursor.execute("SELECT rsid, gene, weight, ref_allele, eff_allele FROM weights where gene = ?;", (gene_key))
weights = self.weightEntriesFromResults(results, extra, callback)
return weights
def loadExtraColumnData(self, gene_key=None):
self.openDBIfNecessary()
try:
if gene_key is None:
results = self.cursor.execute("SELECT gene, genename, `n.snps.in.model`, `pred.perf.R2`, `pred.perf.pval`, `pred.perf.qval` FROM extra;")
else:
results = self.cursor.execute("SELECT gene, genename, `n.snps.in.model`, `pred.perf.R2`, `pred.perf.pval`, `pred.perf.qval` FROM extra WHERE gene = ?;", (gene_key,))
except sqlite3.OperationalError as e:
print(str(e))
raise Exceptions.ReportableException("Could not read input tissue database. Please try updating the tissue model files.")
except Exception as e:
raise e
extra = [GeneEntry(x[WDBEQF.GENE], x[WDBEQF.GENE_NAME], x[WDBEQF.N_SNP_IN_MODEL], x[WDBEQF.PRED_PERF_R2], x[WDBEQF.PRED_PERF_PVAL], x[WDBEQF.PRED_PERF_QVAL]) for x in results]
return extra
def loadGeneNamesFromDB(self):
self.openDBIfNecessary()
names = []
results = self.cursor.execute("SELECT DISTINCT gene FROM weights;")
for result in results:
name = result[0]
names.append(name)
return names
class WeightDBEntryLogic(object):
def __init__(self, db_file_name):
self.weights_by_gene = OrderedDict()#{}
self.genes_for_an_rsid = OrderedDict()#{}
self.gene_data_for_gene = OrderedDict()#{}
self._loadData(db_file_name)
def anEntryWithRSID(self, rsid):
entry = None
if not rsid in self.genes_for_an_rsid:
return entry
genes = self.genes_for_an_rsid[rsid]
gene = genes[0]
weights = self.weights_by_gene[gene]
entry = weights[rsid]
return entry
def _loadData(self, db_file_name):
weights_db = WeightDB(db_file_name)
class ByNameCallback(object):
def __init__(self, weights_by_gene, genes_for_an_rsid, gene_data_for_gene):
self.weights_by_gene = weights_by_gene
self.genes_for_an_rsid = genes_for_an_rsid
self.gene_data_for_gene = gene_data_for_gene
def __call__(self, weight, extra):
if weight.gene in self.weights_by_gene:
weights = self.weights_by_gene[weight.gene]
else:
weights = OrderedDict()
self.weights_by_gene[weight.gene] = weights
weights[weight.rsid]= weight
if not weight.rsid in self.genes_for_an_rsid:
self.genes_for_an_rsid[weight.rsid] = []
genes = self.genes_for_an_rsid[weight.rsid]
if not weight.gene in genes:
genes.append(weight.gene)
gene_entry = extra[weight.gene]
self.gene_data_for_gene[weight.gene] = gene_entry
callback = ByNameCallback(self.weights_by_gene, self.genes_for_an_rsid, self.gene_data_for_gene)
weights_db.loadFromDB(callback)
| true | true |
1c46c9cfeb9efcce9902f255edbe15907ddf263e | 4,994 | py | Python | tests/http/test_fedclient.py | SimmyD/synapse | 26f2f1ca9a8ce6c32e574f0f0e60bb24b773c4e3 | [
"Apache-2.0"
] | null | null | null | tests/http/test_fedclient.py | SimmyD/synapse | 26f2f1ca9a8ce6c32e574f0f0e60bb24b773c4e3 | [
"Apache-2.0"
] | null | null | null | tests/http/test_fedclient.py | SimmyD/synapse | 26f2f1ca9a8ce6c32e574f0f0e60bb24b773c4e3 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2018 New Vector Ltd
#
# 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 mock import Mock
from twisted.internet.defer import TimeoutError
from twisted.internet.error import ConnectingCancelledError, DNSLookupError
from twisted.web.client import ResponseNeverReceived
from synapse.http.matrixfederationclient import MatrixFederationHttpClient
from tests.unittest import HomeserverTestCase
class FederationClientTests(HomeserverTestCase):
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(reactor=reactor, clock=clock)
hs.tls_client_options_factory = None
return hs
def prepare(self, reactor, clock, homeserver):
self.cl = MatrixFederationHttpClient(self.hs)
self.reactor.lookups["testserv"] = "1.2.3.4"
def test_dns_error(self):
"""
If the DNS raising returns an error, it will bubble up.
"""
d = self.cl._request("testserv2:8008", "GET", "foo/bar", timeout=10000)
self.pump()
f = self.failureResultOf(d)
self.assertIsInstance(f.value, DNSLookupError)
def test_client_never_connect(self):
"""
If the HTTP request is not connected and is timed out, it'll give a
ConnectingCancelledError.
"""
d = self.cl._request("testserv:8008", "GET", "foo/bar", timeout=10000)
self.pump()
# Nothing happened yet
self.assertFalse(d.called)
# Make sure treq is trying to connect
clients = self.reactor.tcpClients
self.assertEqual(len(clients), 1)
self.assertEqual(clients[0][0], '1.2.3.4')
self.assertEqual(clients[0][1], 8008)
# Deferred is still without a result
self.assertFalse(d.called)
# Push by enough to time it out
self.reactor.advance(10.5)
f = self.failureResultOf(d)
self.assertIsInstance(f.value, ConnectingCancelledError)
def test_client_connect_no_response(self):
"""
If the HTTP request is connected, but gets no response before being
timed out, it'll give a ResponseNeverReceived.
"""
d = self.cl._request("testserv:8008", "GET", "foo/bar", timeout=10000)
self.pump()
# Nothing happened yet
self.assertFalse(d.called)
# Make sure treq is trying to connect
clients = self.reactor.tcpClients
self.assertEqual(len(clients), 1)
self.assertEqual(clients[0][0], '1.2.3.4')
self.assertEqual(clients[0][1], 8008)
conn = Mock()
client = clients[0][2].buildProtocol(None)
client.makeConnection(conn)
# Deferred is still without a result
self.assertFalse(d.called)
# Push by enough to time it out
self.reactor.advance(10.5)
f = self.failureResultOf(d)
self.assertIsInstance(f.value, ResponseNeverReceived)
def test_client_gets_headers(self):
"""
Once the client gets the headers, _request returns successfully.
"""
d = self.cl._request("testserv:8008", "GET", "foo/bar", timeout=10000)
self.pump()
conn = Mock()
clients = self.reactor.tcpClients
client = clients[0][2].buildProtocol(None)
client.makeConnection(conn)
# Deferred does not have a result
self.assertFalse(d.called)
# Send it the HTTP response
client.dataReceived(b"HTTP/1.1 200 OK\r\nServer: Fake\r\n\r\n")
# We should get a successful response
r = self.successResultOf(d)
self.assertEqual(r.code, 200)
def test_client_headers_no_body(self):
"""
If the HTTP request is connected, but gets no response before being
timed out, it'll give a ResponseNeverReceived.
"""
d = self.cl.post_json("testserv:8008", "foo/bar", timeout=10000)
self.pump()
conn = Mock()
clients = self.reactor.tcpClients
client = clients[0][2].buildProtocol(None)
client.makeConnection(conn)
# Deferred does not have a result
self.assertFalse(d.called)
# Send it the HTTP response
client.dataReceived(
(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
b"Server: Fake\r\n\r\n")
)
# Push by enough to time it out
self.reactor.advance(10.5)
f = self.failureResultOf(d)
self.assertIsInstance(f.value, TimeoutError)
| 31.607595 | 79 | 0.647777 |
from mock import Mock
from twisted.internet.defer import TimeoutError
from twisted.internet.error import ConnectingCancelledError, DNSLookupError
from twisted.web.client import ResponseNeverReceived
from synapse.http.matrixfederationclient import MatrixFederationHttpClient
from tests.unittest import HomeserverTestCase
class FederationClientTests(HomeserverTestCase):
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(reactor=reactor, clock=clock)
hs.tls_client_options_factory = None
return hs
def prepare(self, reactor, clock, homeserver):
self.cl = MatrixFederationHttpClient(self.hs)
self.reactor.lookups["testserv"] = "1.2.3.4"
def test_dns_error(self):
d = self.cl._request("testserv2:8008", "GET", "foo/bar", timeout=10000)
self.pump()
f = self.failureResultOf(d)
self.assertIsInstance(f.value, DNSLookupError)
def test_client_never_connect(self):
d = self.cl._request("testserv:8008", "GET", "foo/bar", timeout=10000)
self.pump()
self.assertFalse(d.called)
clients = self.reactor.tcpClients
self.assertEqual(len(clients), 1)
self.assertEqual(clients[0][0], '1.2.3.4')
self.assertEqual(clients[0][1], 8008)
self.assertFalse(d.called)
self.reactor.advance(10.5)
f = self.failureResultOf(d)
self.assertIsInstance(f.value, ConnectingCancelledError)
def test_client_connect_no_response(self):
d = self.cl._request("testserv:8008", "GET", "foo/bar", timeout=10000)
self.pump()
self.assertFalse(d.called)
clients = self.reactor.tcpClients
self.assertEqual(len(clients), 1)
self.assertEqual(clients[0][0], '1.2.3.4')
self.assertEqual(clients[0][1], 8008)
conn = Mock()
client = clients[0][2].buildProtocol(None)
client.makeConnection(conn)
self.assertFalse(d.called)
self.reactor.advance(10.5)
f = self.failureResultOf(d)
self.assertIsInstance(f.value, ResponseNeverReceived)
def test_client_gets_headers(self):
d = self.cl._request("testserv:8008", "GET", "foo/bar", timeout=10000)
self.pump()
conn = Mock()
clients = self.reactor.tcpClients
client = clients[0][2].buildProtocol(None)
client.makeConnection(conn)
self.assertFalse(d.called)
client.dataReceived(b"HTTP/1.1 200 OK\r\nServer: Fake\r\n\r\n")
r = self.successResultOf(d)
self.assertEqual(r.code, 200)
def test_client_headers_no_body(self):
d = self.cl.post_json("testserv:8008", "foo/bar", timeout=10000)
self.pump()
conn = Mock()
clients = self.reactor.tcpClients
client = clients[0][2].buildProtocol(None)
client.makeConnection(conn)
self.assertFalse(d.called)
client.dataReceived(
(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
b"Server: Fake\r\n\r\n")
)
self.reactor.advance(10.5)
f = self.failureResultOf(d)
self.assertIsInstance(f.value, TimeoutError)
| true | true |
1c46c9e13c1fa6ba1e653f1f33dbebace96b8941 | 1,046 | py | Python | release/stubs.min/Autodesk/Revit/DB/Structure/__init___parts/RebarShapeConstraintSagittaLength.py | htlcnn/ironpython-stubs | 780d829e2104b2789d5f4d6f32b0ec9f2930ca03 | [
"MIT"
] | 182 | 2017-06-27T02:26:15.000Z | 2022-03-30T18:53:43.000Z | release/stubs.min/Autodesk/Revit/DB/Structure/__init___parts/RebarShapeConstraintSagittaLength.py | htlcnn/ironpython-stubs | 780d829e2104b2789d5f4d6f32b0ec9f2930ca03 | [
"MIT"
] | 28 | 2017-06-27T13:38:23.000Z | 2022-03-15T11:19:44.000Z | release/stubs.min/Autodesk/Revit/DB/Structure/__init___parts/RebarShapeConstraintSagittaLength.py | htlcnn/ironpython-stubs | 780d829e2104b2789d5f4d6f32b0ec9f2930ca03 | [
"MIT"
] | 67 | 2017-06-28T09:43:59.000Z | 2022-03-20T21:17:10.000Z | class RebarShapeConstraintSagittaLength(RebarShapeConstraint,IDisposable):
"""
A constraint that can be applied to a RebarShapeDefinitionByArc
and drives the height of the arc.
RebarShapeConstraintSagittaLength(paramId: ElementId)
"""
def Dispose(self):
""" Dispose(self: RebarShapeConstraint,A_0: bool) """
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: RebarShapeConstraint,disposing: bool) """
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,paramId):
""" __new__(cls: type,paramId: ElementId) """
pass
| 34.866667 | 215 | 0.716061 | class RebarShapeConstraintSagittaLength(RebarShapeConstraint,IDisposable):
def Dispose(self):
pass
def ReleaseUnmanagedResources(self,*args):
pass
def __enter__(self,*args):
pass
def __exit__(self,*args):
pass
def __init__(self,*args):
pass
@staticmethod
def __new__(self,paramId):
pass
| true | true |
1c46ca25cd91c0be4a40c520f78d8264149c79a3 | 5,959 | py | Python | tests/unit/streamalert_cli/terraform/test_alert_processor.py | Meliairon/streamalert | 3b774a59d260b2822cd156e837781bd34f3625f7 | [
"Apache-2.0"
] | null | null | null | tests/unit/streamalert_cli/terraform/test_alert_processor.py | Meliairon/streamalert | 3b774a59d260b2822cd156e837781bd34f3625f7 | [
"Apache-2.0"
] | null | null | null | tests/unit/streamalert_cli/terraform/test_alert_processor.py | Meliairon/streamalert | 3b774a59d260b2822cd156e837781bd34f3625f7 | [
"Apache-2.0"
] | null | null | null | """
Copyright 2017-present Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import unittest
from nose.tools import assert_equal
from streamalert_cli.config import CLIConfig
from streamalert_cli.terraform import alert_processor
class TestAlertProcessor(unittest.TestCase):
"""Test the Terraform generation for the alert processor"""
def setUp(self):
"""Create the CLIConfig and the expected template for these tests."""
self.config = dict(CLIConfig(config_path='tests/unit/conf'))
self.alert_proc_config = self.config['lambda']['alert_processor_config']
def test_generate_all_options(self):
"""CLI - Terraform Generate Alert Processor - All Options"""
result = alert_processor.generate_alert_processor(config=self.config)
expected = {
'module': {
'alert_processor_iam': {
'account_id': '12345678910',
'kms_key_arn': '${aws_kms_key.streamalert_secrets.arn}',
'output_lambda_functions': [
'unit_test_function',
'unit_test_qualified_function'
],
'output_s3_buckets': ['unit.test.bucket.name'],
'output_sns_topics': ['unit_test_topic_name'],
'output_sqs_queues': ['unit_test_queue_name'],
'prefix': 'unit-test',
'region': 'us-west-1',
'role_id': '${module.alert_processor_lambda.role_id}',
'source': './modules/tf_alert_processor_iam',
'sse_kms_key_arn': '${aws_kms_key.server_side_encryption.arn}'
},
'alert_processor_lambda': {
'alarm_actions': [
'arn:aws:sns:us-west-1:12345678910:unit-test_streamalert_monitoring'
],
'description': 'Unit-Test Streamalert Alert Processor',
'environment_variables': {
'ALERTS_TABLE': 'unit-test_streamalert_alerts',
'STREAMALERT_PREFIX': 'unit-test',
'AWS_ACCOUNT_ID': '12345678910',
'ENABLE_METRICS': '0',
'LOGGER_LEVEL': 'info'
},
'tags': {},
'errors_alarm_enabled': True,
'errors_alarm_evaluation_periods': 1,
'errors_alarm_period_secs': 2,
'errors_alarm_threshold': 3,
'filename': 'alert_processor.zip',
'function_name': 'unit-test_streamalert_alert_processor',
'handler': 'streamalert.alert_processor.main.handler',
'log_retention_days': 7,
'memory_size_mb': 128,
'source': './modules/tf_lambda',
'throttles_alarm_enabled': True,
'throttles_alarm_evaluation_periods': 4,
'throttles_alarm_period_secs': 5,
'throttles_alarm_threshold': 6,
'timeout_sec': 60,
'vpc_security_group_ids': ['sg-abc'],
'vpc_subnet_ids': ['subnet-123']
}
}
}
assert_equal(expected, result)
def test_generate_minimal_options(self):
"""CLI - Terraform Generate Alert Processor - Minimal Options"""
# Remove extra Lambda options
for key in ['log_level', 'log_retention_days', 'metric_alarms', 'vpc_config']:
del self.alert_proc_config[key]
# Remove all outputs from the config
self.config['outputs'] = {}
result = alert_processor.generate_alert_processor(config=self.config)
expected = {
'module': {
'alert_processor_iam': {
'account_id': '12345678910',
'kms_key_arn': '${aws_kms_key.streamalert_secrets.arn}',
'output_lambda_functions': [],
'output_s3_buckets': [],
'output_sns_topics': [],
'output_sqs_queues': [],
'prefix': 'unit-test',
'region': 'us-west-1',
'role_id': '${module.alert_processor_lambda.role_id}',
'source': './modules/tf_alert_processor_iam',
'sse_kms_key_arn': '${aws_kms_key.server_side_encryption.arn}'
},
'alert_processor_lambda': {
'description': 'Unit-Test Streamalert Alert Processor',
'environment_variables': {
'ALERTS_TABLE': 'unit-test_streamalert_alerts',
'STREAMALERT_PREFIX': 'unit-test',
'AWS_ACCOUNT_ID': '12345678910',
'ENABLE_METRICS': '0',
'LOGGER_LEVEL': 'info'
},
'tags': {},
'filename': 'alert_processor.zip',
'function_name': 'unit-test_streamalert_alert_processor',
'handler': 'streamalert.alert_processor.main.handler',
'memory_size_mb': 128,
'source': './modules/tf_lambda',
'timeout_sec': 60,
}
}
}
assert_equal(expected, result)
| 44.470149 | 92 | 0.538345 | import unittest
from nose.tools import assert_equal
from streamalert_cli.config import CLIConfig
from streamalert_cli.terraform import alert_processor
class TestAlertProcessor(unittest.TestCase):
def setUp(self):
self.config = dict(CLIConfig(config_path='tests/unit/conf'))
self.alert_proc_config = self.config['lambda']['alert_processor_config']
def test_generate_all_options(self):
result = alert_processor.generate_alert_processor(config=self.config)
expected = {
'module': {
'alert_processor_iam': {
'account_id': '12345678910',
'kms_key_arn': '${aws_kms_key.streamalert_secrets.arn}',
'output_lambda_functions': [
'unit_test_function',
'unit_test_qualified_function'
],
'output_s3_buckets': ['unit.test.bucket.name'],
'output_sns_topics': ['unit_test_topic_name'],
'output_sqs_queues': ['unit_test_queue_name'],
'prefix': 'unit-test',
'region': 'us-west-1',
'role_id': '${module.alert_processor_lambda.role_id}',
'source': './modules/tf_alert_processor_iam',
'sse_kms_key_arn': '${aws_kms_key.server_side_encryption.arn}'
},
'alert_processor_lambda': {
'alarm_actions': [
'arn:aws:sns:us-west-1:12345678910:unit-test_streamalert_monitoring'
],
'description': 'Unit-Test Streamalert Alert Processor',
'environment_variables': {
'ALERTS_TABLE': 'unit-test_streamalert_alerts',
'STREAMALERT_PREFIX': 'unit-test',
'AWS_ACCOUNT_ID': '12345678910',
'ENABLE_METRICS': '0',
'LOGGER_LEVEL': 'info'
},
'tags': {},
'errors_alarm_enabled': True,
'errors_alarm_evaluation_periods': 1,
'errors_alarm_period_secs': 2,
'errors_alarm_threshold': 3,
'filename': 'alert_processor.zip',
'function_name': 'unit-test_streamalert_alert_processor',
'handler': 'streamalert.alert_processor.main.handler',
'log_retention_days': 7,
'memory_size_mb': 128,
'source': './modules/tf_lambda',
'throttles_alarm_enabled': True,
'throttles_alarm_evaluation_periods': 4,
'throttles_alarm_period_secs': 5,
'throttles_alarm_threshold': 6,
'timeout_sec': 60,
'vpc_security_group_ids': ['sg-abc'],
'vpc_subnet_ids': ['subnet-123']
}
}
}
assert_equal(expected, result)
def test_generate_minimal_options(self):
for key in ['log_level', 'log_retention_days', 'metric_alarms', 'vpc_config']:
del self.alert_proc_config[key]
self.config['outputs'] = {}
result = alert_processor.generate_alert_processor(config=self.config)
expected = {
'module': {
'alert_processor_iam': {
'account_id': '12345678910',
'kms_key_arn': '${aws_kms_key.streamalert_secrets.arn}',
'output_lambda_functions': [],
'output_s3_buckets': [],
'output_sns_topics': [],
'output_sqs_queues': [],
'prefix': 'unit-test',
'region': 'us-west-1',
'role_id': '${module.alert_processor_lambda.role_id}',
'source': './modules/tf_alert_processor_iam',
'sse_kms_key_arn': '${aws_kms_key.server_side_encryption.arn}'
},
'alert_processor_lambda': {
'description': 'Unit-Test Streamalert Alert Processor',
'environment_variables': {
'ALERTS_TABLE': 'unit-test_streamalert_alerts',
'STREAMALERT_PREFIX': 'unit-test',
'AWS_ACCOUNT_ID': '12345678910',
'ENABLE_METRICS': '0',
'LOGGER_LEVEL': 'info'
},
'tags': {},
'filename': 'alert_processor.zip',
'function_name': 'unit-test_streamalert_alert_processor',
'handler': 'streamalert.alert_processor.main.handler',
'memory_size_mb': 128,
'source': './modules/tf_lambda',
'timeout_sec': 60,
}
}
}
assert_equal(expected, result)
| true | true |
1c46cac18042c8dda9c7d3d35fb6a33fff5a1530 | 4,385 | py | Python | praisetheflesh/praisetheflesh/settings.py | robertraya/portfoliowebsite | 2a27b86c8cbb63a40025ecc35bc286d2f9654adf | [
"CC0-1.0"
] | null | null | null | praisetheflesh/praisetheflesh/settings.py | robertraya/portfoliowebsite | 2a27b86c8cbb63a40025ecc35bc286d2f9654adf | [
"CC0-1.0"
] | null | null | null | praisetheflesh/praisetheflesh/settings.py | robertraya/portfoliowebsite | 2a27b86c8cbb63a40025ecc35bc286d2f9654adf | [
"CC0-1.0"
] | null | null | null | """
Django settings for praisetheflesh project.
Generated by 'django-admin startproject' using Django 3.0.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY', 'Optional default value')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['praisetheflesh.herokuapp.com', '127.0.0.1', 'praisetheflesh.com']
# Application definition
INSTALLED_APPS = [
'praisetheflesh',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'praisetheflesh.praisetheflesh.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'ptf/templates/kyle_gannon'),
os.path.join(BASE_DIR, 'store/templates/store')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'praisetheflesh.praisetheflesh.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_TMP = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
os.makedirs(STATIC_TMP, exist_ok=True)
os.makedirs(STATIC_ROOT, exist_ok=True)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'ptf/static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
#security business
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
#Activate Django-Heroku
django_heroku.settings(locals())
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
},
} | 25.346821 | 91 | 0.697834 |
import os
import django_heroku
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv('SECRET_KEY', 'Optional default value')
DEBUG = False
ALLOWED_HOSTS = ['praisetheflesh.herokuapp.com', '127.0.0.1', 'praisetheflesh.com']
# Application definition
INSTALLED_APPS = [
'praisetheflesh',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'praisetheflesh.praisetheflesh.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'ptf/templates/kyle_gannon'),
os.path.join(BASE_DIR, 'store/templates/store')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'praisetheflesh.praisetheflesh.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_TMP = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
os.makedirs(STATIC_TMP, exist_ok=True)
os.makedirs(STATIC_ROOT, exist_ok=True)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'ptf/static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
#security business
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
#Activate Django-Heroku
django_heroku.settings(locals())
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
},
} | true | true |
1c46cb1e70f734ca59a3951c76d89d67602e1d81 | 2,141 | py | Python | main.py | mzas/j2v | adf63ddd62a356faf845cf7fcb01dbdc81bf163e | [
"Apache-2.0"
] | null | null | null | main.py | mzas/j2v | adf63ddd62a356faf845cf7fcb01dbdc81bf163e | [
"Apache-2.0"
] | null | null | null | main.py | mzas/j2v | adf63ddd62a356faf845cf7fcb01dbdc81bf163e | [
"Apache-2.0"
] | null | null | null | from j2v.generation.processor import MainProcessor
from j2v.utils.config import generator_config
import argparse
import datetime
import time
from j2v.utils.helpers import is_truthy
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--json_files", nargs=argparse.ONE_OR_MORE, type=str, default=[], )
parser.add_argument("--output_view", nargs=argparse.OPTIONAL, type=str,
default=generator_config['OUTPUT_VIEW_ML_OUT_DEFAULT'], )
parser.add_argument("--output_explore", nargs=argparse.OPTIONAL, type=str,
default=generator_config['EXPLORE_LKML_OUT_DEFAULT'], )
parser.add_argument("--column_name", nargs=argparse.OPTIONAL, type=str,
default=generator_config['COLUMN_WITH_JSONS_DEFAULT'], )
parser.add_argument("--sql_table_name", nargs=argparse.OPTIONAL, type=str,
default=generator_config['TABLE_WITH_JSON_COLUMN_DEFAULT'], )
parser.add_argument("--table_alias", nargs=argparse.OPTIONAL, type=str,
default=generator_config['TABLE_ALIAS_DEFAULT'], )
parser.add_argument("--handle_null_values_in_sql", nargs=argparse.OPTIONAL, type=str,
default=generator_config['HANDLE_NULL_VALUES_IN_SQL_DEFAULT'], )
parser.add_argument("--primary_key", nargs=argparse.OPTIONAL, type=str,)
args = parser.parse_args()
p = MainProcessor(column_name=args.column_name, output_explore_file_name=args.output_explore,
output_view_file_name=args.output_view, sql_table_name=args.sql_table_name,
table_alias=args.table_alias, handle_null_values_in_sql=is_truthy(args.handle_null_values_in_sql),
primary_key=args.primary_key)
start_time = time.process_time()
print("{date} Running the generator.\n\n".format(date=datetime.datetime.now()))
p.process_json_files(args.json_files)
end_time = time.process_time()
print("\n\n{date} Finished.".format(date=datetime.datetime.now()))
print("Took {duration:10.1f} ms".format(duration=(end_time - start_time) * 1000))
| 61.171429 | 120 | 0.708547 | from j2v.generation.processor import MainProcessor
from j2v.utils.config import generator_config
import argparse
import datetime
import time
from j2v.utils.helpers import is_truthy
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--json_files", nargs=argparse.ONE_OR_MORE, type=str, default=[], )
parser.add_argument("--output_view", nargs=argparse.OPTIONAL, type=str,
default=generator_config['OUTPUT_VIEW_ML_OUT_DEFAULT'], )
parser.add_argument("--output_explore", nargs=argparse.OPTIONAL, type=str,
default=generator_config['EXPLORE_LKML_OUT_DEFAULT'], )
parser.add_argument("--column_name", nargs=argparse.OPTIONAL, type=str,
default=generator_config['COLUMN_WITH_JSONS_DEFAULT'], )
parser.add_argument("--sql_table_name", nargs=argparse.OPTIONAL, type=str,
default=generator_config['TABLE_WITH_JSON_COLUMN_DEFAULT'], )
parser.add_argument("--table_alias", nargs=argparse.OPTIONAL, type=str,
default=generator_config['TABLE_ALIAS_DEFAULT'], )
parser.add_argument("--handle_null_values_in_sql", nargs=argparse.OPTIONAL, type=str,
default=generator_config['HANDLE_NULL_VALUES_IN_SQL_DEFAULT'], )
parser.add_argument("--primary_key", nargs=argparse.OPTIONAL, type=str,)
args = parser.parse_args()
p = MainProcessor(column_name=args.column_name, output_explore_file_name=args.output_explore,
output_view_file_name=args.output_view, sql_table_name=args.sql_table_name,
table_alias=args.table_alias, handle_null_values_in_sql=is_truthy(args.handle_null_values_in_sql),
primary_key=args.primary_key)
start_time = time.process_time()
print("{date} Running the generator.\n\n".format(date=datetime.datetime.now()))
p.process_json_files(args.json_files)
end_time = time.process_time()
print("\n\n{date} Finished.".format(date=datetime.datetime.now()))
print("Took {duration:10.1f} ms".format(duration=(end_time - start_time) * 1000))
| true | true |
1c46cd2745257059eee9d1a34c553a3af73b903b | 799 | py | Python | profiles_api/migrations/0003_profilefeeditem.py | AbdElRahman24597/profiles-rest-api | 4fd19af745b015b234f9382276b1ac75aaca7a26 | [
"MIT"
] | null | null | null | profiles_api/migrations/0003_profilefeeditem.py | AbdElRahman24597/profiles-rest-api | 4fd19af745b015b234f9382276b1ac75aaca7a26 | [
"MIT"
] | null | null | null | profiles_api/migrations/0003_profilefeeditem.py | AbdElRahman24597/profiles-rest-api | 4fd19af745b015b234f9382276b1ac75aaca7a26 | [
"MIT"
] | null | null | null | # Generated by Django 2.2 on 2021-04-30 14:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles_api', '0002_auto_20210428_1320'),
]
operations = [
migrations.CreateModel(
name='ProfileFeedItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status_text', models.CharField(max_length=255)),
('created_on', models.DateTimeField(auto_now_add=True)),
('user_profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| 31.96 | 126 | 0.638298 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles_api', '0002_auto_20210428_1320'),
]
operations = [
migrations.CreateModel(
name='ProfileFeedItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status_text', models.CharField(max_length=255)),
('created_on', models.DateTimeField(auto_now_add=True)),
('user_profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| true | true |
1c46cdeac23e702966e16a34fc97f70d095e595d | 3,325 | py | Python | continue.py | shivam-kotwalia/KittiSeg | 598ae9f4f797b850001eea1dbb270e128bb78d7d | [
"MIT"
] | 11 | 2017-06-06T21:18:24.000Z | 2019-11-04T14:58:10.000Z | continue.py | rgalvaomesquita/KittiSeg | ac93c2f0f83bf84f2ba0d645f819b2bbeeeaf58d | [
"MIT-0",
"MIT"
] | null | null | null | continue.py | rgalvaomesquita/KittiSeg | ac93c2f0f83bf84f2ba0d645f819b2bbeeeaf58d | [
"MIT-0",
"MIT"
] | 5 | 2017-04-28T09:08:54.000Z | 2020-04-10T23:58:48.000Z | """
Trains, evaluates and saves the KittiSeg model.
-------------------------------------------------
The MIT License (MIT)
Copyright (c) 2017 Marvin Teichmann
More details: https://github.com/MarvinTeichmann/KittiSeg/blob/master/LICENSE
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import commentjson
import logging
import os
import sys
import collections
def dict_merge(dct, merge_dct):
""" Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
updating only top-level keys, dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
``dct``.
:param dct: dict onto which the merge is executed
:param merge_dct: dct merged into dct
:return: None
"""
for k, v in merge_dct.iteritems():
if (k in dct and isinstance(dct[k], dict) and
isinstance(merge_dct[k], collections.Mapping)):
dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]
# configure logging
if 'TV_IS_DEV' in os.environ and os.environ['TV_IS_DEV']:
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
stream=sys.stdout)
else:
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
stream=sys.stdout)
# https://github.com/tensorflow/tensorflow/issues/2034#issuecomment-220820070
import numpy as np
flags = tf.app.flags
FLAGS = flags.FLAGS
sys.path.insert(1, 'incl')
import tensorvision.train as train
import tensorvision.utils as utils
flags.DEFINE_string('name', None,
'Append a name Tag to run.')
flags.DEFINE_string('project', None,
'Append a name Tag to run.')
flags.DEFINE_string('logdir', None,
'File storing model parameters.')
flags.DEFINE_string('mod', None,
'Modifier for model parameters.')
if 'TV_SAVE' in os.environ and os.environ['TV_SAVE']:
tf.app.flags.DEFINE_boolean(
'save', True, ('Whether to save the run. In case --nosave (default) '
'output will be saved to the folder TV_DIR_RUNS/debug, '
'hence it will get overwritten by further runs.'))
else:
tf.app.flags.DEFINE_boolean(
'save', True, ('Whether to save the run. In case --nosave (default) '
'output will be saved to the folder TV_DIR_RUNS/debug '
'hence it will get overwritten by further runs.'))
def main(_):
utils.set_gpus_to_use()
try:
import tensorvision.train
import tensorflow_fcn.utils
except ImportError:
logging.error("Could not import the submodules.")
logging.error("Please execute:"
"'git submodule update --init --recursive'")
exit(1)
if tf.app.flags.FLAGS.logdir is None:
logging.error("No logdir is given.")
logging.info("Usage: python train.py --logdir dir")
exit(1)
logging.info("Continuing training...")
train.continue_training(tf.app.flags.FLAGS.logdir)
if __name__ == '__main__':
tf.app.run()
| 29.954955 | 79 | 0.628872 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import commentjson
import logging
import os
import sys
import collections
def dict_merge(dct, merge_dct):
for k, v in merge_dct.iteritems():
if (k in dct and isinstance(dct[k], dict) and
isinstance(merge_dct[k], collections.Mapping)):
dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]
if 'TV_IS_DEV' in os.environ and os.environ['TV_IS_DEV']:
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
stream=sys.stdout)
else:
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
stream=sys.stdout)
ags = tf.app.flags
FLAGS = flags.FLAGS
sys.path.insert(1, 'incl')
import tensorvision.train as train
import tensorvision.utils as utils
flags.DEFINE_string('name', None,
'Append a name Tag to run.')
flags.DEFINE_string('project', None,
'Append a name Tag to run.')
flags.DEFINE_string('logdir', None,
'File storing model parameters.')
flags.DEFINE_string('mod', None,
'Modifier for model parameters.')
if 'TV_SAVE' in os.environ and os.environ['TV_SAVE']:
tf.app.flags.DEFINE_boolean(
'save', True, ('Whether to save the run. In case --nosave (default) '
'output will be saved to the folder TV_DIR_RUNS/debug, '
'hence it will get overwritten by further runs.'))
else:
tf.app.flags.DEFINE_boolean(
'save', True, ('Whether to save the run. In case --nosave (default) '
'output will be saved to the folder TV_DIR_RUNS/debug '
'hence it will get overwritten by further runs.'))
def main(_):
utils.set_gpus_to_use()
try:
import tensorvision.train
import tensorflow_fcn.utils
except ImportError:
logging.error("Could not import the submodules.")
logging.error("Please execute:"
"'git submodule update --init --recursive'")
exit(1)
if tf.app.flags.FLAGS.logdir is None:
logging.error("No logdir is given.")
logging.info("Usage: python train.py --logdir dir")
exit(1)
logging.info("Continuing training...")
train.continue_training(tf.app.flags.FLAGS.logdir)
if __name__ == '__main__':
tf.app.run()
| true | true |
1c46cf40bbac327ea35c8b14b39b6f7814418ca2 | 52,022 | py | Python | spikeinterface/sortingcomponents/template_matching.py | scratchrealm/spikeinterface | 17cfcd6f0c30c9933c11e560daf750366e12a151 | [
"MIT"
] | null | null | null | spikeinterface/sortingcomponents/template_matching.py | scratchrealm/spikeinterface | 17cfcd6f0c30c9933c11e560daf750366e12a151 | [
"MIT"
] | null | null | null | spikeinterface/sortingcomponents/template_matching.py | scratchrealm/spikeinterface | 17cfcd6f0c30c9933c11e560daf750366e12a151 | [
"MIT"
] | null | null | null | """Sorting components: template matching."""
import numpy as np
import scipy.spatial
from tqdm import tqdm
import sklearn, scipy
import scipy
from threadpoolctl import threadpool_limits
try:
import numba
from numba import jit, prange
HAVE_NUMBA = True
except ImportError:
HAVE_NUMBA = False
from spikeinterface.core import WaveformExtractor
from spikeinterface.core.job_tools import ChunkRecordingExecutor
from spikeinterface.toolkit import (get_noise_levels, get_template_channel_sparsity,
get_channel_distances, get_chunk_with_margin, get_template_extremum_channel, get_random_data_chunks)
from spikeinterface.sortingcomponents.peak_detection import detect_peak_locally_exclusive, detect_peaks_by_channel
from sklearn.feature_extraction.image import extract_patches_2d, reconstruct_from_patches_2d
from sklearn.linear_model import orthogonal_mp_gram
potrs, = scipy.linalg.get_lapack_funcs(('potrs',), dtype=np.float32)
nrm2, = scipy.linalg.get_blas_funcs(('nrm2', ), dtype=np.float32)
spike_dtype = [('sample_ind', 'int64'), ('channel_ind', 'int64'), ('cluster_ind', 'int64'),
('amplitude', 'float64'), ('segment_ind', 'int64')]
def find_spikes_from_templates(recording, method='naive', method_kwargs={}, extra_outputs=False,
**job_kwargs):
"""Find spike from a recording from given templates.
Parameters
----------
recording: RecordingExtractor
The recording extractor object
waveform_extractor: WaveformExtractor
The waveform extractor
method: str
Which method to use ('naive' | 'tridesclous' | 'circus')
method_kwargs: dict, optional
Keyword arguments for the chosen method
extra_outputs: bool
If True then method_kwargs is also return
job_kwargs: dict
Parameters for ChunkRecordingExecutor
Returns
-------
spikes: ndarray
Spikes found from templates.
method_kwargs:
Optionaly returns for debug purpose.
Notes
-----
Templates are represented as WaveformExtractor so statistics can be extracted.
"""
assert method in template_matching_methods
method_class = template_matching_methods[method]
# initialize
method_kwargs = method_class.initialize_and_check_kwargs(recording, method_kwargs)
# add
method_kwargs['margin'] = method_class.get_margin(recording, method_kwargs)
# serialiaze for worker
method_kwargs_seralized = method_class.serialize_method_kwargs(method_kwargs)
# and run
func = _find_spikes_chunk
init_func = _init_worker_find_spikes
init_args = (recording.to_dict(), method, method_kwargs_seralized)
processor = ChunkRecordingExecutor(recording, func, init_func, init_args,
handle_returns=True, job_name=f'find spikes ({method})', **job_kwargs)
spikes = processor.run()
spikes = np.concatenate(spikes)
if extra_outputs:
return spikes, method_kwargs
else:
return spikes
def _init_worker_find_spikes(recording, method, method_kwargs):
"""Initialize worker for finding spikes."""
if isinstance(recording, dict):
from spikeinterface.core import load_extractor
recording = load_extractor(recording)
method_class = template_matching_methods[method]
method_kwargs = method_class.unserialize_in_worker(method_kwargs)
# create a local dict per worker
worker_ctx = {}
worker_ctx['recording'] = recording
worker_ctx['method'] = method
worker_ctx['method_kwargs'] = method_kwargs
worker_ctx['function'] = method_class.main_function
return worker_ctx
def _find_spikes_chunk(segment_index, start_frame, end_frame, worker_ctx):
"""Find spikes from a chunk of data."""
# recover variables of the worker
recording = worker_ctx['recording']
method = worker_ctx['method']
method_kwargs = worker_ctx['method_kwargs']
margin = method_kwargs['margin']
# load trace in memory given some margin
recording_segment = recording._recording_segments[segment_index]
traces, left_margin, right_margin = get_chunk_with_margin(recording_segment,
start_frame, end_frame, None, margin, add_zeros=True)
function = worker_ctx['function']
with threadpool_limits(limits=1):
spikes = function(traces, method_kwargs)
# remove spikes in margin
if margin > 0:
keep = (spikes['sample_ind'] >= margin) & (spikes['sample_ind'] < (traces.shape[0] - margin))
spikes = spikes[keep]
spikes['sample_ind'] += (start_frame - margin)
spikes['segment_ind'] = segment_index
return spikes
# generic class for template engine
class BaseTemplateMatchingEngine:
default_params = {}
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
"""This function runs before loops"""
# need to be implemented in subclass
raise NotImplementedError
@classmethod
def serialize_method_kwargs(cls, kwargs):
"""This function serializes kwargs to distribute them to workers"""
# need to be implemented in subclass
raise NotImplementedError
@classmethod
def unserialize_in_worker(cls, recording, kwargs):
"""This function unserializes kwargs in workers"""
# need to be implemented in subclass
raise NotImplementedError
@classmethod
def get_margin(cls, recording, kwargs):
# need to be implemented in subclass
raise NotImplementedError
@classmethod
def main_function(cls, traces, method_kwargs):
"""This function returns the number of samples for the chunk margins"""
# need to be implemented in subclass
raise NotImplementedError
##################
# naive matching #
##################
class NaiveMatching(BaseTemplateMatchingEngine):
"""
This is a naive template matching that does not resolve collision
and does not take in account sparsity.
It just minimizes the distance to templates for detected peaks.
It is implemented for benchmarking against this low quality template matching.
And also as an example how to deal with methods_kwargs, margin, intit, func, ...
"""
default_params = {
'waveform_extractor': None,
'peak_sign': 'neg',
'n_shifts': 10,
'detect_threshold': 5,
'noise_levels': None,
'local_radius_um': 100,
'random_chunk_kwargs': {},
}
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
d = cls.default_params.copy()
d.update(kwargs)
assert d['waveform_extractor'] is not None
we = d['waveform_extractor']
if d['noise_levels'] is None:
d['noise_levels'] = get_noise_levels(recording, **d['random_chunk_kwargs'])
d['abs_threholds'] = d['noise_levels'] * d['detect_threshold']
channel_distance = get_channel_distances(recording)
d['neighbours_mask'] = channel_distance < d['local_radius_um']
d['nbefore'] = we.nbefore
d['nafter'] = we.nafter
return d
@classmethod
def get_margin(cls, recording, kwargs):
margin = max(kwargs['nbefore'], kwargs['nafter'])
return margin
@classmethod
def serialize_method_kwargs(cls, kwargs):
kwargs = dict(kwargs)
waveform_extractor = kwargs['waveform_extractor']
kwargs['waveform_extractor'] = str(waveform_extractor.folder)
return kwargs
@classmethod
def unserialize_in_worker(cls, kwargs):
we = kwargs['waveform_extractor']
if isinstance(we, str):
we = WaveformExtractor.load_from_folder(we)
kwargs['waveform_extractor'] = we
templates = we.get_all_templates(mode='average')
kwargs['templates'] = templates
return kwargs
@classmethod
def main_function(cls, traces, method_kwargs):
peak_sign = method_kwargs['peak_sign']
abs_threholds = method_kwargs['abs_threholds']
n_shifts = method_kwargs['n_shifts']
neighbours_mask = method_kwargs['neighbours_mask']
templates = method_kwargs['templates']
nbefore = method_kwargs['nbefore']
nafter = method_kwargs['nafter']
margin = method_kwargs['margin']
if margin > 0:
peak_traces = traces[margin:-margin, :]
else:
peak_traces = traces
peak_sample_ind, peak_chan_ind = detect_peak_locally_exclusive(peak_traces, peak_sign, abs_threholds, n_shifts, neighbours_mask)
peak_sample_ind += margin
spikes = np.zeros(peak_sample_ind.size, dtype=spike_dtype)
spikes['sample_ind'] = peak_sample_ind
spikes['channel_ind'] = peak_chan_ind # TODO need to put the channel from template
# naively take the closest template
for i in range(peak_sample_ind.size):
i0 = peak_sample_ind[i] - nbefore
i1 = peak_sample_ind[i] + nafter
wf = traces[i0:i1, :]
dist = np.sum(np.sum((templates - wf[None, : , :])**2, axis=1), axis=1)
cluster_ind = np.argmin(dist)
spikes['cluster_ind'][i] = cluster_ind
spikes['amplitude'][i] = 0.
return spikes
######################
# tridesclous peeler #
######################
class TridesclousPeeler(BaseTemplateMatchingEngine):
"""
Template-matching ported from Tridesclous sorter.
The idea of this peeler is pretty simple.
1. Find peaks
2. order by best amplitues
3. find nearest template
4. remove it from traces.
5. in the residual find peaks again
This method is quite fast but don't give exelent results to resolve
spike collision when templates have high similarity.
"""
default_params = {
'waveform_extractor': None,
'peak_sign': 'neg',
'peak_shift_ms': 0.2,
'detect_threshold': 5,
'noise_levels': None,
'local_radius_um': 100,
'num_closest' : 5,
'sample_shift': 3,
'ms_before': 0.8,
'ms_after': 1.2,
'num_peeler_loop': 2,
'num_template_try' : 1,
}
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
assert HAVE_NUMBA
d = cls.default_params.copy()
d.update(kwargs)
assert isinstance(d['waveform_extractor'], WaveformExtractor)
we = d['waveform_extractor']
unit_ids = we.sorting.unit_ids
channel_ids = we.recording.channel_ids
sr = we.recording.get_sampling_frequency()
# TODO load as sharedmem
templates = we.get_all_templates(mode='average')
d['templates'] = templates
d['nbefore'] = we.nbefore
d['nafter'] = we.nafter
nbefore_short = int(d['ms_before'] * sr / 1000.)
nafter_short = int(d['ms_before'] * sr / 1000.)
assert nbefore_short <= we.nbefore
assert nafter_short <= we.nafter
d['nbefore_short'] = nbefore_short
d['nafter_short'] = nafter_short
s0 = (we.nbefore - nbefore_short)
s1 = -(we.nafter - nafter_short)
if s1 == 0:
s1 = None
templates_short = templates[:, slice(s0,s1), :].copy()
d['templates_short'] = templates_short
d['peak_shift'] = int(d['peak_shift_ms'] / 1000 * sr)
if d['noise_levels'] is None:
print('TridesclousPeeler : noise should be computed outside')
d['noise_levels'] = get_noise_levels(recording)
d['abs_threholds'] = d['noise_levels'] * d['detect_threshold']
channel_distance = get_channel_distances(recording)
d['neighbours_mask'] = channel_distance < d['local_radius_um']
#
#~ template_sparsity_inds = get_template_channel_sparsity(we, method='radius',
#~ peak_sign=d['peak_sign'], outputs='index', radius_um=d['local_radius_um'])
template_sparsity_inds = get_template_channel_sparsity(we, method='threshold',
peak_sign=d['peak_sign'], outputs='index', threshold=d['detect_threshold'])
template_sparsity = np.zeros((unit_ids.size, channel_ids.size), dtype='bool')
for unit_index, unit_id in enumerate(unit_ids):
chan_inds = template_sparsity_inds[unit_id]
template_sparsity[unit_index, chan_inds] = True
d['template_sparsity'] = template_sparsity
extremum_channel = get_template_extremum_channel(we, peak_sign=d['peak_sign'], outputs='index')
# as numpy vector
extremum_channel = np.array([extremum_channel[unit_id] for unit_id in unit_ids], dtype='int64')
d['extremum_channel'] = extremum_channel
channel_locations = we.recording.get_channel_locations()
# TODO try it with real locaion
unit_locations = channel_locations[extremum_channel]
#~ print(unit_locations)
# distance between units
unit_distances = scipy.spatial.distance.cdist(unit_locations, unit_locations, metric='euclidean')
# seach for closet units and unitary discriminant vector
closest_units = []
for unit_ind, unit_id in enumerate(unit_ids):
order = np.argsort(unit_distances[unit_ind, :])
closest_u = np.arange(unit_ids.size)[order].tolist()
closest_u.remove(unit_ind)
closest_u = np.array(closest_u[:d['num_closest']])
# compute unitary discriminent vector
chans, = np.nonzero(d['template_sparsity'][unit_ind, :])
template_sparse = templates[unit_ind, :, :][:, chans]
closest_vec = []
# against N closets
for u in closest_u:
vec = (templates[u, :, :][:, chans] - template_sparse)
vec /= np.sum(vec ** 2)
closest_vec.append((u, vec))
# against noise
closest_vec.append((None, - template_sparse / np.sum(template_sparse ** 2)))
closest_units.append(closest_vec)
d['closest_units'] = closest_units
# distance channel from unit
distances = scipy.spatial.distance.cdist(channel_locations, unit_locations, metric='euclidean')
near_cluster_mask = distances < d['local_radius_um']
# nearby cluster for each channel
possible_clusters_by_channel = []
for channel_ind in range(distances.shape[0]):
cluster_inds, = np.nonzero(near_cluster_mask[channel_ind, :])
possible_clusters_by_channel.append(cluster_inds)
d['possible_clusters_by_channel'] = possible_clusters_by_channel
d['possible_shifts'] = np.arange(-d['sample_shift'], d['sample_shift'] +1, dtype='int64')
return d
@classmethod
def serialize_method_kwargs(cls, kwargs):
kwargs = dict(kwargs)
# remove waveform_extractor
kwargs.pop('waveform_extractor')
return kwargs
@classmethod
def unserialize_in_worker(cls, kwargs):
return kwargs
@classmethod
def get_margin(cls, recording, kwargs):
margin = 2 * (kwargs['nbefore'] + kwargs['nafter'])
return margin
@classmethod
def main_function(cls, traces, d):
traces = traces.copy()
all_spikes = []
level = 0
while True:
spikes = _tdc_find_spikes(traces, d, level=level)
keep = (spikes['cluster_ind'] >= 0)
if not np.any(keep):
break
all_spikes.append(spikes[keep])
level += 1
if level == d['num_peeler_loop']:
break
if len(all_spikes) > 0:
all_spikes = np.concatenate(all_spikes)
order = np.argsort(all_spikes['sample_ind'])
all_spikes = all_spikes[order]
else:
all_spikes = np.zeros(0, dtype=spike_dtype)
return all_spikes
def _tdc_find_spikes(traces, d, level=0):
peak_sign = d['peak_sign']
templates = d['templates']
templates_short = d['templates_short']
margin = d['margin']
possible_clusters_by_channel = d['possible_clusters_by_channel']
peak_traces = traces[margin // 2:-margin // 2, :]
peak_sample_ind, peak_chan_ind = detect_peak_locally_exclusive(peak_traces, peak_sign,
d['abs_threholds'], d['peak_shift'], d['neighbours_mask'])
peak_sample_ind += margin // 2
peak_amplitude = traces[peak_sample_ind, peak_chan_ind]
order = np.argsort(np.abs(peak_amplitude))[::-1]
peak_sample_ind = peak_sample_ind[order]
peak_chan_ind = peak_chan_ind[order]
spikes = np.zeros(peak_sample_ind.size, dtype=spike_dtype)
spikes['sample_ind'] = peak_sample_ind
spikes['channel_ind'] = peak_chan_ind # TODO need to put the channel from template
possible_shifts = d['possible_shifts']
distances_shift = np.zeros(possible_shifts.size)
for i in range(peak_sample_ind.size):
sample_ind = peak_sample_ind[i]
chan_ind = peak_chan_ind[i]
possible_clusters = possible_clusters_by_channel[chan_ind]
if possible_clusters.size > 0:
#~ s0 = sample_ind - d['nbefore']
#~ s1 = sample_ind + d['nafter']
#~ wf = traces[s0:s1, :]
s0 = sample_ind - d['nbefore_short']
s1 = sample_ind + d['nafter_short']
wf_short = traces[s0:s1, :]
## pure numpy with cluster spasity
# distances = np.sum(np.sum((templates[possible_clusters, :, :] - wf[None, : , :])**2, axis=1), axis=1)
## pure numpy with cluster+channel spasity
# union_channels, = np.nonzero(np.any(d['template_sparsity'][possible_clusters, :], axis=0))
# distances = np.sum(np.sum((templates[possible_clusters][:, :, union_channels] - wf[: , union_channels][None, : :])**2, axis=1), axis=1)
## numba with cluster+channel spasity
union_channels = np.any(d['template_sparsity'][possible_clusters, :], axis=0)
# distances = numba_sparse_dist(wf, templates, union_channels, possible_clusters)
distances = numba_sparse_dist(wf_short, templates_short, union_channels, possible_clusters)
# DEBUG
#~ ind = np.argmin(distances)
#~ cluster_ind = possible_clusters[ind]
for ind in np.argsort(distances)[:d['num_template_try']]:
cluster_ind = possible_clusters[ind]
chan_sparsity = d['template_sparsity'][cluster_ind, :]
template_sparse = templates[cluster_ind, :, :][:, chan_sparsity]
# find best shift
## pure numpy version
# for s, shift in enumerate(possible_shifts):
# wf_shift = traces[s0 + shift: s1 + shift, chan_sparsity]
# distances_shift[s] = np.sum((template_sparse - wf_shift)**2)
# ind_shift = np.argmin(distances_shift)
# shift = possible_shifts[ind_shift]
## numba version
numba_best_shift(traces, templates[cluster_ind, :, :], sample_ind, d['nbefore'], possible_shifts, distances_shift, chan_sparsity)
ind_shift = np.argmin(distances_shift)
shift = possible_shifts[ind_shift]
sample_ind = sample_ind + shift
s0 = sample_ind - d['nbefore']
s1 = sample_ind + d['nafter']
wf_sparse = traces[s0:s1, chan_sparsity]
# accept or not
centered = wf_sparse - template_sparse
accepted = True
for other_ind, other_vector in d['closest_units'][cluster_ind]:
v = np.sum(centered * other_vector)
if np.abs(v) >0.5:
accepted = False
break
if accepted:
#~ if ind != np.argsort(distances)[0]:
#~ print('not first one', np.argsort(distances), ind)
break
if accepted:
amplitude = 1.
# remove template
template = templates[cluster_ind, :, :]
s0 = sample_ind - d['nbefore']
s1 = sample_ind + d['nafter']
traces[s0:s1, :] -= template * amplitude
else:
cluster_ind = -1
amplitude = 0.
else:
cluster_ind = -1
amplitude = 0.
spikes['cluster_ind'][i] = cluster_ind
spikes['amplitude'][i] =amplitude
return spikes
if HAVE_NUMBA:
@jit(nopython=True)
def numba_sparse_dist(wf, templates, union_channels, possible_clusters):
"""
numba implementation that compute distance from template with sparsity
handle by two separate vectors
"""
total_cluster, width, num_chan = templates.shape
num_cluster = possible_clusters.shape[0]
distances = np.zeros((num_cluster,), dtype=np.float32)
for i in prange(num_cluster):
cluster_ind = possible_clusters[i]
sum_dist = 0.
for chan_ind in range(num_chan):
if union_channels[chan_ind]:
for s in range(width):
v = wf[s, chan_ind]
t = templates[cluster_ind, s, chan_ind]
sum_dist += (v - t) ** 2
distances[i] = sum_dist
return distances
@jit(nopython=True)
def numba_best_shift(traces, template, sample_ind, nbefore, possible_shifts, distances_shift, chan_sparsity):
"""
numba implementation to compute several sample shift before template substraction
"""
width, num_chan = template.shape
n_shift = possible_shifts.size
for i in range(n_shift):
shift = possible_shifts[i]
sum_dist = 0.
for chan_ind in range(num_chan):
if chan_sparsity[chan_ind]:
for s in range(width):
v = traces[sample_ind - nbefore + s +shift, chan_ind]
t = template[s, chan_ind]
sum_dist += (v - t) ** 2
distances_shift[i] = sum_dist
return distances_shift
#################
# Circus peeler #
#################
# if HAVE_NUMBA:
# @jit(nopython=True)
# def fastconvolution(traces, templates, output):
# nb_time, nb_channels = traces.shape
# nb_templates, nb_samples, nb_channels = templates.shape
# center = nb_samples // 2
# for i in range(center, nb_time - center + 1):
# offset_1 = i - center
# for k in range(nb_templates):
# for jj in range(nb_samples):
# offset_2 = offset_1 + jj
# for j in range(nb_channels):
# output[k, offset_1] += (templates[k, jj, j] * traces[offset_2, j])
# return output
class CircusOMPPeeler(BaseTemplateMatchingEngine):
"""
Orthogonal Matching Pursuit inspired from Spyking Circus sorter
https://elifesciences.org/articles/34518
This is an Orthogonal Template Matching algorithm. For speed and
memory optimization, templates are automatically sparsified if the
density of the matrix falls below a given threshold. Signal is
convolved with the templates, and as long as some scalar products
are higher than a given threshold, we use a Cholesky decomposition
to compute the optimal amplitudes needed to reconstruct the signal.
IMPORTANT NOTE: small chunks are more efficient for such Peeler,
consider using 100ms chunk
Parameters
----------
noise_levels: array
The noise levels, for every channels
random_chunk_kwargs: dict
Parameters for computing noise levels, if not provided (sub optimal)
amplitude: tuple
(Minimal, Maximal) amplitudes allowed for every template
omp_min_sps: float
Stopping criteria of the OMP algorithm, in percentage of the norm
sparsify_threshold: float
Templates are sparsified in order to keep only the channels necessary
to explain a given fraction of the total norm
use_sparse_matrix_threshold: float
If density of the templates is below a given threshold, sparse matrix
are used (memory efficient)
progress_bar_steps: bool
In order to display or not steps from the algorithm
-----
"""
_default_params = {
'sparsify_threshold': 0.99,
'amplitudes' : [0.5, 1.5],
'use_sparse_matrix_threshold' : 0.25,
'noise_levels': None,
'random_chunk_kwargs': {},
'omp_min_sps' : 0.5,
'progess_bar_steps' : False,
}
@classmethod
def _sparsify_template(cls, template, sparsify_threshold, noise_levels):
is_silent = template.std(0) < 0.25*noise_levels
template[:, is_silent] = 0
channel_norms = np.linalg.norm(template, axis=0)**2
total_norm = np.linalg.norm(template)**2
idx = np.argsort(channel_norms)[::-1]
explained_norms = np.cumsum(channel_norms[idx]/total_norm)
channel = np.searchsorted(explained_norms, sparsify_threshold)
active_channels = np.sort(idx[:channel])
template[:, idx[channel:]] = 0
return template, active_channels
@classmethod
def _prepare_templates(cls, d):
waveform_extractor = d['waveform_extractor']
nb_samples = d['nb_samples']
nb_channels = d['nb_channels']
nb_templates = d['nb_templates']
use_sparse_matrix_threshold = d['use_sparse_matrix_threshold']
d['norms'] = np.zeros(nb_templates, dtype=np.float32)
all_units = list(d['waveform_extractor'].sorting.unit_ids)
templates = waveform_extractor.get_all_templates(mode='median').copy()
d['sparsities'] = {}
for count, unit_id in enumerate(all_units):
templates[count], active_channels = cls._sparsify_template(templates[count], d['sparsify_threshold'], d['noise_levels'])
d['sparsities'][count] = active_channels
d['norms'][count] = np.linalg.norm(templates[count])
templates[count] /= d['norms'][count]
templates = templates.reshape(nb_templates, -1)
nnz = np.sum(templates != 0)/(nb_templates * nb_samples * nb_channels)
if nnz <= use_sparse_matrix_threshold:
templates = scipy.sparse.csr_matrix(templates)
print(f'Templates are automatically sparsified (sparsity level is {nnz})')
d['is_dense'] = False
else:
d['is_dense'] = True
d['templates'] = templates
return d
@classmethod
def _prepare_overlaps(cls, d):
templates = d['templates']
nb_samples = d['nb_samples']
nb_channels = d['nb_channels']
nb_templates = d['nb_templates']
is_dense = d['is_dense']
if not is_dense:
dense_templates = templates.toarray()
else:
dense_templates = templates
dense_templates = dense_templates.reshape(nb_templates, nb_samples, nb_channels)
size = 2 * nb_samples - 1
all_delays = list(range(nb_samples))
if d['progess_bar_steps']:
all_delays = tqdm(all_delays, desc='[1] compute overlaps')
overlaps = {}
for delay in all_delays:
source = dense_templates[:, :delay, :].reshape(nb_templates, -1)
target = dense_templates[:, nb_samples-delay:, :].reshape(nb_templates, -1)
if delay > 0:
overlaps[delay] = scipy.sparse.csr_matrix(source.dot(target.T))
else:
overlaps[delay] = scipy.sparse.csr_matrix((nb_templates, nb_templates), dtype=np.float32)
if delay < nb_samples:
overlaps[size - delay-1] = overlaps[delay].T.tocsr()
new_overlaps = []
for i in range(nb_templates):
data = [overlaps[j][i, :].T for j in range(size)]
data = scipy.sparse.hstack(data)
new_overlaps += [data]
d['overlaps'] = new_overlaps
return d
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
d = cls._default_params.copy()
d.update(kwargs)
assert isinstance(d['waveform_extractor'], WaveformExtractor)
for v in ['sparsify_threshold', 'omp_min_sps','use_sparse_matrix_threshold']:
assert (d[v] >= 0) and (d[v] <= 1), f'{v} should be in [0, 1]'
if d['noise_levels'] is None:
print('CircusOMPPeeler : noise should be computed outside')
d['noise_levels'] = get_noise_levels(recording, **d['random_chunk_kwargs'])
d['nb_channels'] = d['waveform_extractor'].recording.get_num_channels()
d['nb_samples'] = d['waveform_extractor'].nsamples
d['nb_templates'] = len(d['waveform_extractor'].sorting.unit_ids)
d['nbefore'] = d['waveform_extractor'].nbefore
d['nafter'] = d['waveform_extractor'].nafter
d = cls._prepare_templates(d)
d = cls._prepare_overlaps(d)
return d
@classmethod
def serialize_method_kwargs(cls, kwargs):
kwargs = dict(kwargs)
# remove waveform_extractor
kwargs.pop('waveform_extractor')
return kwargs
@classmethod
def unserialize_in_worker(cls, kwargs):
return kwargs
@classmethod
def get_margin(cls, recording, kwargs):
margin = 2 * max(kwargs['nbefore'], kwargs['nafter'])
return margin
@classmethod
def main_function(cls, traces, d):
templates = d['templates']
nb_templates = d['nb_templates']
nb_channels = d['nb_channels']
overlaps = d['overlaps']
margin = d['margin']
norms = d['norms']
nbefore = d['nbefore']
nafter = d['nafter']
omp_tol = np.finfo(np.float32).eps
omp_min_sps = d['omp_min_sps']
nb_samples = d['nafter'] + d['nbefore']
neighbor_window = nb_samples - 1
min_amplitude, max_amplitude = d['amplitudes']
sparsities = d['sparsities']
is_dense = d['is_dense']
stop_criteria = omp_min_sps * norms[:, np.newaxis]
nb_peaks = len(traces) - nb_samples + 1
if is_dense:
kernel_filters = templates.reshape(nb_templates, nb_samples, nb_channels)[:, ::-1, :]
scalar_products = scipy.signal.fftconvolve(kernel_filters, traces[np.newaxis, :, :], axes=(0, 1), mode='valid').sum(2)
else:
scalar_products = np.empty((nb_templates, nb_peaks), dtype=np.float32)
for i in range(nb_templates):
kernel_filter = templates[i].toarray().reshape(nb_samples, nb_channels)
kernel_filter = kernel_filter[::-1, sparsities[i]]
convolution = scipy.signal.fftconvolve(kernel_filter, traces[:, sparsities[i]], axes=0, mode='valid')
if len(convolution) > 0:
scalar_products[i] = convolution.sum(1)
else:
scalar_products[i] = 0
peak_chan_ind = np.zeros(nb_peaks)
nb_spikes = 0
spikes = np.empty(scalar_products.size, dtype=spike_dtype)
idx_lookup = np.arange(scalar_products.size).reshape(nb_templates, -1)
M = np.zeros((nb_peaks, nb_peaks), dtype=np.float32)
all_selections = np.empty((2, scalar_products.size), dtype=np.int32)
res_sps = np.zeros(0, dtype=np.float32)
final_amplitudes = np.zeros(scalar_products.shape, dtype=np.float32)
nb_selection = 0
full_sps = scalar_products.copy()
neighbors = {}
cached_overlaps = {}
is_valid = (scalar_products > stop_criteria)
while np.any(is_valid):
best_amplitude_ind = scalar_products[is_valid].argmax()
best_cluster_ind, peak_index = np.unravel_index(idx_lookup[is_valid][best_amplitude_ind], idx_lookup.shape)
all_selections[:, nb_selection] = [best_cluster_ind, peak_index]
nb_selection += 1
selection = all_selections[:, :nb_selection]
res_sps = full_sps[selection[0], selection[1]]
mb_selection = nb_selection - 1
delta_t = selection[1] - peak_index
idx = np.where(np.abs(delta_t) <= neighbor_window)[0]
myline = neighbor_window + delta_t[idx]
if best_cluster_ind not in cached_overlaps.keys():
cached_overlaps[best_cluster_ind] = overlaps[best_cluster_ind].toarray()
M[mb_selection, idx] = cached_overlaps[best_cluster_ind][selection[0, idx], myline]
if nb_selection >= (M.shape[0] - 1):
Z = np.zeros((2*M.shape[0], 2*M.shape[1]), dtype=np.float32)
Z[:nb_selection, :nb_selection] = M[:nb_selection, :nb_selection]
M = Z
if mb_selection > 0:
scipy.linalg.solve_triangular(M[:mb_selection, :mb_selection], M[mb_selection, :mb_selection], trans=0,
lower=1,
overwrite_b=True,
check_finite=False)
v = nrm2(M[mb_selection, :mb_selection]) ** 2
if 1 - v <= omp_tol: # selected atoms are dependent
break
M[mb_selection, mb_selection] = np.sqrt(1 - v)
all_amplitudes, _ = potrs(M[:nb_selection, :nb_selection], res_sps,
lower=True, overwrite_b=False)
all_amplitudes /= norms[selection[0]]
diff_amplitudes = (all_amplitudes - final_amplitudes[selection[0], selection[1]])
modified = np.where(np.abs(diff_amplitudes) > omp_tol)[0]
final_amplitudes[selection[0], selection[1]] = all_amplitudes
for i in modified:
tmp_best, tmp_peak = selection[:, i]
diff_amp = diff_amplitudes[i]*norms[tmp_best]
if not tmp_best in cached_overlaps.keys():
cached_overlaps[tmp_best] = overlaps[tmp_best].toarray()
if not tmp_peak in neighbors.keys():
idx = [max(0, tmp_peak - neighbor_window), min(nb_peaks, tmp_peak + neighbor_window + 1)]
offset = [neighbor_window + idx[0] - tmp_peak, neighbor_window + idx[1] - tmp_peak]
neighbors[tmp_peak] = {'idx' : idx, 'tdx' : offset}
idx = neighbors[tmp_peak]['idx']
tdx = neighbors[tmp_peak]['tdx']
to_add = diff_amp * cached_overlaps[tmp_best][:, tdx[0]:tdx[1]]
scalar_products[:, idx[0]:idx[1]] -= to_add
scalar_products[best_cluster_ind, peak_index] = -np.inf
is_valid = (scalar_products > stop_criteria)
is_valid = (final_amplitudes > min_amplitude)*(final_amplitudes < max_amplitude)
valid_indices = np.where(is_valid)
nb_spikes = len(valid_indices[0])
spikes['sample_ind'][:nb_spikes] = valid_indices[1] + d['nbefore']
spikes['channel_ind'][:nb_spikes] = 0
spikes['cluster_ind'][:nb_spikes] = valid_indices[0]
spikes['amplitude'][:nb_spikes] = final_amplitudes[valid_indices[0], valid_indices[1]]
spikes = spikes[:nb_spikes]
order = np.argsort(spikes['sample_ind'])
spikes = spikes[order]
return spikes
class CircusPeeler(BaseTemplateMatchingEngine):
"""
Greedy Template-matching ported from the Spyking Circus sorter
https://elifesciences.org/articles/34518
This is a Greedy Template Matching algorithm. The idea is to detect
all the peaks (negative, positive or both) above a certain threshold
Then, at every peak (plus or minus some jitter) we look if the signal
can be explained with a scaled template.
The amplitudes allowed, for every templates, are automatically adjusted
in an optimal manner, to enhance the Matthew Correlation Coefficient
between all spikes/templates in the waveformextractor. For speed and
memory optimization, templates are automatically sparsified if the
density of the matrix falls below a given threshold
Parameters
----------
peak_sign: str
Sign of the peak (neg, pos, or both)
n_shifts: int
The number of samples before/after to classify a peak (should be low)
jitter: int
The number of samples considered before/after every peak to search for
matches
detect_threshold: int
The detection threshold
noise_levels: array
The noise levels, for every channels
random_chunk_kwargs: dict
Parameters for computing noise levels, if not provided (sub optimal)
max_amplitude: float
Maximal amplitude allowed for every template
min_amplitude: float
Minimal amplitude allowed for every template
sparsify_threshold: float
Templates are sparsified in order to keep only the channels necessary
to explain a given fraction of the total norm
use_sparse_matrix_threshold: float
If density of the templates is below a given threshold, sparse matrix
are used (memory efficient)
progress_bar_steps: bool
In order to display or not steps from the algorithm
-----
"""
_default_params = {
'peak_sign': 'neg',
'n_shifts': 1,
'jitter' : 1,
'detect_threshold': 5,
'noise_levels': None,
'random_chunk_kwargs': {},
'sparsify_threshold': 0.99,
'max_amplitude' : 1.5,
'min_amplitude' : 0.5,
'use_sparse_matrix_threshold' : 0.25,
'progess_bar_steps' : True,
}
@classmethod
def _sparsify_template(cls, template, sparsify_threshold, noise_levels):
is_silent = template.std(0) < 0.25*noise_levels
template[:, is_silent] = 0
channel_norms = np.linalg.norm(template, axis=0)**2
total_norm = np.linalg.norm(template)**2
idx = np.argsort(channel_norms)[::-1]
explained_norms = np.cumsum(channel_norms[idx]/total_norm)
channel = np.searchsorted(explained_norms, sparsify_threshold)
active_channels = np.sort(idx[:channel])
template[:, idx[channel:]] = 0
return template, active_channels
@classmethod
def _prepare_templates(cls, d):
waveform_extractor = d['waveform_extractor']
nb_samples = d['nb_samples']
nb_channels = d['nb_channels']
nb_templates = d['nb_templates']
max_amplitude = d['max_amplitude']
min_amplitude = d['min_amplitude']
use_sparse_matrix_threshold = d['use_sparse_matrix_threshold']
d['norms'] = np.zeros(nb_templates, dtype=np.float32)
all_units = list(d['waveform_extractor'].sorting.unit_ids)
templates = waveform_extractor.get_all_templates(mode='median').copy()
d['sparsities'] = {}
for count, unit_id in enumerate(all_units):
templates[count], active_channels = cls._sparsify_template(templates[count], d['sparsify_threshold'], d['noise_levels'])
d['sparsities'][count] = active_channels
d['norms'][count] = np.linalg.norm(templates[count])
templates[count] /= d['norms'][count]
templates = templates.reshape(nb_templates, -1)
nnz = np.sum(templates != 0)/(nb_templates * nb_samples * nb_channels)
if nnz <= use_sparse_matrix_threshold:
templates = scipy.sparse.csr_matrix(templates)
print(f'Templates are automatically sparsified (sparsity level is {nnz})')
d['is_dense'] = False
else:
d['is_dense'] = True
d['templates'] = templates
return d
@classmethod
def _prepare_overlaps(cls, d):
templates = d['templates']
nb_samples = d['nb_samples']
nb_channels = d['nb_channels']
nb_templates = d['nb_templates']
is_dense = d['is_dense']
if not is_dense:
dense_templates = templates.toarray()
else:
dense_templates = templates
dense_templates = dense_templates.reshape(nb_templates, nb_samples, nb_channels)
size = 2 * nb_samples - 1
all_delays = list(range(nb_samples))
if d['progess_bar_steps']:
all_delays = tqdm(all_delays, desc='[1] compute overlaps')
overlaps = {}
for delay in all_delays:
source = dense_templates[:, :delay, :].reshape(nb_templates, -1)
target = dense_templates[:, nb_samples-delay:, :].reshape(nb_templates, -1)
if delay > 0:
overlaps[delay] = scipy.sparse.csr_matrix(source.dot(target.T))
else:
overlaps[delay] = scipy.sparse.csr_matrix((nb_templates, nb_templates), dtype=np.float32)
if delay < nb_samples:
overlaps[size - delay-1] = overlaps[delay].T.tocsr()
new_overlaps = []
for i in range(nb_templates):
data = [overlaps[j][i, :].T for j in range(size)]
data = scipy.sparse.hstack(data)
new_overlaps += [data]
d['overlaps'] = new_overlaps
return d
@classmethod
def _mcc_error(cls, bounds, good, bad):
fn = np.sum((good < bounds[0]) | (good > bounds[1]))
fp = np.sum((bounds[0] <= bad) & (bad <= bounds[1]))
tp = np.sum((bounds[0] <= good) & (good <= bounds[1]))
tn = np.sum((bad < bounds[0]) | (bad > bounds[1]))
denom = (tp+fp)*(tp+fn)*(tn+fp)*(tn+fn)
if denom > 0:
mcc = 1 - (tp*tn - fp*fn)/np.sqrt(denom)
else:
mcc = 1
return mcc
@classmethod
def _cost_function_mcc(cls, bounds, good, bad, delta_amplitude, alpha):
# We want a minimal error, with the larger bounds that are possible
cost = alpha*cls._mcc_error(bounds, good, bad) + (1 - alpha)*np.abs((1 - (bounds[1] - bounds[0])/delta_amplitude))
return cost
@classmethod
def _optimize_amplitudes(cls, noise_snippets, d):
waveform_extractor = d['waveform_extractor']
templates = d['templates']
nb_templates = d['nb_templates']
max_amplitude = d['max_amplitude']
min_amplitude = d['min_amplitude']
alpha = 0.5
norms = d['norms']
all_units = list(waveform_extractor.sorting.unit_ids)
if d['progess_bar_steps']:
all_units = tqdm(all_units, desc='[2] compute amplitudes')
d['amplitudes'] = np.zeros((nb_templates, 2), dtype=np.float32)
noise = templates.dot(noise_snippets)/norms[:, np.newaxis]
all_amps = {}
for count, unit_id in enumerate(all_units):
w = waveform_extractor.get_waveforms(unit_id)
snippets = w.reshape(w.shape[0], -1).T
amps = templates.dot(snippets)/norms[:, np.newaxis]
good = amps[count, :].flatten()
sub_amps = amps[np.concatenate((np.arange(count), np.arange(count+1, nb_templates))), :]
bad = sub_amps[sub_amps >= good]
bad = np.concatenate((bad, noise[count]))
cost_kwargs = [good, bad, max_amplitude - min_amplitude, alpha]
cost_bounds = [(min_amplitude, 1), (1, max_amplitude)]
res = scipy.optimize.differential_evolution(cls._cost_function_mcc, bounds=cost_bounds, args=cost_kwargs)
d['amplitudes'][count] = res.x
# import pylab as plt
# plt.hist(good, 100, alpha=0.5)
# plt.hist(bad, 100, alpha=0.5)
# plt.hist(noise[count], 100, alpha=0.5)
# ymin, ymax = plt.ylim()
# plt.plot([res.x[0], res.x[0]], [ymin, ymax], 'k--')
# plt.plot([res.x[1], res.x[1]], [ymin, ymax], 'k--')
# plt.savefig('test_%d.png' %count)
# plt.close()
return d
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
d = cls._default_params.copy()
d.update(kwargs)
assert isinstance(d['waveform_extractor'], WaveformExtractor)
for v in ['sparsify_threshold', 'use_sparse_matrix_threshold']:
assert (d[v] >= 0) and (d[v] <= 1), f'{v} should be in [0, 1]'
d['nb_channels'] = d['waveform_extractor'].recording.get_num_channels()
d['nb_samples'] = d['waveform_extractor'].nsamples
d['nb_templates'] = len(d['waveform_extractor'].sorting.unit_ids)
if d['noise_levels'] is None:
print('CircusPeeler : noise should be computed outside')
d['noise_levels'] = get_noise_levels(recording, **d['random_chunk_kwargs'])
d['abs_threholds'] = d['noise_levels'] * d['detect_threshold']
d = cls._prepare_templates(d)
d = cls._prepare_overlaps(d)
d['nbefore'] = d['waveform_extractor'].nbefore
d['nafter'] = d['waveform_extractor'].nafter
d['patch_sizes'] = (d['waveform_extractor'].nsamples, d['nb_channels'])
d['sym_patch'] = d['nbefore'] == d['nafter']
#d['jitter'] = int(1e-3*d['jitter'] * recording.get_sampling_frequency())
nb_segments = recording.get_num_segments()
if d['waveform_extractor']._params['max_spikes_per_unit'] is None:
nb_snippets = 1000
else:
nb_snippets = 2*d['waveform_extractor']._params['max_spikes_per_unit']
nb_chunks = nb_snippets // nb_segments
noise_snippets = get_random_data_chunks(recording, num_chunks_per_segment=nb_chunks, chunk_size=d['nb_samples'], seed=42)
noise_snippets = noise_snippets.reshape(nb_chunks, d['nb_samples'], d['nb_channels']).reshape(nb_chunks, -1).T
d = cls._optimize_amplitudes(noise_snippets, d)
return d
@classmethod
def serialize_method_kwargs(cls, kwargs):
kwargs = dict(kwargs)
# remove waveform_extractor
kwargs.pop('waveform_extractor')
return kwargs
@classmethod
def unserialize_in_worker(cls, kwargs):
return kwargs
@classmethod
def get_margin(cls, recording, kwargs):
margin = 2 * max(kwargs['nbefore'], kwargs['nafter'])
return margin
@classmethod
def main_function(cls, traces, d):
peak_sign = d['peak_sign']
abs_threholds = d['abs_threholds']
n_shifts = d['n_shifts']
templates = d['templates']
nb_templates = d['nb_templates']
nb_channels = d['nb_channels']
overlaps = d['overlaps']
margin = d['margin']
norms = d['norms']
jitter = d['jitter']
patch_sizes = d['patch_sizes']
nb_samples = d['nafter'] + d['nbefore']
neighbor_window = nb_samples - 1
amplitudes = d['amplitudes']
sym_patch = d['sym_patch']
sparsities = d['sparsities']
is_dense = d['is_dense']
peak_traces = traces[margin // 2:-margin // 2, :]
peak_sample_ind, peak_chan_ind = detect_peaks_by_channel(peak_traces, peak_sign, abs_threholds, n_shifts)
if jitter > 0:
jittered_peaks = peak_sample_ind[:, np.newaxis] + np.arange(-jitter, jitter)
jittered_channels = peak_chan_ind[:, np.newaxis] + np.zeros(2*jitter)
mask = (jittered_peaks > 0) & (jittered_peaks < len(peak_traces))
jittered_peaks = jittered_peaks[mask]
jittered_channels = jittered_channels[mask]
peak_sample_ind, unique_idx = np.unique(jittered_peaks, return_index=True)
peak_chan_ind = jittered_channels[unique_idx]
else:
peak_sample_ind, unique_idx = np.unique(peak_sample_ind, return_index=True)
peak_chan_ind = peak_chan_ind[unique_idx]
nb_peaks = len(peak_sample_ind)
if sym_patch:
snippets = extract_patches_2d(traces, patch_sizes)[peak_sample_ind]
peak_sample_ind += margin // 2
else:
peak_sample_ind += margin // 2
snippet_window = np.arange(-d['nbefore'], d['nafter'])
snippets = traces[peak_sample_ind[:, np.newaxis] + snippet_window]
if nb_peaks > 0:
snippets = snippets.reshape(nb_peaks, -1)
scalar_products = templates.dot(snippets.T)
else:
scalar_products = np.zeros((nb_templates, 0), dtype=np.float32)
nb_spikes = 0
spikes = np.empty(scalar_products.size, dtype=spike_dtype)
idx_lookup = np.arange(scalar_products.size).reshape(nb_templates, -1)
min_sps = (amplitudes[:, 0] * norms)[:, np.newaxis]
max_sps = (amplitudes[:, 1] * norms)[:, np.newaxis]
is_valid = (scalar_products > min_sps) & (scalar_products < max_sps)
cached_overlaps = {}
while np.any(is_valid):
best_amplitude_ind = scalar_products[is_valid].argmax()
best_cluster_ind, peak_index = np.unravel_index(idx_lookup[is_valid][best_amplitude_ind], idx_lookup.shape)
best_amplitude = scalar_products[best_cluster_ind, peak_index]
best_peak_sample_ind = peak_sample_ind[peak_index]
best_peak_chan_ind = peak_chan_ind[peak_index]
peak_data = peak_sample_ind - peak_sample_ind[peak_index]
is_valid = np.searchsorted(peak_data, [-neighbor_window, neighbor_window + 1])
idx_neighbor = peak_data[is_valid[0]:is_valid[1]] + neighbor_window
if not best_cluster_ind in cached_overlaps.keys():
cached_overlaps[best_cluster_ind] = overlaps[best_cluster_ind].toarray()
to_add = -best_amplitude * cached_overlaps[best_cluster_ind][:, idx_neighbor]
scalar_products[:, is_valid[0]:is_valid[1]] += to_add
scalar_products[best_cluster_ind, is_valid[0]:is_valid[1]] = -np.inf
spikes['sample_ind'][nb_spikes] = best_peak_sample_ind
spikes['channel_ind'][nb_spikes] = best_peak_chan_ind
spikes['cluster_ind'][nb_spikes] = best_cluster_ind
spikes['amplitude'][nb_spikes] = best_amplitude
nb_spikes += 1
is_valid = (scalar_products > min_sps) & (scalar_products < max_sps)
spikes['amplitude'][:nb_spikes] /= norms[spikes['cluster_ind'][:nb_spikes]]
spikes = spikes[:nb_spikes]
order = np.argsort(spikes['sample_ind'])
spikes = spikes[order]
return spikes
template_matching_methods = {
'naive' : NaiveMatching,
'tridesclous' : TridesclousPeeler,
'circus' : CircusPeeler,
'circus-omp' : CircusOMPPeeler
}
| 36.532303 | 153 | 0.606647 |
import numpy as np
import scipy.spatial
from tqdm import tqdm
import sklearn, scipy
import scipy
from threadpoolctl import threadpool_limits
try:
import numba
from numba import jit, prange
HAVE_NUMBA = True
except ImportError:
HAVE_NUMBA = False
from spikeinterface.core import WaveformExtractor
from spikeinterface.core.job_tools import ChunkRecordingExecutor
from spikeinterface.toolkit import (get_noise_levels, get_template_channel_sparsity,
get_channel_distances, get_chunk_with_margin, get_template_extremum_channel, get_random_data_chunks)
from spikeinterface.sortingcomponents.peak_detection import detect_peak_locally_exclusive, detect_peaks_by_channel
from sklearn.feature_extraction.image import extract_patches_2d, reconstruct_from_patches_2d
from sklearn.linear_model import orthogonal_mp_gram
potrs, = scipy.linalg.get_lapack_funcs(('potrs',), dtype=np.float32)
nrm2, = scipy.linalg.get_blas_funcs(('nrm2', ), dtype=np.float32)
spike_dtype = [('sample_ind', 'int64'), ('channel_ind', 'int64'), ('cluster_ind', 'int64'),
('amplitude', 'float64'), ('segment_ind', 'int64')]
def find_spikes_from_templates(recording, method='naive', method_kwargs={}, extra_outputs=False,
**job_kwargs):
assert method in template_matching_methods
method_class = template_matching_methods[method]
method_kwargs = method_class.initialize_and_check_kwargs(recording, method_kwargs)
method_kwargs['margin'] = method_class.get_margin(recording, method_kwargs)
method_kwargs_seralized = method_class.serialize_method_kwargs(method_kwargs)
func = _find_spikes_chunk
init_func = _init_worker_find_spikes
init_args = (recording.to_dict(), method, method_kwargs_seralized)
processor = ChunkRecordingExecutor(recording, func, init_func, init_args,
handle_returns=True, job_name=f'find spikes ({method})', **job_kwargs)
spikes = processor.run()
spikes = np.concatenate(spikes)
if extra_outputs:
return spikes, method_kwargs
else:
return spikes
def _init_worker_find_spikes(recording, method, method_kwargs):
if isinstance(recording, dict):
from spikeinterface.core import load_extractor
recording = load_extractor(recording)
method_class = template_matching_methods[method]
method_kwargs = method_class.unserialize_in_worker(method_kwargs)
worker_ctx = {}
worker_ctx['recording'] = recording
worker_ctx['method'] = method
worker_ctx['method_kwargs'] = method_kwargs
worker_ctx['function'] = method_class.main_function
return worker_ctx
def _find_spikes_chunk(segment_index, start_frame, end_frame, worker_ctx):
recording = worker_ctx['recording']
method = worker_ctx['method']
method_kwargs = worker_ctx['method_kwargs']
margin = method_kwargs['margin']
recording_segment = recording._recording_segments[segment_index]
traces, left_margin, right_margin = get_chunk_with_margin(recording_segment,
start_frame, end_frame, None, margin, add_zeros=True)
function = worker_ctx['function']
with threadpool_limits(limits=1):
spikes = function(traces, method_kwargs)
if margin > 0:
keep = (spikes['sample_ind'] >= margin) & (spikes['sample_ind'] < (traces.shape[0] - margin))
spikes = spikes[keep]
spikes['sample_ind'] += (start_frame - margin)
spikes['segment_ind'] = segment_index
return spikes
class BaseTemplateMatchingEngine:
default_params = {}
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
raise NotImplementedError
@classmethod
def serialize_method_kwargs(cls, kwargs):
raise NotImplementedError
@classmethod
def unserialize_in_worker(cls, recording, kwargs):
raise NotImplementedError
@classmethod
def get_margin(cls, recording, kwargs):
raise NotImplementedError
@classmethod
def main_function(cls, traces, method_kwargs):
raise NotImplementedError
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
d = cls.default_params.copy()
d.update(kwargs)
assert d['waveform_extractor'] is not None
we = d['waveform_extractor']
if d['noise_levels'] is None:
d['noise_levels'] = get_noise_levels(recording, **d['random_chunk_kwargs'])
d['abs_threholds'] = d['noise_levels'] * d['detect_threshold']
channel_distance = get_channel_distances(recording)
d['neighbours_mask'] = channel_distance < d['local_radius_um']
d['nbefore'] = we.nbefore
d['nafter'] = we.nafter
return d
@classmethod
def get_margin(cls, recording, kwargs):
margin = max(kwargs['nbefore'], kwargs['nafter'])
return margin
@classmethod
def serialize_method_kwargs(cls, kwargs):
kwargs = dict(kwargs)
waveform_extractor = kwargs['waveform_extractor']
kwargs['waveform_extractor'] = str(waveform_extractor.folder)
return kwargs
@classmethod
def unserialize_in_worker(cls, kwargs):
we = kwargs['waveform_extractor']
if isinstance(we, str):
we = WaveformExtractor.load_from_folder(we)
kwargs['waveform_extractor'] = we
templates = we.get_all_templates(mode='average')
kwargs['templates'] = templates
return kwargs
@classmethod
def main_function(cls, traces, method_kwargs):
peak_sign = method_kwargs['peak_sign']
abs_threholds = method_kwargs['abs_threholds']
n_shifts = method_kwargs['n_shifts']
neighbours_mask = method_kwargs['neighbours_mask']
templates = method_kwargs['templates']
nbefore = method_kwargs['nbefore']
nafter = method_kwargs['nafter']
margin = method_kwargs['margin']
if margin > 0:
peak_traces = traces[margin:-margin, :]
else:
peak_traces = traces
peak_sample_ind, peak_chan_ind = detect_peak_locally_exclusive(peak_traces, peak_sign, abs_threholds, n_shifts, neighbours_mask)
peak_sample_ind += margin
spikes = np.zeros(peak_sample_ind.size, dtype=spike_dtype)
spikes['sample_ind'] = peak_sample_ind
spikes['channel_ind'] = peak_chan_ind
for i in range(peak_sample_ind.size):
i0 = peak_sample_ind[i] - nbefore
i1 = peak_sample_ind[i] + nafter
wf = traces[i0:i1, :]
dist = np.sum(np.sum((templates - wf[None, : , :])**2, axis=1), axis=1)
cluster_ind = np.argmin(dist)
spikes['cluster_ind'][i] = cluster_ind
spikes['amplitude'][i] = 0.
return spikes
d
def initialize_and_check_kwargs(cls, recording, kwargs):
assert HAVE_NUMBA
d = cls.default_params.copy()
d.update(kwargs)
assert isinstance(d['waveform_extractor'], WaveformExtractor)
we = d['waveform_extractor']
unit_ids = we.sorting.unit_ids
channel_ids = we.recording.channel_ids
sr = we.recording.get_sampling_frequency()
templates = we.get_all_templates(mode='average')
d['templates'] = templates
d['nbefore'] = we.nbefore
d['nafter'] = we.nafter
nbefore_short = int(d['ms_before'] * sr / 1000.)
nafter_short = int(d['ms_before'] * sr / 1000.)
assert nbefore_short <= we.nbefore
assert nafter_short <= we.nafter
d['nbefore_short'] = nbefore_short
d['nafter_short'] = nafter_short
s0 = (we.nbefore - nbefore_short)
s1 = -(we.nafter - nafter_short)
if s1 == 0:
s1 = None
templates_short = templates[:, slice(s0,s1), :].copy()
d['templates_short'] = templates_short
d['peak_shift'] = int(d['peak_shift_ms'] / 1000 * sr)
if d['noise_levels'] is None:
print('TridesclousPeeler : noise should be computed outside')
d['noise_levels'] = get_noise_levels(recording)
d['abs_threholds'] = d['noise_levels'] * d['detect_threshold']
channel_distance = get_channel_distances(recording)
d['neighbours_mask'] = channel_distance < d['local_radius_um']
template_sparsity_inds = get_template_channel_sparsity(we, method='threshold',
peak_sign=d['peak_sign'], outputs='index', threshold=d['detect_threshold'])
template_sparsity = np.zeros((unit_ids.size, channel_ids.size), dtype='bool')
for unit_index, unit_id in enumerate(unit_ids):
chan_inds = template_sparsity_inds[unit_id]
template_sparsity[unit_index, chan_inds] = True
d['template_sparsity'] = template_sparsity
extremum_channel = get_template_extremum_channel(we, peak_sign=d['peak_sign'], outputs='index')
extremum_channel = np.array([extremum_channel[unit_id] for unit_id in unit_ids], dtype='int64')
d['extremum_channel'] = extremum_channel
channel_locations = we.recording.get_channel_locations()
unit_locations = channel_locations[extremum_channel]
unit_distances = scipy.spatial.distance.cdist(unit_locations, unit_locations, metric='euclidean')
closest_units = []
for unit_ind, unit_id in enumerate(unit_ids):
order = np.argsort(unit_distances[unit_ind, :])
closest_u = np.arange(unit_ids.size)[order].tolist()
closest_u.remove(unit_ind)
closest_u = np.array(closest_u[:d['num_closest']])
chans, = np.nonzero(d['template_sparsity'][unit_ind, :])
template_sparse = templates[unit_ind, :, :][:, chans]
closest_vec = []
for u in closest_u:
vec = (templates[u, :, :][:, chans] - template_sparse)
vec /= np.sum(vec ** 2)
closest_vec.append((u, vec))
closest_vec.append((None, - template_sparse / np.sum(template_sparse ** 2)))
closest_units.append(closest_vec)
d['closest_units'] = closest_units
distances = scipy.spatial.distance.cdist(channel_locations, unit_locations, metric='euclidean')
near_cluster_mask = distances < d['local_radius_um']
possible_clusters_by_channel = []
for channel_ind in range(distances.shape[0]):
cluster_inds, = np.nonzero(near_cluster_mask[channel_ind, :])
possible_clusters_by_channel.append(cluster_inds)
d['possible_clusters_by_channel'] = possible_clusters_by_channel
d['possible_shifts'] = np.arange(-d['sample_shift'], d['sample_shift'] +1, dtype='int64')
return d
@classmethod
def serialize_method_kwargs(cls, kwargs):
kwargs = dict(kwargs)
kwargs.pop('waveform_extractor')
return kwargs
@classmethod
def unserialize_in_worker(cls, kwargs):
return kwargs
@classmethod
def get_margin(cls, recording, kwargs):
margin = 2 * (kwargs['nbefore'] + kwargs['nafter'])
return margin
@classmethod
def main_function(cls, traces, d):
traces = traces.copy()
all_spikes = []
level = 0
while True:
spikes = _tdc_find_spikes(traces, d, level=level)
keep = (spikes['cluster_ind'] >= 0)
if not np.any(keep):
break
all_spikes.append(spikes[keep])
level += 1
if level == d['num_peeler_loop']:
break
if len(all_spikes) > 0:
all_spikes = np.concatenate(all_spikes)
order = np.argsort(all_spikes['sample_ind'])
all_spikes = all_spikes[order]
else:
all_spikes = np.zeros(0, dtype=spike_dtype)
return all_spikes
def _tdc_find_spikes(traces, d, level=0):
peak_sign = d['peak_sign']
templates = d['templates']
templates_short = d['templates_short']
margin = d['margin']
possible_clusters_by_channel = d['possible_clusters_by_channel']
peak_traces = traces[margin // 2:-margin // 2, :]
peak_sample_ind, peak_chan_ind = detect_peak_locally_exclusive(peak_traces, peak_sign,
d['abs_threholds'], d['peak_shift'], d['neighbours_mask'])
peak_sample_ind += margin // 2
peak_amplitude = traces[peak_sample_ind, peak_chan_ind]
order = np.argsort(np.abs(peak_amplitude))[::-1]
peak_sample_ind = peak_sample_ind[order]
peak_chan_ind = peak_chan_ind[order]
spikes = np.zeros(peak_sample_ind.size, dtype=spike_dtype)
spikes['sample_ind'] = peak_sample_ind
spikes['channel_ind'] = peak_chan_ind
possible_shifts = d['possible_shifts']
distances_shift = np.zeros(possible_shifts.size)
for i in range(peak_sample_ind.size):
sample_ind = peak_sample_ind[i]
chan_ind = peak_chan_ind[i]
possible_clusters = possible_clusters_by_channel[chan_ind]
if possible_clusters.size > 0:
s0 = sample_ind - d['nbefore_short']
s1 = sample_ind + d['nafter_short']
wf_short = traces[s0:s1, :]
.any(d['template_sparsity'][possible_clusters, :], axis=0)
distances = numba_sparse_dist(wf_short, templates_short, union_channels, possible_clusters)
for ind in np.argsort(distances)[:d['num_template_try']]:
cluster_ind = possible_clusters[ind]
chan_sparsity = d['template_sparsity'][cluster_ind, :]
template_sparse = templates[cluster_ind, :, :][:, chan_sparsity]
numba_best_shift(traces, templates[cluster_ind, :, :], sample_ind, d['nbefore'], possible_shifts, distances_shift, chan_sparsity)
ind_shift = np.argmin(distances_shift)
shift = possible_shifts[ind_shift]
sample_ind = sample_ind + shift
s0 = sample_ind - d['nbefore']
s1 = sample_ind + d['nafter']
wf_sparse = traces[s0:s1, chan_sparsity]
centered = wf_sparse - template_sparse
accepted = True
for other_ind, other_vector in d['closest_units'][cluster_ind]:
v = np.sum(centered * other_vector)
if np.abs(v) >0.5:
accepted = False
break
if accepted:
break
if accepted:
amplitude = 1.
template = templates[cluster_ind, :, :]
s0 = sample_ind - d['nbefore']
s1 = sample_ind + d['nafter']
traces[s0:s1, :] -= template * amplitude
else:
cluster_ind = -1
amplitude = 0.
else:
cluster_ind = -1
amplitude = 0.
spikes['cluster_ind'][i] = cluster_ind
spikes['amplitude'][i] =amplitude
return spikes
if HAVE_NUMBA:
@jit(nopython=True)
def numba_sparse_dist(wf, templates, union_channels, possible_clusters):
total_cluster, width, num_chan = templates.shape
num_cluster = possible_clusters.shape[0]
distances = np.zeros((num_cluster,), dtype=np.float32)
for i in prange(num_cluster):
cluster_ind = possible_clusters[i]
sum_dist = 0.
for chan_ind in range(num_chan):
if union_channels[chan_ind]:
for s in range(width):
v = wf[s, chan_ind]
t = templates[cluster_ind, s, chan_ind]
sum_dist += (v - t) ** 2
distances[i] = sum_dist
return distances
@jit(nopython=True)
def numba_best_shift(traces, template, sample_ind, nbefore, possible_shifts, distances_shift, chan_sparsity):
width, num_chan = template.shape
n_shift = possible_shifts.size
for i in range(n_shift):
shift = possible_shifts[i]
sum_dist = 0.
for chan_ind in range(num_chan):
if chan_sparsity[chan_ind]:
for s in range(width):
v = traces[sample_ind - nbefore + s +shift, chan_ind]
t = template[s, chan_ind]
sum_dist += (v - t) ** 2
distances_shift[i] = sum_dist
return distances_shift
': {},
'omp_min_sps' : 0.5,
'progess_bar_steps' : False,
}
@classmethod
def _sparsify_template(cls, template, sparsify_threshold, noise_levels):
is_silent = template.std(0) < 0.25*noise_levels
template[:, is_silent] = 0
channel_norms = np.linalg.norm(template, axis=0)**2
total_norm = np.linalg.norm(template)**2
idx = np.argsort(channel_norms)[::-1]
explained_norms = np.cumsum(channel_norms[idx]/total_norm)
channel = np.searchsorted(explained_norms, sparsify_threshold)
active_channels = np.sort(idx[:channel])
template[:, idx[channel:]] = 0
return template, active_channels
@classmethod
def _prepare_templates(cls, d):
waveform_extractor = d['waveform_extractor']
nb_samples = d['nb_samples']
nb_channels = d['nb_channels']
nb_templates = d['nb_templates']
use_sparse_matrix_threshold = d['use_sparse_matrix_threshold']
d['norms'] = np.zeros(nb_templates, dtype=np.float32)
all_units = list(d['waveform_extractor'].sorting.unit_ids)
templates = waveform_extractor.get_all_templates(mode='median').copy()
d['sparsities'] = {}
for count, unit_id in enumerate(all_units):
templates[count], active_channels = cls._sparsify_template(templates[count], d['sparsify_threshold'], d['noise_levels'])
d['sparsities'][count] = active_channels
d['norms'][count] = np.linalg.norm(templates[count])
templates[count] /= d['norms'][count]
templates = templates.reshape(nb_templates, -1)
nnz = np.sum(templates != 0)/(nb_templates * nb_samples * nb_channels)
if nnz <= use_sparse_matrix_threshold:
templates = scipy.sparse.csr_matrix(templates)
print(f'Templates are automatically sparsified (sparsity level is {nnz})')
d['is_dense'] = False
else:
d['is_dense'] = True
d['templates'] = templates
return d
@classmethod
def _prepare_overlaps(cls, d):
templates = d['templates']
nb_samples = d['nb_samples']
nb_channels = d['nb_channels']
nb_templates = d['nb_templates']
is_dense = d['is_dense']
if not is_dense:
dense_templates = templates.toarray()
else:
dense_templates = templates
dense_templates = dense_templates.reshape(nb_templates, nb_samples, nb_channels)
size = 2 * nb_samples - 1
all_delays = list(range(nb_samples))
if d['progess_bar_steps']:
all_delays = tqdm(all_delays, desc='[1] compute overlaps')
overlaps = {}
for delay in all_delays:
source = dense_templates[:, :delay, :].reshape(nb_templates, -1)
target = dense_templates[:, nb_samples-delay:, :].reshape(nb_templates, -1)
if delay > 0:
overlaps[delay] = scipy.sparse.csr_matrix(source.dot(target.T))
else:
overlaps[delay] = scipy.sparse.csr_matrix((nb_templates, nb_templates), dtype=np.float32)
if delay < nb_samples:
overlaps[size - delay-1] = overlaps[delay].T.tocsr()
new_overlaps = []
for i in range(nb_templates):
data = [overlaps[j][i, :].T for j in range(size)]
data = scipy.sparse.hstack(data)
new_overlaps += [data]
d['overlaps'] = new_overlaps
return d
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
d = cls._default_params.copy()
d.update(kwargs)
assert isinstance(d['waveform_extractor'], WaveformExtractor)
for v in ['sparsify_threshold', 'omp_min_sps','use_sparse_matrix_threshold']:
assert (d[v] >= 0) and (d[v] <= 1), f'{v} should be in [0, 1]'
if d['noise_levels'] is None:
print('CircusOMPPeeler : noise should be computed outside')
d['noise_levels'] = get_noise_levels(recording, **d['random_chunk_kwargs'])
d['nb_channels'] = d['waveform_extractor'].recording.get_num_channels()
d['nb_samples'] = d['waveform_extractor'].nsamples
d['nb_templates'] = len(d['waveform_extractor'].sorting.unit_ids)
d['nbefore'] = d['waveform_extractor'].nbefore
d['nafter'] = d['waveform_extractor'].nafter
d = cls._prepare_templates(d)
d = cls._prepare_overlaps(d)
return d
@classmethod
def serialize_method_kwargs(cls, kwargs):
kwargs = dict(kwargs)
kwargs.pop('waveform_extractor')
return kwargs
@classmethod
def unserialize_in_worker(cls, kwargs):
return kwargs
@classmethod
def get_margin(cls, recording, kwargs):
margin = 2 * max(kwargs['nbefore'], kwargs['nafter'])
return margin
@classmethod
def main_function(cls, traces, d):
templates = d['templates']
nb_templates = d['nb_templates']
nb_channels = d['nb_channels']
overlaps = d['overlaps']
margin = d['margin']
norms = d['norms']
nbefore = d['nbefore']
nafter = d['nafter']
omp_tol = np.finfo(np.float32).eps
omp_min_sps = d['omp_min_sps']
nb_samples = d['nafter'] + d['nbefore']
neighbor_window = nb_samples - 1
min_amplitude, max_amplitude = d['amplitudes']
sparsities = d['sparsities']
is_dense = d['is_dense']
stop_criteria = omp_min_sps * norms[:, np.newaxis]
nb_peaks = len(traces) - nb_samples + 1
if is_dense:
kernel_filters = templates.reshape(nb_templates, nb_samples, nb_channels)[:, ::-1, :]
scalar_products = scipy.signal.fftconvolve(kernel_filters, traces[np.newaxis, :, :], axes=(0, 1), mode='valid').sum(2)
else:
scalar_products = np.empty((nb_templates, nb_peaks), dtype=np.float32)
for i in range(nb_templates):
kernel_filter = templates[i].toarray().reshape(nb_samples, nb_channels)
kernel_filter = kernel_filter[::-1, sparsities[i]]
convolution = scipy.signal.fftconvolve(kernel_filter, traces[:, sparsities[i]], axes=0, mode='valid')
if len(convolution) > 0:
scalar_products[i] = convolution.sum(1)
else:
scalar_products[i] = 0
peak_chan_ind = np.zeros(nb_peaks)
nb_spikes = 0
spikes = np.empty(scalar_products.size, dtype=spike_dtype)
idx_lookup = np.arange(scalar_products.size).reshape(nb_templates, -1)
M = np.zeros((nb_peaks, nb_peaks), dtype=np.float32)
all_selections = np.empty((2, scalar_products.size), dtype=np.int32)
res_sps = np.zeros(0, dtype=np.float32)
final_amplitudes = np.zeros(scalar_products.shape, dtype=np.float32)
nb_selection = 0
full_sps = scalar_products.copy()
neighbors = {}
cached_overlaps = {}
is_valid = (scalar_products > stop_criteria)
while np.any(is_valid):
best_amplitude_ind = scalar_products[is_valid].argmax()
best_cluster_ind, peak_index = np.unravel_index(idx_lookup[is_valid][best_amplitude_ind], idx_lookup.shape)
all_selections[:, nb_selection] = [best_cluster_ind, peak_index]
nb_selection += 1
selection = all_selections[:, :nb_selection]
res_sps = full_sps[selection[0], selection[1]]
mb_selection = nb_selection - 1
delta_t = selection[1] - peak_index
idx = np.where(np.abs(delta_t) <= neighbor_window)[0]
myline = neighbor_window + delta_t[idx]
if best_cluster_ind not in cached_overlaps.keys():
cached_overlaps[best_cluster_ind] = overlaps[best_cluster_ind].toarray()
M[mb_selection, idx] = cached_overlaps[best_cluster_ind][selection[0, idx], myline]
if nb_selection >= (M.shape[0] - 1):
Z = np.zeros((2*M.shape[0], 2*M.shape[1]), dtype=np.float32)
Z[:nb_selection, :nb_selection] = M[:nb_selection, :nb_selection]
M = Z
if mb_selection > 0:
scipy.linalg.solve_triangular(M[:mb_selection, :mb_selection], M[mb_selection, :mb_selection], trans=0,
lower=1,
overwrite_b=True,
check_finite=False)
v = nrm2(M[mb_selection, :mb_selection]) ** 2
if 1 - v <= omp_tol:
break
M[mb_selection, mb_selection] = np.sqrt(1 - v)
all_amplitudes, _ = potrs(M[:nb_selection, :nb_selection], res_sps,
lower=True, overwrite_b=False)
all_amplitudes /= norms[selection[0]]
diff_amplitudes = (all_amplitudes - final_amplitudes[selection[0], selection[1]])
modified = np.where(np.abs(diff_amplitudes) > omp_tol)[0]
final_amplitudes[selection[0], selection[1]] = all_amplitudes
for i in modified:
tmp_best, tmp_peak = selection[:, i]
diff_amp = diff_amplitudes[i]*norms[tmp_best]
if not tmp_best in cached_overlaps.keys():
cached_overlaps[tmp_best] = overlaps[tmp_best].toarray()
if not tmp_peak in neighbors.keys():
idx = [max(0, tmp_peak - neighbor_window), min(nb_peaks, tmp_peak + neighbor_window + 1)]
offset = [neighbor_window + idx[0] - tmp_peak, neighbor_window + idx[1] - tmp_peak]
neighbors[tmp_peak] = {'idx' : idx, 'tdx' : offset}
idx = neighbors[tmp_peak]['idx']
tdx = neighbors[tmp_peak]['tdx']
to_add = diff_amp * cached_overlaps[tmp_best][:, tdx[0]:tdx[1]]
scalar_products[:, idx[0]:idx[1]] -= to_add
scalar_products[best_cluster_ind, peak_index] = -np.inf
is_valid = (scalar_products > stop_criteria)
is_valid = (final_amplitudes > min_amplitude)*(final_amplitudes < max_amplitude)
valid_indices = np.where(is_valid)
nb_spikes = len(valid_indices[0])
spikes['sample_ind'][:nb_spikes] = valid_indices[1] + d['nbefore']
spikes['channel_ind'][:nb_spikes] = 0
spikes['cluster_ind'][:nb_spikes] = valid_indices[0]
spikes['amplitude'][:nb_spikes] = final_amplitudes[valid_indices[0], valid_indices[1]]
spikes = spikes[:nb_spikes]
order = np.argsort(spikes['sample_ind'])
spikes = spikes[order]
return spikes
class CircusPeeler(BaseTemplateMatchingEngine):
_default_params = {
'peak_sign': 'neg',
'n_shifts': 1,
'jitter' : 1,
'detect_threshold': 5,
'noise_levels': None,
'random_chunk_kwargs': {},
'sparsify_threshold': 0.99,
'max_amplitude' : 1.5,
'min_amplitude' : 0.5,
'use_sparse_matrix_threshold' : 0.25,
'progess_bar_steps' : True,
}
@classmethod
def _sparsify_template(cls, template, sparsify_threshold, noise_levels):
is_silent = template.std(0) < 0.25*noise_levels
template[:, is_silent] = 0
channel_norms = np.linalg.norm(template, axis=0)**2
total_norm = np.linalg.norm(template)**2
idx = np.argsort(channel_norms)[::-1]
explained_norms = np.cumsum(channel_norms[idx]/total_norm)
channel = np.searchsorted(explained_norms, sparsify_threshold)
active_channels = np.sort(idx[:channel])
template[:, idx[channel:]] = 0
return template, active_channels
@classmethod
def _prepare_templates(cls, d):
waveform_extractor = d['waveform_extractor']
nb_samples = d['nb_samples']
nb_channels = d['nb_channels']
nb_templates = d['nb_templates']
max_amplitude = d['max_amplitude']
min_amplitude = d['min_amplitude']
use_sparse_matrix_threshold = d['use_sparse_matrix_threshold']
d['norms'] = np.zeros(nb_templates, dtype=np.float32)
all_units = list(d['waveform_extractor'].sorting.unit_ids)
templates = waveform_extractor.get_all_templates(mode='median').copy()
d['sparsities'] = {}
for count, unit_id in enumerate(all_units):
templates[count], active_channels = cls._sparsify_template(templates[count], d['sparsify_threshold'], d['noise_levels'])
d['sparsities'][count] = active_channels
d['norms'][count] = np.linalg.norm(templates[count])
templates[count] /= d['norms'][count]
templates = templates.reshape(nb_templates, -1)
nnz = np.sum(templates != 0)/(nb_templates * nb_samples * nb_channels)
if nnz <= use_sparse_matrix_threshold:
templates = scipy.sparse.csr_matrix(templates)
print(f'Templates are automatically sparsified (sparsity level is {nnz})')
d['is_dense'] = False
else:
d['is_dense'] = True
d['templates'] = templates
return d
@classmethod
def _prepare_overlaps(cls, d):
templates = d['templates']
nb_samples = d['nb_samples']
nb_channels = d['nb_channels']
nb_templates = d['nb_templates']
is_dense = d['is_dense']
if not is_dense:
dense_templates = templates.toarray()
else:
dense_templates = templates
dense_templates = dense_templates.reshape(nb_templates, nb_samples, nb_channels)
size = 2 * nb_samples - 1
all_delays = list(range(nb_samples))
if d['progess_bar_steps']:
all_delays = tqdm(all_delays, desc='[1] compute overlaps')
overlaps = {}
for delay in all_delays:
source = dense_templates[:, :delay, :].reshape(nb_templates, -1)
target = dense_templates[:, nb_samples-delay:, :].reshape(nb_templates, -1)
if delay > 0:
overlaps[delay] = scipy.sparse.csr_matrix(source.dot(target.T))
else:
overlaps[delay] = scipy.sparse.csr_matrix((nb_templates, nb_templates), dtype=np.float32)
if delay < nb_samples:
overlaps[size - delay-1] = overlaps[delay].T.tocsr()
new_overlaps = []
for i in range(nb_templates):
data = [overlaps[j][i, :].T for j in range(size)]
data = scipy.sparse.hstack(data)
new_overlaps += [data]
d['overlaps'] = new_overlaps
return d
@classmethod
def _mcc_error(cls, bounds, good, bad):
fn = np.sum((good < bounds[0]) | (good > bounds[1]))
fp = np.sum((bounds[0] <= bad) & (bad <= bounds[1]))
tp = np.sum((bounds[0] <= good) & (good <= bounds[1]))
tn = np.sum((bad < bounds[0]) | (bad > bounds[1]))
denom = (tp+fp)*(tp+fn)*(tn+fp)*(tn+fn)
if denom > 0:
mcc = 1 - (tp*tn - fp*fn)/np.sqrt(denom)
else:
mcc = 1
return mcc
@classmethod
def _cost_function_mcc(cls, bounds, good, bad, delta_amplitude, alpha):
cost = alpha*cls._mcc_error(bounds, good, bad) + (1 - alpha)*np.abs((1 - (bounds[1] - bounds[0])/delta_amplitude))
return cost
@classmethod
def _optimize_amplitudes(cls, noise_snippets, d):
waveform_extractor = d['waveform_extractor']
templates = d['templates']
nb_templates = d['nb_templates']
max_amplitude = d['max_amplitude']
min_amplitude = d['min_amplitude']
alpha = 0.5
norms = d['norms']
all_units = list(waveform_extractor.sorting.unit_ids)
if d['progess_bar_steps']:
all_units = tqdm(all_units, desc='[2] compute amplitudes')
d['amplitudes'] = np.zeros((nb_templates, 2), dtype=np.float32)
noise = templates.dot(noise_snippets)/norms[:, np.newaxis]
all_amps = {}
for count, unit_id in enumerate(all_units):
w = waveform_extractor.get_waveforms(unit_id)
snippets = w.reshape(w.shape[0], -1).T
amps = templates.dot(snippets)/norms[:, np.newaxis]
good = amps[count, :].flatten()
sub_amps = amps[np.concatenate((np.arange(count), np.arange(count+1, nb_templates))), :]
bad = sub_amps[sub_amps >= good]
bad = np.concatenate((bad, noise[count]))
cost_kwargs = [good, bad, max_amplitude - min_amplitude, alpha]
cost_bounds = [(min_amplitude, 1), (1, max_amplitude)]
res = scipy.optimize.differential_evolution(cls._cost_function_mcc, bounds=cost_bounds, args=cost_kwargs)
d['amplitudes'][count] = res.x
return d
@classmethod
def initialize_and_check_kwargs(cls, recording, kwargs):
d = cls._default_params.copy()
d.update(kwargs)
assert isinstance(d['waveform_extractor'], WaveformExtractor)
for v in ['sparsify_threshold', 'use_sparse_matrix_threshold']:
assert (d[v] >= 0) and (d[v] <= 1), f'{v} should be in [0, 1]'
d['nb_channels'] = d['waveform_extractor'].recording.get_num_channels()
d['nb_samples'] = d['waveform_extractor'].nsamples
d['nb_templates'] = len(d['waveform_extractor'].sorting.unit_ids)
if d['noise_levels'] is None:
print('CircusPeeler : noise should be computed outside')
d['noise_levels'] = get_noise_levels(recording, **d['random_chunk_kwargs'])
d['abs_threholds'] = d['noise_levels'] * d['detect_threshold']
d = cls._prepare_templates(d)
d = cls._prepare_overlaps(d)
d['nbefore'] = d['waveform_extractor'].nbefore
d['nafter'] = d['waveform_extractor'].nafter
d['patch_sizes'] = (d['waveform_extractor'].nsamples, d['nb_channels'])
d['sym_patch'] = d['nbefore'] == d['nafter']
nb_segments = recording.get_num_segments()
if d['waveform_extractor']._params['max_spikes_per_unit'] is None:
nb_snippets = 1000
else:
nb_snippets = 2*d['waveform_extractor']._params['max_spikes_per_unit']
nb_chunks = nb_snippets // nb_segments
noise_snippets = get_random_data_chunks(recording, num_chunks_per_segment=nb_chunks, chunk_size=d['nb_samples'], seed=42)
noise_snippets = noise_snippets.reshape(nb_chunks, d['nb_samples'], d['nb_channels']).reshape(nb_chunks, -1).T
d = cls._optimize_amplitudes(noise_snippets, d)
return d
@classmethod
def serialize_method_kwargs(cls, kwargs):
kwargs = dict(kwargs)
kwargs.pop('waveform_extractor')
return kwargs
@classmethod
def unserialize_in_worker(cls, kwargs):
return kwargs
@classmethod
def get_margin(cls, recording, kwargs):
margin = 2 * max(kwargs['nbefore'], kwargs['nafter'])
return margin
@classmethod
def main_function(cls, traces, d):
peak_sign = d['peak_sign']
abs_threholds = d['abs_threholds']
n_shifts = d['n_shifts']
templates = d['templates']
nb_templates = d['nb_templates']
nb_channels = d['nb_channels']
overlaps = d['overlaps']
margin = d['margin']
norms = d['norms']
jitter = d['jitter']
patch_sizes = d['patch_sizes']
nb_samples = d['nafter'] + d['nbefore']
neighbor_window = nb_samples - 1
amplitudes = d['amplitudes']
sym_patch = d['sym_patch']
sparsities = d['sparsities']
is_dense = d['is_dense']
peak_traces = traces[margin // 2:-margin // 2, :]
peak_sample_ind, peak_chan_ind = detect_peaks_by_channel(peak_traces, peak_sign, abs_threholds, n_shifts)
if jitter > 0:
jittered_peaks = peak_sample_ind[:, np.newaxis] + np.arange(-jitter, jitter)
jittered_channels = peak_chan_ind[:, np.newaxis] + np.zeros(2*jitter)
mask = (jittered_peaks > 0) & (jittered_peaks < len(peak_traces))
jittered_peaks = jittered_peaks[mask]
jittered_channels = jittered_channels[mask]
peak_sample_ind, unique_idx = np.unique(jittered_peaks, return_index=True)
peak_chan_ind = jittered_channels[unique_idx]
else:
peak_sample_ind, unique_idx = np.unique(peak_sample_ind, return_index=True)
peak_chan_ind = peak_chan_ind[unique_idx]
nb_peaks = len(peak_sample_ind)
if sym_patch:
snippets = extract_patches_2d(traces, patch_sizes)[peak_sample_ind]
peak_sample_ind += margin // 2
else:
peak_sample_ind += margin // 2
snippet_window = np.arange(-d['nbefore'], d['nafter'])
snippets = traces[peak_sample_ind[:, np.newaxis] + snippet_window]
if nb_peaks > 0:
snippets = snippets.reshape(nb_peaks, -1)
scalar_products = templates.dot(snippets.T)
else:
scalar_products = np.zeros((nb_templates, 0), dtype=np.float32)
nb_spikes = 0
spikes = np.empty(scalar_products.size, dtype=spike_dtype)
idx_lookup = np.arange(scalar_products.size).reshape(nb_templates, -1)
min_sps = (amplitudes[:, 0] * norms)[:, np.newaxis]
max_sps = (amplitudes[:, 1] * norms)[:, np.newaxis]
is_valid = (scalar_products > min_sps) & (scalar_products < max_sps)
cached_overlaps = {}
while np.any(is_valid):
best_amplitude_ind = scalar_products[is_valid].argmax()
best_cluster_ind, peak_index = np.unravel_index(idx_lookup[is_valid][best_amplitude_ind], idx_lookup.shape)
best_amplitude = scalar_products[best_cluster_ind, peak_index]
best_peak_sample_ind = peak_sample_ind[peak_index]
best_peak_chan_ind = peak_chan_ind[peak_index]
peak_data = peak_sample_ind - peak_sample_ind[peak_index]
is_valid = np.searchsorted(peak_data, [-neighbor_window, neighbor_window + 1])
idx_neighbor = peak_data[is_valid[0]:is_valid[1]] + neighbor_window
if not best_cluster_ind in cached_overlaps.keys():
cached_overlaps[best_cluster_ind] = overlaps[best_cluster_ind].toarray()
to_add = -best_amplitude * cached_overlaps[best_cluster_ind][:, idx_neighbor]
scalar_products[:, is_valid[0]:is_valid[1]] += to_add
scalar_products[best_cluster_ind, is_valid[0]:is_valid[1]] = -np.inf
spikes['sample_ind'][nb_spikes] = best_peak_sample_ind
spikes['channel_ind'][nb_spikes] = best_peak_chan_ind
spikes['cluster_ind'][nb_spikes] = best_cluster_ind
spikes['amplitude'][nb_spikes] = best_amplitude
nb_spikes += 1
is_valid = (scalar_products > min_sps) & (scalar_products < max_sps)
spikes['amplitude'][:nb_spikes] /= norms[spikes['cluster_ind'][:nb_spikes]]
spikes = spikes[:nb_spikes]
order = np.argsort(spikes['sample_ind'])
spikes = spikes[order]
return spikes
template_matching_methods = {
'naive' : NaiveMatching,
'tridesclous' : TridesclousPeeler,
'circus' : CircusPeeler,
'circus-omp' : CircusOMPPeeler
}
| true | true |
1c46d1d4784a0d62c8a99280915d87553433d406 | 170 | py | Python | recepcao/admin.py | alantinoco/recepcao-edificio-comercial | dcbfa9fd93f71b2bec15681b947371f8af3e815f | [
"MIT"
] | null | null | null | recepcao/admin.py | alantinoco/recepcao-edificio-comercial | dcbfa9fd93f71b2bec15681b947371f8af3e815f | [
"MIT"
] | null | null | null | recepcao/admin.py | alantinoco/recepcao-edificio-comercial | dcbfa9fd93f71b2bec15681b947371f8af3e815f | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import *
admin.site.register(Sala)
admin.site.register(Usuario)
admin.site.register(Visitante)
admin.site.register(Visita)
| 21.25 | 32 | 0.811765 | from django.contrib import admin
from .models import *
admin.site.register(Sala)
admin.site.register(Usuario)
admin.site.register(Visitante)
admin.site.register(Visita)
| true | true |
1c46d206debfc3cfd0af0e2eb1216cafaca41f24 | 3,325 | py | Python | ucscsdk/mometa/storage/StorageSnapshotCtx.py | parag-may4/ucscsdk | 2ea762fa070330e3a4e2c21b46b157469555405b | [
"Apache-2.0"
] | 9 | 2016-12-22T08:39:25.000Z | 2019-09-10T15:36:19.000Z | ucscsdk/mometa/storage/StorageSnapshotCtx.py | parag-may4/ucscsdk | 2ea762fa070330e3a4e2c21b46b157469555405b | [
"Apache-2.0"
] | 10 | 2017-01-31T06:59:56.000Z | 2021-11-09T09:14:37.000Z | ucscsdk/mometa/storage/StorageSnapshotCtx.py | parag-may4/ucscsdk | 2ea762fa070330e3a4e2c21b46b157469555405b | [
"Apache-2.0"
] | 13 | 2016-11-14T07:42:58.000Z | 2022-02-10T17:32:05.000Z | """This module contains the general information for StorageSnapshotCtx ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class StorageSnapshotCtxConsts():
LUN_CFG_ACTION_DELETE = "delete"
LUN_CFG_ACTION_OFFLINE = "offline"
LUN_CFG_ACTION_ONLINE = "online"
LUN_CFG_ACTION_RESTORE_SNAPSHOT = "restore-snapshot"
LUN_CFG_ACTION_TRIGGERED = "triggered"
TS_CREATED_ = ""
class StorageSnapshotCtx(ManagedObject):
"""This is StorageSnapshotCtx class."""
consts = StorageSnapshotCtxConsts()
naming_props = set([])
mo_meta = MoMeta("StorageSnapshotCtx", "storageSnapshotCtx", "snap-ctx", VersionMeta.Version141a, "InputOutput", 0x1f, [], ["admin", "ls-compute", "ls-config", "ls-server", "ls-storage"], [u'storageScsiLun'], [], ["Get"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version141a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []),
"lun_cfg_action": MoPropertyMeta("lun_cfg_action", "lunCfgAction", "string", VersionMeta.Version141a, MoPropertyMeta.READ_WRITE, 0x4, None, None, None, ["delete", "offline", "online", "restore-snapshot", "triggered"], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []),
"snap_percent": MoPropertyMeta("snap_percent", "snapPercent", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []),
"src_lun_dn": MoPropertyMeta("src_lun_dn", "srcLunDn", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, 0, 256, None, [], []),
"src_lun_name": MoPropertyMeta("src_lun_name", "srcLunName", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version141a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
"ts_created": MoPropertyMeta("ts_created", "tsCreated", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, None, None, r"""([0-9]){4}-([0-9]){2}-([0-9]){2}T([0-9]){2}:([0-9]){2}:([0-9]){2}((\.([0-9]){3})){0,1}""", [""], []),
}
prop_map = {
"childAction": "child_action",
"dn": "dn",
"lunCfgAction": "lun_cfg_action",
"rn": "rn",
"snapPercent": "snap_percent",
"srcLunDn": "src_lun_dn",
"srcLunName": "src_lun_name",
"status": "status",
"tsCreated": "ts_created",
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.lun_cfg_action = None
self.snap_percent = None
self.src_lun_dn = None
self.src_lun_name = None
self.status = None
self.ts_created = None
ManagedObject.__init__(self, "StorageSnapshotCtx", parent_mo_or_dn, **kwargs)
| 54.508197 | 249 | 0.657444 |
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class StorageSnapshotCtxConsts():
LUN_CFG_ACTION_DELETE = "delete"
LUN_CFG_ACTION_OFFLINE = "offline"
LUN_CFG_ACTION_ONLINE = "online"
LUN_CFG_ACTION_RESTORE_SNAPSHOT = "restore-snapshot"
LUN_CFG_ACTION_TRIGGERED = "triggered"
TS_CREATED_ = ""
class StorageSnapshotCtx(ManagedObject):
consts = StorageSnapshotCtxConsts()
naming_props = set([])
mo_meta = MoMeta("StorageSnapshotCtx", "storageSnapshotCtx", "snap-ctx", VersionMeta.Version141a, "InputOutput", 0x1f, [], ["admin", "ls-compute", "ls-config", "ls-server", "ls-storage"], [u'storageScsiLun'], [], ["Get"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version141a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []),
"lun_cfg_action": MoPropertyMeta("lun_cfg_action", "lunCfgAction", "string", VersionMeta.Version141a, MoPropertyMeta.READ_WRITE, 0x4, None, None, None, ["delete", "offline", "online", "restore-snapshot", "triggered"], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []),
"snap_percent": MoPropertyMeta("snap_percent", "snapPercent", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []),
"src_lun_dn": MoPropertyMeta("src_lun_dn", "srcLunDn", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, 0, 256, None, [], []),
"src_lun_name": MoPropertyMeta("src_lun_name", "srcLunName", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version141a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
"ts_created": MoPropertyMeta("ts_created", "tsCreated", "string", VersionMeta.Version141a, MoPropertyMeta.READ_ONLY, None, None, None, r"""([0-9]){4}-([0-9]){2}-([0-9]){2}T([0-9]){2}:([0-9]){2}:([0-9]){2}((\.([0-9]){3})){0,1}""", [""], []),
}
prop_map = {
"childAction": "child_action",
"dn": "dn",
"lunCfgAction": "lun_cfg_action",
"rn": "rn",
"snapPercent": "snap_percent",
"srcLunDn": "src_lun_dn",
"srcLunName": "src_lun_name",
"status": "status",
"tsCreated": "ts_created",
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.lun_cfg_action = None
self.snap_percent = None
self.src_lun_dn = None
self.src_lun_name = None
self.status = None
self.ts_created = None
ManagedObject.__init__(self, "StorageSnapshotCtx", parent_mo_or_dn, **kwargs)
| true | true |
1c46d21702697c85163d3d5adbdd640e38fb9d31 | 417 | py | Python | tina/assimp/pfm.py | xuhao1/taichi_three | 25fdf047da4c93df36a047a0be3cc47225d328c9 | [
"MIT"
] | 152 | 2020-06-17T09:08:59.000Z | 2022-03-30T13:48:49.000Z | tina/assimp/pfm.py | xuhao1/taichi_three | 25fdf047da4c93df36a047a0be3cc47225d328c9 | [
"MIT"
] | 46 | 2020-06-20T15:15:57.000Z | 2022-03-24T20:03:18.000Z | tina/assimp/pfm.py | xuhao1/taichi_three | 25fdf047da4c93df36a047a0be3cc47225d328c9 | [
"MIT"
] | 27 | 2020-06-20T14:25:55.000Z | 2022-03-12T08:11:31.000Z | import numpy as np
import sys
def pfmwrite(path, im):
im = im.swapaxes(0, 1)
scale = max(1e-10, -im.min(), im.max())
h, w = im.shape[:2]
with open(path, 'wb') as f:
f.write(b'PF\n' if len(im.shape) >= 3 else b'Pf\n')
f.write(f'{w} {h}\n'.encode())
f.write(f'{scale if sys.byteorder == "big" else -scale}\n'.encode())
f.write((im / scale).astype(np.float32).tobytes())
| 32.076923 | 76 | 0.553957 | import numpy as np
import sys
def pfmwrite(path, im):
im = im.swapaxes(0, 1)
scale = max(1e-10, -im.min(), im.max())
h, w = im.shape[:2]
with open(path, 'wb') as f:
f.write(b'PF\n' if len(im.shape) >= 3 else b'Pf\n')
f.write(f'{w} {h}\n'.encode())
f.write(f'{scale if sys.byteorder == "big" else -scale}\n'.encode())
f.write((im / scale).astype(np.float32).tobytes())
| true | true |
1c46d21fab526fc9bb640abb06ed75334c27fafe | 677 | py | Python | setup.py | tianhuil/checkpoint | 842d1cff0cbe5926a36f1927fb75b5dcbaf4ec31 | [
"Apache-2.0"
] | null | null | null | setup.py | tianhuil/checkpoint | 842d1cff0cbe5926a36f1927fb75b5dcbaf4ec31 | [
"Apache-2.0"
] | null | null | null | setup.py | tianhuil/checkpoint | 842d1cff0cbe5926a36f1927fb75b5dcbaf4ec31 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
from distutils.core import setup
setup(
name='checkpoint',
version='0.1',
description='Setup',
author='Tianhui Michael Li',
author_email='test@example.com',
url='https://github.com/tianhuil/checkpoint/',
packages=['checkpoint'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| 27.08 | 57 | 0.646972 |
from distutils.core import setup
setup(
name='checkpoint',
version='0.1',
description='Setup',
author='Tianhui Michael Li',
author_email='test@example.com',
url='https://github.com/tianhuil/checkpoint/',
packages=['checkpoint'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| true | true |
1c46d3b7b10037122d1f0238ad1b6a580936df6a | 4,834 | py | Python | TestTickAlpha-Iota.py | nikorasen/Project_S.U.I.T.U.P. | 4f2873346bd3954d455e2e4e19a84f20c58d1ab2 | [
"MIT"
] | null | null | null | TestTickAlpha-Iota.py | nikorasen/Project_S.U.I.T.U.P. | 4f2873346bd3954d455e2e4e19a84f20c58d1ab2 | [
"MIT"
] | null | null | null | TestTickAlpha-Iota.py | nikorasen/Project_S.U.I.T.U.P. | 4f2873346bd3954d455e2e4e19a84f20c58d1ab2 | [
"MIT"
] | null | null | null | import tkinter as tk
import feedparser
import datetime
import time
from tkinter import messagebox
import re
def Spyder(): #Crawls the links in the sources file, saves them to a txt file
All_Articles=''
try:
with open('Sources.txt', 'r') as Srcs:
for line in Srcs:
Link=line
Link=Link.strip('\n') #removes any newline characters
Feed=feedparser.parse(Link)
for entry in Feed.entries:
try:
Art_Title=entry.title
except AttributeError:
Art_Title='n/a'
try:
Art_Auth=entry.author
except AttributeError:
try:
Art_Auth=entry.media
except AttributeError:
try:
Art_Auth=entry.generator
except AttributeError:
Art_Auth='n/a'
try:
Art_URL=entry.link
except AttributeError:
try:
Art_URL=entry.url
except AttributeError:
Art_URL='n/a'
try:
Post_Time=entry.pubdate
except AttributeError:
try:
Post_Time=entry.pubDate
except AttributeError:
try:
Post_Time=entry.published_parsed
except AttributeError:
Post_Time='n/a'
try:
Desc=entry.summary
except AttributeError:
try:
Desc=entry.description
except AttributeError:
Desc='n/a'
All_Articles+=' Title: '+str(Art_Title)+' Author: '+str(Art_Auth)+' Link: '+str(Art_URL)+' Posted: '+str(Post_Time)+' Summary: '+str(Desc)+'\n'
except EOFError:
pass
try:
with open('Art_Arch.txt', 'a') as Svd: #Saves the All_Articles string to a text file
Svd.write(All_Articles+'\n')
except FileNotFoundError:
with open('Art_Arch.txt', 'x') as Svd:
Svd.write(All_Articles+'\n')
def Strip_XML1(string): #Removes the XML characters from a passed string using a regex
XML_Chr=re.compile(r'[\s()-]+')
return XML_Chr.sub(' ', string)
def Strip_XML2(string): #Removes the XML characters from a passed string using a regex
XML_Chr=re.compile(r'<.*?>')
return XML_Chr.sub(' ', string)
Spyder()
root = tk.Tk()
root.geometry('1900x30')
root.wm_title('S.U.I.T.U.P. Newsdesk BETA Ticker')
svar = tk.StringVar()
labl = tk.Label(root, textvariable=svar, height=25, bg='#003b6f', fg='white')
strArticles=''
def shif():
shif.msg = shif.msg[1:] + shif.msg[0]
svar.set(shif.msg)
root.after(150, shif)
try:
with open('Art_Arch.txt', 'r') as Svd:
strCurr_Disp=''
for line in Svd:
strCurr_Disp=line
strCurr_Disp=strCurr_Disp.strip('\n')
strCurr_Disp=strCurr_Disp.strip('</a>')
strCurr_Disp=strCurr_Disp.strip('<a')
strCurr_Disp=strCurr_Disp.strip('</p>')
strCurr_Disp=strCurr_Disp.strip('<p>')
strCurr_Disp=strCurr_Disp.strip('</strong>')
strCurr_Disp=strCurr_Disp.strip('<p><img')
strCurr_Disp=strCurr_Disp.strip(' <p><img ')
strCurr_Disp=strCurr_Disp.strip(' <img ')
strCurr_Disp=strCurr_Disp.strip('<img width="300"')
strCurr_Disp=strCurr_Disp.strip('<img')
strCurr_Disp=strCurr_Disp.strip(' <img src=')
strCurr_Disp=strCurr_Disp.strip(' align="right" ')
strCurr_Disp=strCurr_Disp.strip(' hspace="20" ')
strCurr_Disp=strCurr_Disp.strip(' vspace="20" ')
strCurr_Disp=strCurr_Disp.strip('<td')
strCurr_Disp=strCurr_Disp.strip('</td')
strCurr_Disp=strCurr_Disp.strip('</td>')
strCurr_Disp=strCurr_Disp.strip('<br')
strCurr_Disp=strCurr_Disp.strip(' <br />')
strCurr_Disp=strCurr_Disp.strip(' <br ')
strCurr_Disp=strCurr_Disp.strip('MISC')
strCurr_Disp=strCurr_Disp.strip(' MISC ')
strCurr_Disp=strCurr_Disp.strip('</a')
strCurr_Disp=Strip_XML1(strCurr_Disp)
strCurr_Disp=Strip_XML2(strCurr_Disp)
strArticles=strArticles + str(strCurr_Disp)
shif.msg=(strArticles)
except EOFError:
pass
shif()
labl.pack()
root.mainloop()
| 40.621849 | 163 | 0.522342 | import tkinter as tk
import feedparser
import datetime
import time
from tkinter import messagebox
import re
def Spyder():
All_Articles=''
try:
with open('Sources.txt', 'r') as Srcs:
for line in Srcs:
Link=line
Link=Link.strip('\n')
Feed=feedparser.parse(Link)
for entry in Feed.entries:
try:
Art_Title=entry.title
except AttributeError:
Art_Title='n/a'
try:
Art_Auth=entry.author
except AttributeError:
try:
Art_Auth=entry.media
except AttributeError:
try:
Art_Auth=entry.generator
except AttributeError:
Art_Auth='n/a'
try:
Art_URL=entry.link
except AttributeError:
try:
Art_URL=entry.url
except AttributeError:
Art_URL='n/a'
try:
Post_Time=entry.pubdate
except AttributeError:
try:
Post_Time=entry.pubDate
except AttributeError:
try:
Post_Time=entry.published_parsed
except AttributeError:
Post_Time='n/a'
try:
Desc=entry.summary
except AttributeError:
try:
Desc=entry.description
except AttributeError:
Desc='n/a'
All_Articles+=' Title: '+str(Art_Title)+' Author: '+str(Art_Auth)+' Link: '+str(Art_URL)+' Posted: '+str(Post_Time)+' Summary: '+str(Desc)+'\n'
except EOFError:
pass
try:
with open('Art_Arch.txt', 'a') as Svd:
Svd.write(All_Articles+'\n')
except FileNotFoundError:
with open('Art_Arch.txt', 'x') as Svd:
Svd.write(All_Articles+'\n')
def Strip_XML1(string):
XML_Chr=re.compile(r'[\s()-]+')
return XML_Chr.sub(' ', string)
def Strip_XML2(string):
XML_Chr=re.compile(r'<.*?>')
return XML_Chr.sub(' ', string)
Spyder()
root = tk.Tk()
root.geometry('1900x30')
root.wm_title('S.U.I.T.U.P. Newsdesk BETA Ticker')
svar = tk.StringVar()
labl = tk.Label(root, textvariable=svar, height=25, bg='#003b6f', fg='white')
strArticles=''
def shif():
shif.msg = shif.msg[1:] + shif.msg[0]
svar.set(shif.msg)
root.after(150, shif)
try:
with open('Art_Arch.txt', 'r') as Svd:
strCurr_Disp=''
for line in Svd:
strCurr_Disp=line
strCurr_Disp=strCurr_Disp.strip('\n')
strCurr_Disp=strCurr_Disp.strip('</a>')
strCurr_Disp=strCurr_Disp.strip('<a')
strCurr_Disp=strCurr_Disp.strip('</p>')
strCurr_Disp=strCurr_Disp.strip('<p>')
strCurr_Disp=strCurr_Disp.strip('</strong>')
strCurr_Disp=strCurr_Disp.strip('<p><img')
strCurr_Disp=strCurr_Disp.strip(' <p><img ')
strCurr_Disp=strCurr_Disp.strip(' <img ')
strCurr_Disp=strCurr_Disp.strip('<img width="300"')
strCurr_Disp=strCurr_Disp.strip('<img')
strCurr_Disp=strCurr_Disp.strip(' <img src=')
strCurr_Disp=strCurr_Disp.strip(' align="right" ')
strCurr_Disp=strCurr_Disp.strip(' hspace="20" ')
strCurr_Disp=strCurr_Disp.strip(' vspace="20" ')
strCurr_Disp=strCurr_Disp.strip('<td')
strCurr_Disp=strCurr_Disp.strip('</td')
strCurr_Disp=strCurr_Disp.strip('</td>')
strCurr_Disp=strCurr_Disp.strip('<br')
strCurr_Disp=strCurr_Disp.strip(' <br />')
strCurr_Disp=strCurr_Disp.strip(' <br ')
strCurr_Disp=strCurr_Disp.strip('MISC')
strCurr_Disp=strCurr_Disp.strip(' MISC ')
strCurr_Disp=strCurr_Disp.strip('</a')
strCurr_Disp=Strip_XML1(strCurr_Disp)
strCurr_Disp=Strip_XML2(strCurr_Disp)
strArticles=strArticles + str(strCurr_Disp)
shif.msg=(strArticles)
except EOFError:
pass
shif()
labl.pack()
root.mainloop()
| true | true |
1c46d3bf5256bb38fc04428e212b3c747382289c | 27,516 | py | Python | exchangelib/autodiscover/discovery.py | denisovkv/exchangelib | fcb4cdac9f41e97f849ddab46ebf7cb9b6ca5d7f | [
"BSD-2-Clause"
] | null | null | null | exchangelib/autodiscover/discovery.py | denisovkv/exchangelib | fcb4cdac9f41e97f849ddab46ebf7cb9b6ca5d7f | [
"BSD-2-Clause"
] | null | null | null | exchangelib/autodiscover/discovery.py | denisovkv/exchangelib | fcb4cdac9f41e97f849ddab46ebf7cb9b6ca5d7f | [
"BSD-2-Clause"
] | null | null | null | import logging
import time
from urllib.parse import urlparse
import dns.resolver
from ..configuration import Configuration
from ..credentials import OAuth2Credentials
from ..errors import AutoDiscoverFailed, AutoDiscoverCircularRedirect, TransportError, RedirectError, UnauthorizedError
from ..protocol import Protocol, FailFast
from ..transport import get_auth_method_from_response, DEFAULT_HEADERS, NOAUTH, OAUTH2, CREDENTIALS_REQUIRED
from ..util import post_ratelimited, get_domain, get_redirect_url, _back_off_if_needed, _may_retry_on_error, \
is_valid_hostname, DummyResponse, CONNECTION_ERRORS, TLS_ERRORS
from ..version import Version
from .cache import autodiscover_cache
from .properties import Autodiscover
from .protocol import AutodiscoverProtocol
log = logging.getLogger(__name__)
def discover(email, credentials=None, auth_type=None, retry_policy=None):
return Autodiscovery(
email=email, credentials=credentials, auth_type=auth_type, retry_policy=retry_policy
).discover()
class SrvRecord:
"""A container for autodiscover-related SRV records in DNS"""
def __init__(self, priority, weight, port, srv):
self.priority = priority
self.weight = weight
self.port = port
self.srv = srv
def __eq__(self, other):
for k in self.__dict__.keys():
if getattr(self, k) != getattr(other, k):
return False
return True
class Autodiscovery:
"""Autodiscover is a Microsoft protocol for automatically getting the endpoint of the Exchange server and other
connection-related settings holding the email address using only the email address, and username and password of the
user.
For a description of the protocol implemented, see "Autodiscover for Exchange ActiveSync developers":
https://docs.microsoft.com/en-us/previous-versions/office/developer/exchange-server-interoperability-guidance/hh352638%28v%3dexchg.140%29
Descriptions of the steps from the article are provided in their respective methods in this class.
For a description of how to handle autodiscover error messages, see:
https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/handling-autodiscover-error-messages
A tip from the article:
The client can perform steps 1 through 4 in any order or in parallel to expedite the process, but it must wait for
responses to finish at each step before proceeding. Given that many organizations prefer to use the URL in step 2 to
set up the Autodiscover service, the client might try this step first.
Another possibly newer resource which has not yet been attempted is "Outlook 2016 Implementation of Autodiscover":
https://support.microsoft.com/en-us/help/3211279/outlook-2016-implementation-of-autodiscover
WARNING: The autodiscover protocol is very complicated. If you have problems autodiscovering using this
implementation, start by doing an official test at https://testconnectivity.microsoft.com
"""
# When connecting to servers that may not be serving the correct endpoint, we should use a retry policy that does
# not leave us hanging for a long time on each step in the protocol.
INITIAL_RETRY_POLICY = FailFast()
RETRY_WAIT = 10 # Seconds to wait before retry on connection errors
MAX_REDIRECTS = 10 # Maximum number of URL redirects before we give up
def __init__(self, email, credentials=None, auth_type=None, retry_policy=None):
"""
Args:
email: The email address to autodiscover
credentials: Credentials with authorization to make autodiscover lookups for this Account (Default value = None)
auth_type: (Default value = None)
retry_policy: (Default value = None)
"""
self.email = email
self.credentials = credentials
self.auth_type = auth_type # The auth type that the resulting protocol instance should have
self.retry_policy = retry_policy # The retry policy that the resulting protocol instance should have
self._urls_visited = [] # Collects HTTP and Autodiscover redirects
self._redirect_count = 0
self._emails_visited = [] # Collects Autodiscover email redirects
def discover(self):
self._emails_visited.append(self.email.lower())
# Check the autodiscover cache to see if we already know the autodiscover service endpoint for this email
# domain. Use a lock to guard against multiple threads competing to cache information.
log.debug('Waiting for autodiscover_cache lock')
with autodiscover_cache:
log.debug('autodiscover_cache lock acquired')
cache_key = self._cache_key
domain = get_domain(self.email)
if cache_key in autodiscover_cache:
ad_protocol = autodiscover_cache[cache_key]
log.debug('Cache hit for key %s: %s', cache_key, ad_protocol.service_endpoint)
try:
ad_response = self._quick(protocol=ad_protocol)
except AutoDiscoverFailed:
# Autodiscover no longer works with this domain. Clear cache and try again after releasing the lock
log.debug('AD request failure. Removing cache for key %s', cache_key)
del autodiscover_cache[cache_key]
ad_response = self._step_1(hostname=domain)
else:
# This will cache the result
ad_response = self._step_1(hostname=domain)
log.debug('Released autodiscover_cache_lock')
if ad_response.redirect_address:
log.debug('Got a redirect address: %s', ad_response.redirect_address)
if ad_response.redirect_address.lower() in self._emails_visited:
raise AutoDiscoverCircularRedirect('We were redirected to an email address we have already seen')
# Start over, but with the new email address
self.email = ad_response.redirect_address
return self.discover()
# We successfully received a response. Clear the cache of seen emails etc.
self.clear()
return self._build_response(ad_response=ad_response)
def clear(self):
# This resets cached variables
self._urls_visited = []
self._redirect_count = 0
self._emails_visited = []
@property
def _cache_key(self):
# We may be using multiple different credentials and changing our minds on TLS verification. This key
# combination should be safe for caching.
domain = get_domain(self.email)
return domain, self.credentials
def _build_response(self, ad_response):
ews_url = ad_response.protocol.ews_url
if not ews_url:
raise AutoDiscoverFailed("Response is missing an 'ews_url' value")
if not ad_response.autodiscover_smtp_address:
# Autodiscover does not always return an email address. In that case, the requesting email should be used
ad_response.user.autodiscover_smtp_address = self.email
# Get the server version. Not all protocol entries have a server version so we cheat a bit and also look at the
# other ones that point to the same endpoint.
for protocol in ad_response.account.protocols:
if not protocol.ews_url or not protocol.server_version:
continue
if protocol.ews_url.lower() == ews_url.lower():
version = Version(build=protocol.server_version)
break
else:
version = None
# We may not want to use the auth_package hints in the AD response. It could be incorrect and we can just guess.
protocol = Protocol(
config=Configuration(
service_endpoint=ews_url,
credentials=self.credentials,
version=version,
auth_type=self.auth_type,
retry_policy=self.retry_policy,
)
)
return ad_response, protocol
def _quick(self, protocol):
# Reset auth type and retry policy if we requested non-default values
if self.auth_type:
protocol.config.auth_type = self.auth_type
if self.retry_policy:
protocol.config.retry_policy = self.retry_policy
try:
r = self._get_authenticated_response(protocol=protocol)
except TransportError as e:
raise AutoDiscoverFailed('Response error: %s' % e)
if r.status_code == 200:
try:
ad = Autodiscover.from_bytes(bytes_content=r.content)
return self._step_5(ad=ad)
except ValueError as e:
raise AutoDiscoverFailed('Invalid response: %s' % e)
raise AutoDiscoverFailed('Invalid response code: %s' % r.status_code)
def _redirect_url_is_valid(self, url):
"""Three separate responses can be “Redirect responses”:
* An HTTP status code (301, 302) with a new URL
* An HTTP status code of 200, but with a payload XML containing a redirect to a different URL
* An HTTP status code of 200, but with a payload XML containing a different SMTP address as the target address
We only handle the HTTP 302 redirects here. We validate the URL received in the redirect response to ensure that
it does not redirect to non-SSL endpoints or SSL endpoints with invalid certificates, and that the redirect is
not circular. Finally, we should fail after 10 redirects.
Args:
url:
"""
if url.lower() in self._urls_visited:
log.warning('We have already tried this URL: %s', url)
return False
if self._redirect_count >= self.MAX_REDIRECTS:
log.warning('We reached max redirects at URL: %s', url)
return False
# We require TLS endpoints
if not url.startswith('https://'):
log.debug('Invalid scheme for URL: %s', url)
return False
# Quick test that the endpoint responds and that TLS handshake is OK
try:
self._get_unauthenticated_response(url, method='head')
except TransportError as e:
log.debug('Response error on redirect URL %s: %s', url, e)
return False
self._redirect_count += 1
return True
def _get_unauthenticated_response(self, url, method='post'):
"""Get auth type by tasting headers from the server. Do POST requests be default. HEAD is too error prone, and
some servers are set up to redirect to OWA on all requests except POST to the autodiscover endpoint.
Args:
url:
method: (Default value = 'post')
"""
# We are connecting to untrusted servers here, so take necessary precautions.
hostname = urlparse(url).netloc
if not is_valid_hostname(hostname, timeout=AutodiscoverProtocol.TIMEOUT):
# 'requests' is really bad at reporting that a hostname cannot be resolved. Let's check this separately.
# Don't retry on DNS errors. They will most likely be persistent.
raise TransportError('%r has no DNS entry' % hostname)
kwargs = dict(
url=url, headers=DEFAULT_HEADERS.copy(), allow_redirects=False, timeout=AutodiscoverProtocol.TIMEOUT
)
if method == 'post':
kwargs['data'] = Autodiscover.payload(email=self.email)
retry = 0
t_start = time.monotonic()
while True:
_back_off_if_needed(self.INITIAL_RETRY_POLICY.back_off_until)
log.debug('Trying to get response from %s', url)
with AutodiscoverProtocol.raw_session() as s:
try:
r = getattr(s, method)(**kwargs)
r.close() # Release memory
break
except TLS_ERRORS as e:
# Don't retry on TLS errors. They will most likely be persistent.
raise TransportError(str(e))
except CONNECTION_ERRORS as e:
r = DummyResponse(url=url, headers={}, request_headers=kwargs['headers'])
total_wait = time.monotonic() - t_start
if _may_retry_on_error(response=r, retry_policy=self.INITIAL_RETRY_POLICY, wait=total_wait):
log.debug("Connection error on URL %s (retry %s, error: %s). Cool down", url, retry, e)
self.INITIAL_RETRY_POLICY.back_off(self.RETRY_WAIT)
retry += 1
continue
else:
log.debug("Connection error on URL %s: %s", url, e)
raise TransportError(str(e))
try:
auth_type = get_auth_method_from_response(response=r)
except UnauthorizedError:
# Failed to guess the auth type
auth_type = NOAUTH
if r.status_code in (301, 302):
if 'location' in r.headers:
# Make the redirect URL absolute
try:
r.headers['location'] = get_redirect_url(r)
except TransportError:
del r.headers['location']
return auth_type, r
def _get_authenticated_response(self, protocol):
"""Get a response by using the credentials provided. We guess the auth type along the way.
Args:
protocol:
"""
# Redo the request with the correct auth
data = Autodiscover.payload(email=self.email)
# TODO: If Kerberos auth is set, we should set the X-ClientCanHandle='Negotiate' header. See
# https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/pox-autodiscover-request-for-exchange
headers = DEFAULT_HEADERS.copy()
try:
session = protocol.get_session()
r, session = post_ratelimited(protocol=protocol, session=session, url=protocol.service_endpoint,
headers=headers, data=data, allow_redirects=False, stream=False)
protocol.release_session(session)
except UnauthorizedError as e:
# It's entirely possible for the endpoint to ask for login. We should continue if login fails because this
# isn't necessarily the right endpoint to use.
raise TransportError(str(e))
except RedirectError as e:
r = DummyResponse(url=protocol.service_endpoint, headers={'location': e.url}, request_headers=None,
status_code=302)
return r
def _attempt_response(self, url):
"""Returns a (is_valid_response, response) tuple
Args:
url:
"""
self._urls_visited.append(url.lower())
log.debug('Attempting to get a valid response from %s', url)
try:
auth_type, r = self._get_unauthenticated_response(url=url)
if isinstance(self.credentials, OAuth2Credentials):
# This type of credentials *must* use the OAuth auth type
auth_type = OAUTH2
elif self.credentials is None and auth_type in CREDENTIALS_REQUIRED:
raise ValueError('Auth type %r was detected but no credentials were provided' % auth_type)
ad_protocol = AutodiscoverProtocol(
config=Configuration(
service_endpoint=url,
credentials=self.credentials,
auth_type=auth_type,
retry_policy=self.INITIAL_RETRY_POLICY,
)
)
if auth_type != NOAUTH:
r = self._get_authenticated_response(protocol=ad_protocol)
except TransportError as e:
log.debug('Failed to get a response: %s', e)
return False, None
if r.status_code in (301, 302) and 'location' in r.headers:
redirect_url = get_redirect_url(r)
if self._redirect_url_is_valid(url=redirect_url):
# The protocol does not specify this explicitly, but by looking at how testconnectivity.microsoft.com
# works, it seems that we should follow this URL now and try to get a valid response.
return self._attempt_response(url=redirect_url)
if r.status_code == 200:
try:
ad = Autodiscover.from_bytes(bytes_content=r.content)
# We got a valid response. Unless this is a URL redirect response, we cache the result
if ad.response is None or not ad.response.redirect_url:
cache_key = self._cache_key
log.debug('Adding cache entry for key %s: %s', cache_key, ad_protocol.service_endpoint)
autodiscover_cache[cache_key] = ad_protocol
return True, ad
except ValueError as e:
log.debug('Invalid response: %s', e)
return False, None
def _step_1(self, hostname):
"""The client sends an Autodiscover request to https://example.com/autodiscover/autodiscover.xml and then does
one of the following:
* If the Autodiscover attempt succeeds, the client proceeds to step 5.
* If the Autodiscover attempt fails, the client proceeds to step 2.
Args:
hostname:
"""
url = 'https://%s/Autodiscover/Autodiscover.xml' % hostname
log.info('Step 1: Trying autodiscover on %r with email %r', url, self.email)
is_valid_response, ad = self._attempt_response(url=url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_2(hostname=hostname)
def _step_2(self, hostname):
"""The client sends an Autodiscover request to https://autodiscover.example.com/autodiscover/autodiscover.xml
and then does one of the following:
* If the Autodiscover attempt succeeds, the client proceeds to step 5.
* If the Autodiscover attempt fails, the client proceeds to step 3.
Args:
hostname:
"""
url = 'https://autodiscover.%s/Autodiscover/Autodiscover.xml' % hostname
log.info('Step 2: Trying autodiscover on %r with email %r', url, self.email)
is_valid_response, ad = self._attempt_response(url=url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_3(hostname=hostname)
def _step_3(self, hostname):
"""The client sends an unauth'ed GET method request to
http://autodiscover.example.com/autodiscover/autodiscover.xml (Note that this is a non-HTTPS endpoint). The
client then does one of the following:
* If the GET request returns a 302 redirect response, it gets the redirection URL from the 'Location' HTTP
header and validates it as described in the "Redirect responses" section. The client then does one of the
following:
* If the redirection URL is valid, the client tries the URL and then does one of the following:
* If the attempt succeeds, the client proceeds to step 5.
* If the attempt fails, the client proceeds to step 4.
* If the redirection URL is not valid, the client proceeds to step 4.
* If the GET request does not return a 302 redirect response, the client proceeds to step 4.
Args:
hostname:
"""
url = 'http://autodiscover.%s/Autodiscover/Autodiscover.xml' % hostname
log.info('Step 3: Trying autodiscover on %r with email %r', url, self.email)
try:
_, r = self._get_unauthenticated_response(url=url, method='get')
except TransportError:
r = DummyResponse(url=url, headers={}, request_headers={})
if r.status_code in (301, 302) and 'location' in r.headers:
redirect_url = get_redirect_url(r)
if self._redirect_url_is_valid(url=redirect_url):
is_valid_response, ad = self._attempt_response(url=redirect_url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_4(hostname=hostname)
else:
return self._step_4(hostname=hostname)
else:
return self._step_4(hostname=hostname)
def _step_4(self, hostname):
"""The client performs a Domain Name System (DNS) query for an SRV record for _autodiscover._tcp.example.com.
The query might return multiple records. The client selects only records that point to an SSL endpoint and that
have the highest priority and weight. One of the following actions then occurs:
* If no such records are returned, the client proceeds to step 6.
* If records are returned, the application randomly chooses a record in the list and validates the endpoint
that it points to by following the process described in the "Redirect Response" section. The client then
does one of the following:
* If the redirection URL is valid, the client tries the URL and then does one of the following:
* If the attempt succeeds, the client proceeds to step 5.
* If the attempt fails, the client proceeds to step 6.
* If the redirection URL is not valid, the client proceeds to step 6.
Args:
hostname:
"""
dns_hostname = '_autodiscover._tcp.%s' % hostname
log.info('Step 4: Trying autodiscover on %r with email %r', dns_hostname, self.email)
srv_records = _get_srv_records(dns_hostname)
try:
srv_host = _select_srv_host(srv_records)
except ValueError:
srv_host = None
if not srv_host:
return self._step_6()
else:
redirect_url = 'https://%s/Autodiscover/Autodiscover.xml' % srv_host
if self._redirect_url_is_valid(url=redirect_url):
is_valid_response, ad = self._attempt_response(url=redirect_url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_6()
else:
return self._step_6()
def _step_5(self, ad):
"""When a valid Autodiscover request succeeds, the following sequence occurs:
* If the server responds with an HTTP 302 redirect, the client validates the redirection URL according to
the process defined in the "Redirect responses" and then does one of the following:
* If the redirection URL is valid, the client tries the URL and then does one of the following:
* If the attempt succeeds, the client repeats step 5 from the beginning.
* If the attempt fails, the client proceeds to step 6.
* If the redirection URL is not valid, the client proceeds to step 6.
* If the server responds with a valid Autodiscover response, the client does one of the following:
* If the value of the Action element is "Redirect", the client gets the redirection email address from
the Redirect element and then returns to step 1, using this new email address.
* If the value of the Action element is "Settings", the client has successfully received the requested
configuration settings for the specified user. The client does not need to proceed to step 6.
Args:
ad:
"""
log.info('Step 5: Checking response')
if ad.response is None:
# This is not explicit in the protocol, but let's raise errors here
ad.raise_errors()
ad_response = ad.response
if ad_response.redirect_url:
log.debug('Got a redirect URL: %s', ad_response.redirect_url)
# We are diverging a bit from the protocol here. We will never get an HTTP 302 since earlier steps already
# followed the redirects where possible. Instead, we handle retirect responses here.
if self._redirect_url_is_valid(url=ad_response.redirect_url):
is_valid_response, ad = self._attempt_response(url=ad_response.redirect_url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_6()
else:
log.debug('Invalid redirect URL: %s', ad_response.redirect_url)
return self._step_6()
else:
# This could be an email redirect. Let outer layer handle this
return ad_response
def _step_6(self):
"""If the client cannot contact the Autodiscover service, the client should ask the user for the Exchange server
name and use it to construct an Exchange EWS URL. The client should try to use this URL for future requests.
"""
raise AutoDiscoverFailed(
'All steps in the autodiscover protocol failed for email %r. If you think this is an error, consider doing '
'an official test at https://testconnectivity.microsoft.com' % self.email)
def _get_srv_records(hostname):
"""Send a DNS query for SRV entries for the hostname.
An SRV entry that has been formatted for autodiscovery will have the following format:
canonical name = mail.example.com.
service = 8 100 443 webmail.example.com.
The first three numbers in the service line are: priority, weight, port
Args:
hostname:
"""
log.debug('Attempting to get SRV records for %s', hostname)
resolver = dns.resolver.Resolver()
resolver.timeout = AutodiscoverProtocol.TIMEOUT
records = []
try:
answers = resolver.query('%s.' % hostname, 'SRV')
except (dns.resolver.NoNameservers, dns.resolver.NoAnswer, dns.resolver.NXDOMAIN) as e:
log.debug('DNS lookup failure: %s', e)
return records
for rdata in answers:
try:
vals = rdata.to_text().strip().rstrip('.').split(' ')
# Raise ValueError if the first three are not ints, and IndexError if there are less than 4 values
priority, weight, port, srv = int(vals[0]), int(vals[1]), int(vals[2]), vals[3]
record = SrvRecord(priority=priority, weight=weight, port=port, srv=srv)
log.debug('Found SRV record %s ', record)
records.append(record)
except (ValueError, IndexError):
log.debug('Incompatible SRV record for %s (%s)', hostname, rdata.to_text())
return records
def _select_srv_host(srv_records):
"""Select the record with the highest priority, that also supports TLS
Args:
srv_records:
"""
best_record = None
for srv_record in srv_records:
if srv_record.port != 443:
log.debug('Skipping SRV record %r (no TLS)', srv_record)
continue
# Assume port 443 will serve TLS. If not, autodiscover will probably also be broken for others.
if best_record is None or best_record.priority < srv_record.priority:
best_record = srv_record
if not best_record:
raise ValueError('No suitable records')
return best_record.srv
| 47.523316 | 141 | 0.641409 | import logging
import time
from urllib.parse import urlparse
import dns.resolver
from ..configuration import Configuration
from ..credentials import OAuth2Credentials
from ..errors import AutoDiscoverFailed, AutoDiscoverCircularRedirect, TransportError, RedirectError, UnauthorizedError
from ..protocol import Protocol, FailFast
from ..transport import get_auth_method_from_response, DEFAULT_HEADERS, NOAUTH, OAUTH2, CREDENTIALS_REQUIRED
from ..util import post_ratelimited, get_domain, get_redirect_url, _back_off_if_needed, _may_retry_on_error, \
is_valid_hostname, DummyResponse, CONNECTION_ERRORS, TLS_ERRORS
from ..version import Version
from .cache import autodiscover_cache
from .properties import Autodiscover
from .protocol import AutodiscoverProtocol
log = logging.getLogger(__name__)
def discover(email, credentials=None, auth_type=None, retry_policy=None):
return Autodiscovery(
email=email, credentials=credentials, auth_type=auth_type, retry_policy=retry_policy
).discover()
class SrvRecord:
def __init__(self, priority, weight, port, srv):
self.priority = priority
self.weight = weight
self.port = port
self.srv = srv
def __eq__(self, other):
for k in self.__dict__.keys():
if getattr(self, k) != getattr(other, k):
return False
return True
class Autodiscovery:
INITIAL_RETRY_POLICY = FailFast()
RETRY_WAIT = 10
MAX_REDIRECTS = 10
def __init__(self, email, credentials=None, auth_type=None, retry_policy=None):
self.email = email
self.credentials = credentials
self.auth_type = auth_type
self.retry_policy = retry_policy
self._urls_visited = []
self._redirect_count = 0
self._emails_visited = []
def discover(self):
self._emails_visited.append(self.email.lower())
log.debug('Waiting for autodiscover_cache lock')
with autodiscover_cache:
log.debug('autodiscover_cache lock acquired')
cache_key = self._cache_key
domain = get_domain(self.email)
if cache_key in autodiscover_cache:
ad_protocol = autodiscover_cache[cache_key]
log.debug('Cache hit for key %s: %s', cache_key, ad_protocol.service_endpoint)
try:
ad_response = self._quick(protocol=ad_protocol)
except AutoDiscoverFailed:
log.debug('AD request failure. Removing cache for key %s', cache_key)
del autodiscover_cache[cache_key]
ad_response = self._step_1(hostname=domain)
else:
ad_response = self._step_1(hostname=domain)
log.debug('Released autodiscover_cache_lock')
if ad_response.redirect_address:
log.debug('Got a redirect address: %s', ad_response.redirect_address)
if ad_response.redirect_address.lower() in self._emails_visited:
raise AutoDiscoverCircularRedirect('We were redirected to an email address we have already seen')
self.email = ad_response.redirect_address
return self.discover()
self.clear()
return self._build_response(ad_response=ad_response)
def clear(self):
self._urls_visited = []
self._redirect_count = 0
self._emails_visited = []
@property
def _cache_key(self):
domain = get_domain(self.email)
return domain, self.credentials
def _build_response(self, ad_response):
ews_url = ad_response.protocol.ews_url
if not ews_url:
raise AutoDiscoverFailed("Response is missing an 'ews_url' value")
if not ad_response.autodiscover_smtp_address:
ad_response.user.autodiscover_smtp_address = self.email
for protocol in ad_response.account.protocols:
if not protocol.ews_url or not protocol.server_version:
continue
if protocol.ews_url.lower() == ews_url.lower():
version = Version(build=protocol.server_version)
break
else:
version = None
protocol = Protocol(
config=Configuration(
service_endpoint=ews_url,
credentials=self.credentials,
version=version,
auth_type=self.auth_type,
retry_policy=self.retry_policy,
)
)
return ad_response, protocol
def _quick(self, protocol):
if self.auth_type:
protocol.config.auth_type = self.auth_type
if self.retry_policy:
protocol.config.retry_policy = self.retry_policy
try:
r = self._get_authenticated_response(protocol=protocol)
except TransportError as e:
raise AutoDiscoverFailed('Response error: %s' % e)
if r.status_code == 200:
try:
ad = Autodiscover.from_bytes(bytes_content=r.content)
return self._step_5(ad=ad)
except ValueError as e:
raise AutoDiscoverFailed('Invalid response: %s' % e)
raise AutoDiscoverFailed('Invalid response code: %s' % r.status_code)
def _redirect_url_is_valid(self, url):
if url.lower() in self._urls_visited:
log.warning('We have already tried this URL: %s', url)
return False
if self._redirect_count >= self.MAX_REDIRECTS:
log.warning('We reached max redirects at URL: %s', url)
return False
if not url.startswith('https://'):
log.debug('Invalid scheme for URL: %s', url)
return False
try:
self._get_unauthenticated_response(url, method='head')
except TransportError as e:
log.debug('Response error on redirect URL %s: %s', url, e)
return False
self._redirect_count += 1
return True
def _get_unauthenticated_response(self, url, method='post'):
hostname = urlparse(url).netloc
if not is_valid_hostname(hostname, timeout=AutodiscoverProtocol.TIMEOUT):
# Don't retry on DNS errors. They will most likely be persistent.
raise TransportError('%r has no DNS entry' % hostname)
kwargs = dict(
url=url, headers=DEFAULT_HEADERS.copy(), allow_redirects=False, timeout=AutodiscoverProtocol.TIMEOUT
)
if method == 'post':
kwargs['data'] = Autodiscover.payload(email=self.email)
retry = 0
t_start = time.monotonic()
while True:
_back_off_if_needed(self.INITIAL_RETRY_POLICY.back_off_until)
log.debug('Trying to get response from %s', url)
with AutodiscoverProtocol.raw_session() as s:
try:
r = getattr(s, method)(**kwargs)
r.close()
break
except TLS_ERRORS as e:
raise TransportError(str(e))
except CONNECTION_ERRORS as e:
r = DummyResponse(url=url, headers={}, request_headers=kwargs['headers'])
total_wait = time.monotonic() - t_start
if _may_retry_on_error(response=r, retry_policy=self.INITIAL_RETRY_POLICY, wait=total_wait):
log.debug("Connection error on URL %s (retry %s, error: %s). Cool down", url, retry, e)
self.INITIAL_RETRY_POLICY.back_off(self.RETRY_WAIT)
retry += 1
continue
else:
log.debug("Connection error on URL %s: %s", url, e)
raise TransportError(str(e))
try:
auth_type = get_auth_method_from_response(response=r)
except UnauthorizedError:
# Failed to guess the auth type
auth_type = NOAUTH
if r.status_code in (301, 302):
if 'location' in r.headers:
# Make the redirect URL absolute
try:
r.headers['location'] = get_redirect_url(r)
except TransportError:
del r.headers['location']
return auth_type, r
def _get_authenticated_response(self, protocol):
# Redo the request with the correct auth
data = Autodiscover.payload(email=self.email)
# TODO: If Kerberos auth is set, we should set the X-ClientCanHandle='Negotiate' header. See
# https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/pox-autodiscover-request-for-exchange
headers = DEFAULT_HEADERS.copy()
try:
session = protocol.get_session()
r, session = post_ratelimited(protocol=protocol, session=session, url=protocol.service_endpoint,
headers=headers, data=data, allow_redirects=False, stream=False)
protocol.release_session(session)
except UnauthorizedError as e:
# It's entirely possible for the endpoint to ask for login. We should continue if login fails because this
raise TransportError(str(e))
except RedirectError as e:
r = DummyResponse(url=protocol.service_endpoint, headers={'location': e.url}, request_headers=None,
status_code=302)
return r
def _attempt_response(self, url):
self._urls_visited.append(url.lower())
log.debug('Attempting to get a valid response from %s', url)
try:
auth_type, r = self._get_unauthenticated_response(url=url)
if isinstance(self.credentials, OAuth2Credentials):
# This type of credentials *must* use the OAuth auth type
auth_type = OAUTH2
elif self.credentials is None and auth_type in CREDENTIALS_REQUIRED:
raise ValueError('Auth type %r was detected but no credentials were provided' % auth_type)
ad_protocol = AutodiscoverProtocol(
config=Configuration(
service_endpoint=url,
credentials=self.credentials,
auth_type=auth_type,
retry_policy=self.INITIAL_RETRY_POLICY,
)
)
if auth_type != NOAUTH:
r = self._get_authenticated_response(protocol=ad_protocol)
except TransportError as e:
log.debug('Failed to get a response: %s', e)
return False, None
if r.status_code in (301, 302) and 'location' in r.headers:
redirect_url = get_redirect_url(r)
if self._redirect_url_is_valid(url=redirect_url):
# The protocol does not specify this explicitly, but by looking at how testconnectivity.microsoft.com
# works, it seems that we should follow this URL now and try to get a valid response.
return self._attempt_response(url=redirect_url)
if r.status_code == 200:
try:
ad = Autodiscover.from_bytes(bytes_content=r.content)
# We got a valid response. Unless this is a URL redirect response, we cache the result
if ad.response is None or not ad.response.redirect_url:
cache_key = self._cache_key
log.debug('Adding cache entry for key %s: %s', cache_key, ad_protocol.service_endpoint)
autodiscover_cache[cache_key] = ad_protocol
return True, ad
except ValueError as e:
log.debug('Invalid response: %s', e)
return False, None
def _step_1(self, hostname):
url = 'https://%s/Autodiscover/Autodiscover.xml' % hostname
log.info('Step 1: Trying autodiscover on %r with email %r', url, self.email)
is_valid_response, ad = self._attempt_response(url=url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_2(hostname=hostname)
def _step_2(self, hostname):
url = 'https://autodiscover.%s/Autodiscover/Autodiscover.xml' % hostname
log.info('Step 2: Trying autodiscover on %r with email %r', url, self.email)
is_valid_response, ad = self._attempt_response(url=url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_3(hostname=hostname)
def _step_3(self, hostname):
url = 'http://autodiscover.%s/Autodiscover/Autodiscover.xml' % hostname
log.info('Step 3: Trying autodiscover on %r with email %r', url, self.email)
try:
_, r = self._get_unauthenticated_response(url=url, method='get')
except TransportError:
r = DummyResponse(url=url, headers={}, request_headers={})
if r.status_code in (301, 302) and 'location' in r.headers:
redirect_url = get_redirect_url(r)
if self._redirect_url_is_valid(url=redirect_url):
is_valid_response, ad = self._attempt_response(url=redirect_url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_4(hostname=hostname)
else:
return self._step_4(hostname=hostname)
else:
return self._step_4(hostname=hostname)
def _step_4(self, hostname):
dns_hostname = '_autodiscover._tcp.%s' % hostname
log.info('Step 4: Trying autodiscover on %r with email %r', dns_hostname, self.email)
srv_records = _get_srv_records(dns_hostname)
try:
srv_host = _select_srv_host(srv_records)
except ValueError:
srv_host = None
if not srv_host:
return self._step_6()
else:
redirect_url = 'https://%s/Autodiscover/Autodiscover.xml' % srv_host
if self._redirect_url_is_valid(url=redirect_url):
is_valid_response, ad = self._attempt_response(url=redirect_url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_6()
else:
return self._step_6()
def _step_5(self, ad):
log.info('Step 5: Checking response')
if ad.response is None:
# This is not explicit in the protocol, but let's raise errors here
ad.raise_errors()
ad_response = ad.response
if ad_response.redirect_url:
log.debug('Got a redirect URL: %s', ad_response.redirect_url)
if self._redirect_url_is_valid(url=ad_response.redirect_url):
is_valid_response, ad = self._attempt_response(url=ad_response.redirect_url)
if is_valid_response:
return self._step_5(ad=ad)
else:
return self._step_6()
else:
log.debug('Invalid redirect URL: %s', ad_response.redirect_url)
return self._step_6()
else:
return ad_response
def _step_6(self):
raise AutoDiscoverFailed(
'All steps in the autodiscover protocol failed for email %r. If you think this is an error, consider doing '
'an official test at https://testconnectivity.microsoft.com' % self.email)
def _get_srv_records(hostname):
log.debug('Attempting to get SRV records for %s', hostname)
resolver = dns.resolver.Resolver()
resolver.timeout = AutodiscoverProtocol.TIMEOUT
records = []
try:
answers = resolver.query('%s.' % hostname, 'SRV')
except (dns.resolver.NoNameservers, dns.resolver.NoAnswer, dns.resolver.NXDOMAIN) as e:
log.debug('DNS lookup failure: %s', e)
return records
for rdata in answers:
try:
vals = rdata.to_text().strip().rstrip('.').split(' ')
priority, weight, port, srv = int(vals[0]), int(vals[1]), int(vals[2]), vals[3]
record = SrvRecord(priority=priority, weight=weight, port=port, srv=srv)
log.debug('Found SRV record %s ', record)
records.append(record)
except (ValueError, IndexError):
log.debug('Incompatible SRV record for %s (%s)', hostname, rdata.to_text())
return records
def _select_srv_host(srv_records):
best_record = None
for srv_record in srv_records:
if srv_record.port != 443:
log.debug('Skipping SRV record %r (no TLS)', srv_record)
continue
if best_record is None or best_record.priority < srv_record.priority:
best_record = srv_record
if not best_record:
raise ValueError('No suitable records')
return best_record.srv
| true | true |
1c46d49bbe5567ce4f5689afc64fec986b8a50d0 | 439 | py | Python | projects/golem_integration/tests/browser/find/find_element_not_found.py | kangchenwei/keyautotest2 | f980d46cabfc128b2099af3d33968f236923063f | [
"MIT"
] | null | null | null | projects/golem_integration/tests/browser/find/find_element_not_found.py | kangchenwei/keyautotest2 | f980d46cabfc128b2099af3d33968f236923063f | [
"MIT"
] | null | null | null | projects/golem_integration/tests/browser/find/find_element_not_found.py | kangchenwei/keyautotest2 | f980d46cabfc128b2099af3d33968f236923063f | [
"MIT"
] | null | null | null | from golem import actions
from golem.core.exceptions import ElementNotFound
description = 'Verify the webdriver.find method throws error when element is not found'
def test(data):
actions.navigate(data.env.url+'elements/')
browser = actions.get_browser()
selector = '.invalid-selector-value'
actions.step('Find element by css')
try:
elem = browser.find(css=selector)
except ElementNotFound:
pass
| 27.4375 | 87 | 0.71754 | from golem import actions
from golem.core.exceptions import ElementNotFound
description = 'Verify the webdriver.find method throws error when element is not found'
def test(data):
actions.navigate(data.env.url+'elements/')
browser = actions.get_browser()
selector = '.invalid-selector-value'
actions.step('Find element by css')
try:
elem = browser.find(css=selector)
except ElementNotFound:
pass
| true | true |
1c46d4f59678cd4c42ab336c2ddd37684bf8a54e | 580 | py | Python | tests/spline.py | parmes/solfec-2.0 | 3329d3e1e4d58fefaf976c04bab19284aef45bc2 | [
"MIT"
] | 1 | 2020-06-21T23:52:25.000Z | 2020-06-21T23:52:25.000Z | tests/spline.py | parmes/solfec-2.0 | 3329d3e1e4d58fefaf976c04bab19284aef45bc2 | [
"MIT"
] | 1 | 2020-05-01T14:44:01.000Z | 2020-05-01T23:50:36.000Z | tests/spline.py | parmes/solfec-2.0 | 3329d3e1e4d58fefaf976c04bab19284aef45bc2 | [
"MIT"
] | 2 | 2020-06-21T23:59:21.000Z | 2021-12-09T09:49:50.000Z | # Solfec-2.0 input command test: SPLINE
import sys, os
d0 = os.path.dirname(os.path.realpath(sys.argv[1]))
spl0 = SPLINE (os.path.join(d0,'spline.txt'));
spl1 = SPLINE (os.path.join(d0,'spline.txt'), cache = 10)
lst2 = [0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16];
spl2 = SPLINE (lst2);
lst3 = [[0, 10], [1, 11], [2, 12], [3, 13], [4, 14], [5, 15], [6, 16]];
spl3 = SPLINE (lst3);
lst4 = [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16)];
spl4 = SPLINE (lst3);
print_SPLINE(spl0)
print_SPLINE(spl1)
print_SPLINE(spl2)
print_SPLINE(spl3)
print_SPLINE(spl4)
| 26.363636 | 71 | 0.593103 |
import sys, os
d0 = os.path.dirname(os.path.realpath(sys.argv[1]))
spl0 = SPLINE (os.path.join(d0,'spline.txt'));
spl1 = SPLINE (os.path.join(d0,'spline.txt'), cache = 10)
lst2 = [0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16];
spl2 = SPLINE (lst2);
lst3 = [[0, 10], [1, 11], [2, 12], [3, 13], [4, 14], [5, 15], [6, 16]];
spl3 = SPLINE (lst3);
lst4 = [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16)];
spl4 = SPLINE (lst3);
print_SPLINE(spl0)
print_SPLINE(spl1)
print_SPLINE(spl2)
print_SPLINE(spl3)
print_SPLINE(spl4)
| true | true |
1c46d5eee6f5de64e17b1f5566525b7d8e6e6eb6 | 1,597 | py | Python | application/tictactoe/datastore.py | Deephan/tic-tac-toe-for-slack | d3aa7e9c2bc52d8afad6d8057ebb60373b100a78 | [
"Apache-2.0"
] | null | null | null | application/tictactoe/datastore.py | Deephan/tic-tac-toe-for-slack | d3aa7e9c2bc52d8afad6d8057ebb60373b100a78 | [
"Apache-2.0"
] | 4 | 2016-07-05T16:11:31.000Z | 2016-07-05T16:16:26.000Z | application/tictactoe/datastore.py | Deephan/tic-tac-toe-for-slack | d3aa7e9c2bc52d8afad6d8057ebb60373b100a78 | [
"Apache-2.0"
] | null | null | null | '''
datastore.py
Datastore module for the game of Tic-Tac-Toe
Note: This module currently does nothing. Work to be done to store the state of the game.
'''
class DataStore:
class State(ndb.Model):
""" Stores the current state of the board """
board = ndb.StringProperty()
moves = ndb.IntegerProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
def retrieveState():
query = State.query()
states = query.order(-State.date).fetch(1)
lastState = []
turns = None
# pass the board to play before you can serialize the current state
if len(states) > 0:
for state in states:
lastState = deserializeBoard(state.board)
turns = state.moves
else:
lastState = [['#','#','#'],['#','#','#'],['#','#','#']]
turns = 9
return (lastState, turns)
def storeState():
serialized_state = serializeBoard(currentState)
State(board = serialized_state, moves = turns).put()
return
def serializeBoard(board):
state = ""
for row in board:
for col in row:
state += col
return state
def deserializeBoard(state):
ROWS = COLS = 3
board = []
count = 0
while ROWS > 0:
row = []
while COLS > 0:
row.append(str(state[count]))
count += 1
COLS -= 1
board.append(row)
ROWS -= 1
COLS = 3
return board
| 27.067797 | 93 | 0.513463 |
class DataStore:
class State(ndb.Model):
board = ndb.StringProperty()
moves = ndb.IntegerProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
def retrieveState():
query = State.query()
states = query.order(-State.date).fetch(1)
lastState = []
turns = None
if len(states) > 0:
for state in states:
lastState = deserializeBoard(state.board)
turns = state.moves
else:
lastState = [['#','#','#'],['#','#','#'],['#','#','#']]
turns = 9
return (lastState, turns)
def storeState():
serialized_state = serializeBoard(currentState)
State(board = serialized_state, moves = turns).put()
return
def serializeBoard(board):
state = ""
for row in board:
for col in row:
state += col
return state
def deserializeBoard(state):
ROWS = COLS = 3
board = []
count = 0
while ROWS > 0:
row = []
while COLS > 0:
row.append(str(state[count]))
count += 1
COLS -= 1
board.append(row)
ROWS -= 1
COLS = 3
return board
| true | true |
1c46d65620086f1fc1ed2ef78050ec11a4ddc8ca | 670 | py | Python | pythran/tests/cases/projection_simplex.py | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 1,647 | 2015-01-13T01:45:38.000Z | 2022-03-28T01:23:41.000Z | pythran/tests/cases/projection_simplex.py | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 1,116 | 2015-01-01T09:52:05.000Z | 2022-03-18T21:06:40.000Z | pythran/tests/cases/projection_simplex.py | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 180 | 2015-02-12T02:47:28.000Z | 2022-03-14T10:28:18.000Z | #from https://gist.github.com/mblondel/c99e575a5207c76a99d714e8c6e08e89
#pythran export projection_simplex(float[], int)
#runas import numpy as np; np.random.seed(0); x = np.random.rand(10); projection_simplex(x, 1)
import numpy as np
def projection_simplex(v, z=1):
"""
Old implementation for test and benchmark purposes.
The arguments v and z should be a vector and a scalar, respectively.
"""
n_features = v.shape[0]
u = np.sort(v)[::-1]
cssv = np.cumsum(u) - z
ind = np.arange(n_features) + 1
cond = u - cssv / ind > 0
rho = ind[cond][-1]
theta = cssv[cond][-1] / float(rho)
w = np.maximum(v - theta, 0)
return w
| 33.5 | 94 | 0.653731 |
import numpy as np
def projection_simplex(v, z=1):
n_features = v.shape[0]
u = np.sort(v)[::-1]
cssv = np.cumsum(u) - z
ind = np.arange(n_features) + 1
cond = u - cssv / ind > 0
rho = ind[cond][-1]
theta = cssv[cond][-1] / float(rho)
w = np.maximum(v - theta, 0)
return w
| true | true |
1c46d68712cfe5660bca7d1c26bdad8cf4708df8 | 3,921 | py | Python | feedler/admin.py | pcoder/public-health-ch | cebc4849653560c54238b67814074353ff7c01f3 | [
"MIT"
] | 2 | 2020-10-29T16:27:21.000Z | 2021-06-07T12:47:46.000Z | feedler/admin.py | pcoder/public-health-ch | cebc4849653560c54238b67814074353ff7c01f3 | [
"MIT"
] | 11 | 2017-05-09T10:50:28.000Z | 2021-12-15T17:01:23.000Z | feedler/admin.py | pcoder/public-health-ch | cebc4849653560c54238b67814074353ff7c01f3 | [
"MIT"
] | 4 | 2017-04-24T13:06:55.000Z | 2021-06-04T02:18:32.000Z | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.conf.urls import url
from django.urls import reverse
from django.utils.functional import cached_property
from django.utils.translation import ugettext as _
from django.shortcuts import redirect
from wagtail.admin import messages
from wagtail.contrib.modeladmin.helpers import AdminURLHelper, ButtonHelper
from wagtail.contrib.modeladmin.options import ModelAdmin
from wagtail.contrib.modeladmin.views import IndexView
from wagtail.core.models import Site
from feedler.models import Entry
from feedler.refresh import refresh_streams
from feedler.models.admin import FeedlySettings
class RefreshButtonHelper(ButtonHelper):
"""
This helper constructs a refresh button
"""
button_classnames = ['icon', 'icon-download']
def refresh_button(self, classnames_add=None, classnames_exclude=None):
if classnames_add is None: classnames_add = []
if classnames_exclude is None: classnames_exclude = []
classnames = self.button_classnames + classnames_add
cn = self.finalise_classname(classnames, classnames_exclude)
text = _('Sync {}'.format(self.verbose_name_plural.title()))
return {
'url': self.url_helper.get_action_url('refresh', query_params=self.request.GET),
'label': text, 'classname': cn, 'title': text,
}
class RefreshAdminURLHelper(AdminURLHelper):
"""
This helper constructs the different urls, to overwrite the default behaviour
and append the filters to the action.
"""
non_object_specific_actions = ('create', 'choose_parent', 'index', 'refresh')
def get_action_url(self, action, *args, **kwargs):
query_params = kwargs.pop('query_params', None)
url_name = self.get_action_url_name(action)
if action in self.non_object_specific_actions:
url = reverse(url_name)
else:
url = reverse(url_name, args=args, kwargs=kwargs)
if query_params:
url += '?{params}'.format(params=query_params.urlencode())
return url
def get_action_url_pattern(self, action):
if action in self.non_object_specific_actions:
return self._get_action_url_pattern(action)
return self._get_object_specific_action_url_pattern(action)
class RefreshView(IndexView):
"""
A Class Based View which will handle the button click
"""
# def export_csv(self):
# data = self.queryset.all()
# response = ...
# return response
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
super().dispatch(request, *args, **kwargs)
site = Site.find_for_request(request)
if not refresh_streams(FeedlySettings.for_site(site)):
messages.error(
request, _('Sorry, could not refresh streams. Please try again in a few minutes, then contact support if the issue persists.'))
return redirect('/admin/feedler/entry/')
class EntryModelAdminMixin(object):
"""
A mixin to add to your model admin which hooks the different helpers, the view
and register the new urls.
"""
button_helper_class = RefreshButtonHelper
url_helper_class = RefreshAdminURLHelper
view_class = RefreshView
def get_admin_urls_for_registration(self):
urls = super().get_admin_urls_for_registration()
urls += (
url(
self.url_helper.get_action_url_pattern('refresh'),
self.refresh_view,
name=self.url_helper.get_action_url_name('refresh')
),
)
return urls
def refresh_view(self, request):
kwargs = {'model_admin': self}
view_class = self.view_class
return view_class.as_view(**kwargs)(request)
| 38.821782 | 143 | 0.694211 |
from django.db import models
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.conf.urls import url
from django.urls import reverse
from django.utils.functional import cached_property
from django.utils.translation import ugettext as _
from django.shortcuts import redirect
from wagtail.admin import messages
from wagtail.contrib.modeladmin.helpers import AdminURLHelper, ButtonHelper
from wagtail.contrib.modeladmin.options import ModelAdmin
from wagtail.contrib.modeladmin.views import IndexView
from wagtail.core.models import Site
from feedler.models import Entry
from feedler.refresh import refresh_streams
from feedler.models.admin import FeedlySettings
class RefreshButtonHelper(ButtonHelper):
button_classnames = ['icon', 'icon-download']
def refresh_button(self, classnames_add=None, classnames_exclude=None):
if classnames_add is None: classnames_add = []
if classnames_exclude is None: classnames_exclude = []
classnames = self.button_classnames + classnames_add
cn = self.finalise_classname(classnames, classnames_exclude)
text = _('Sync {}'.format(self.verbose_name_plural.title()))
return {
'url': self.url_helper.get_action_url('refresh', query_params=self.request.GET),
'label': text, 'classname': cn, 'title': text,
}
class RefreshAdminURLHelper(AdminURLHelper):
non_object_specific_actions = ('create', 'choose_parent', 'index', 'refresh')
def get_action_url(self, action, *args, **kwargs):
query_params = kwargs.pop('query_params', None)
url_name = self.get_action_url_name(action)
if action in self.non_object_specific_actions:
url = reverse(url_name)
else:
url = reverse(url_name, args=args, kwargs=kwargs)
if query_params:
url += '?{params}'.format(params=query_params.urlencode())
return url
def get_action_url_pattern(self, action):
if action in self.non_object_specific_actions:
return self._get_action_url_pattern(action)
return self._get_object_specific_action_url_pattern(action)
class RefreshView(IndexView):
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
super().dispatch(request, *args, **kwargs)
site = Site.find_for_request(request)
if not refresh_streams(FeedlySettings.for_site(site)):
messages.error(
request, _('Sorry, could not refresh streams. Please try again in a few minutes, then contact support if the issue persists.'))
return redirect('/admin/feedler/entry/')
class EntryModelAdminMixin(object):
button_helper_class = RefreshButtonHelper
url_helper_class = RefreshAdminURLHelper
view_class = RefreshView
def get_admin_urls_for_registration(self):
urls = super().get_admin_urls_for_registration()
urls += (
url(
self.url_helper.get_action_url_pattern('refresh'),
self.refresh_view,
name=self.url_helper.get_action_url_name('refresh')
),
)
return urls
def refresh_view(self, request):
kwargs = {'model_admin': self}
view_class = self.view_class
return view_class.as_view(**kwargs)(request)
| true | true |
1c46d82743933279d3da7a04509b37c438837201 | 1,295 | py | Python | wazimap/tests/test_geo.py | anoited007/country-dashboard | 577bbcc4992e24c484650895fabbcdf4343e1bdb | [
"MIT"
] | 16 | 2017-10-19T03:36:41.000Z | 2022-03-03T11:46:20.000Z | wazimap/tests/test_geo.py | ChrisAchinga/wazimap | a66a1524030a8b98e7ea0dfb270d1946ca75b3b2 | [
"MIT"
] | 66 | 2016-02-15T08:59:29.000Z | 2017-09-21T14:00:43.000Z | wazimap/tests/test_geo.py | ChrisAchinga/wazimap | a66a1524030a8b98e7ea0dfb270d1946ca75b3b2 | [
"MIT"
] | 18 | 2017-10-06T12:26:37.000Z | 2021-08-30T01:38:37.000Z | from django.test import TestCase
from django.conf import settings
from wazimap.geo import geo_data, GeoData
class GeoTestCase(TestCase):
def test_versioned_geos(self):
# create two geos at different versions
cpt11 = geo_data.geo_model.objects.create(geo_level='municipality', geo_code='cpt', long_name='City of Cape Town', version='2011')
cpt16 = geo_data.geo_model.objects.create(geo_level='municipality', geo_code='cpt', long_name='City of Cape Town', version='2016')
self.assertEquals(cpt16, geo_data.get_geography('cpt', 'municipality'))
self.assertEquals(cpt11, geo_data.get_geography('cpt', 'municipality', '2011'))
self.assertEquals(cpt16, geo_data.get_geography('cpt', 'municipality', '2016'))
def test_geometry(self):
# if the geometry_data is missing the version, we should raise an error
settings.WAZIMAP['geometry_data'] = {'country': 'geo/country.geojson'}
with self.assertRaises(ValueError):
GeoData()
# if the geometry_data is missing the version, we should raise an error
# raises an attribute error from line 188 geo.py
settings.WAZIMAP['geometry_data'] = {'': 'geo/country.geojson'}
with self.assertRaises(AttributeError):
GeoData()
| 43.166667 | 138 | 0.695753 | from django.test import TestCase
from django.conf import settings
from wazimap.geo import geo_data, GeoData
class GeoTestCase(TestCase):
def test_versioned_geos(self):
cpt11 = geo_data.geo_model.objects.create(geo_level='municipality', geo_code='cpt', long_name='City of Cape Town', version='2011')
cpt16 = geo_data.geo_model.objects.create(geo_level='municipality', geo_code='cpt', long_name='City of Cape Town', version='2016')
self.assertEquals(cpt16, geo_data.get_geography('cpt', 'municipality'))
self.assertEquals(cpt11, geo_data.get_geography('cpt', 'municipality', '2011'))
self.assertEquals(cpt16, geo_data.get_geography('cpt', 'municipality', '2016'))
def test_geometry(self):
settings.WAZIMAP['geometry_data'] = {'country': 'geo/country.geojson'}
with self.assertRaises(ValueError):
GeoData()
settings.WAZIMAP['geometry_data'] = {'': 'geo/country.geojson'}
with self.assertRaises(AttributeError):
GeoData()
| true | true |
1c46d8fd89313610b00380ac3e01e23cbd64aab7 | 11,884 | py | Python | chemdataextractor/cli/pos.py | gubschk/CDEWIP | fb628593417df5f955eb1fa62176b7cb3c322ebc | [
"MIT"
] | null | null | null | chemdataextractor/cli/pos.py | gubschk/CDEWIP | fb628593417df5f955eb1fa62176b7cb3c322ebc | [
"MIT"
] | null | null | null | chemdataextractor/cli/pos.py | gubschk/CDEWIP | fb628593417df5f955eb1fa62176b7cb3c322ebc | [
"MIT"
] | 1 | 2021-02-21T02:51:39.000Z | 2021-02-21T02:51:39.000Z | # -*- coding: utf-8 -*-
"""
chemdataextractor.cli.pos
~~~~~~~~~~~~~~~~~~~~~~~~~
Part of speech tagging commands.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import click
from ..doc import Document, Text
from ..nlp.corpus import genia_training, wsj_training, wsj_evaluation, genia_evaluation
from ..nlp.pos import TAGS, ChemApPosTagger, ChemCrfPosTagger
log = logging.getLogger(__name__)
@click.group(name='pos')
@click.pass_context
def pos_cli(ctx):
"""POS tagger commands."""
pass
@pos_cli.command()
@click.option('--output', '-o', help='Output model file.', required=True)
@click.pass_context
def train_all(ctx, output):
"""Train POS tagger on WSJ, GENIA, and both. With and without cluster features."""
click.echo('chemdataextractor.pos.train_all')
click.echo('Output: %s' % output)
ctx.invoke(train, output='%s_wsj_nocluster.pickle' % output, corpus='wsj', clusters=False)
ctx.invoke(train, output='%s_wsj.pickle' % output, corpus='wsj', clusters=True)
ctx.invoke(train, output='%s_genia_nocluster.pickle' % output, corpus='genia', clusters=False)
ctx.invoke(train, output='%s_genia.pickle' % output, corpus='genia', clusters=True)
ctx.invoke(train, output='%s_wsj_genia_nocluster.pickle' % output, corpus='wsj+genia', clusters=False)
ctx.invoke(train, output='%s_wsj_genia.pickle' % output, corpus='wsj+genia', clusters=True)
@pos_cli.command()
@click.argument('model', required=True)
@click.pass_context
def evaluate_all(ctx, model):
"""Evaluate POS taggers on WSJ and GENIA."""
click.echo('chemdataextractor.pos.evaluate_all')
click.echo('Model: %s' % model)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_wsj.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_wsj.pickle' % model, corpus='genia', clusters=True)
ctx.invoke(evaluate, model='%s_genia_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_genia_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_genia.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_genia.pickle' % model, corpus='genia', clusters=True)
ctx.invoke(evaluate, model='%s_wsj_genia_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_genia_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_genia.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_wsj_genia.pickle' % model, corpus='genia', clusters=True)
@pos_cli.command()
@click.option('--output', '-o', help='Output model file.', required=True)
@click.option('--corpus', type=click.Choice(['wsj', 'genia', 'wsj+genia']), help='Training corpus')
@click.option('--clusters/--no-clusters', help='Whether to use cluster features', default=True)
@click.pass_context
def train(ctx, output, corpus, clusters):
"""Train POS Tagger."""
click.echo('chemdataextractor.pos.train')
click.echo('Output: %s' % output)
click.echo('Corpus: %s' % corpus)
click.echo('Clusters: %s' % clusters)
wsj_sents = []
genia_sents = []
if corpus == 'wsj' or corpus == 'wsj+genia':
wsj_sents = list(wsj_training.tagged_sents())
# For WSJ, remove all tokens with -NONE- tag
for i, wsj_sent in enumerate(wsj_sents):
wsj_sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
if corpus == 'genia' or corpus == 'wsj+genia':
genia_sents = list(genia_training.tagged_sents())
# Translate GENIA
for i, genia_sent in enumerate(genia_sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
genia_sents[i][j] = (token, '-LRB-') # ( to -RLB- (also do for evaluation)
elif tag == ')':
genia_sents[i][j] = (token, '-RRB-') # ) to -RRB- (also do for evaluation)
elif tag == 'CT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == 'XT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == '-':
genia_sents[i][j] = (token, ':') # Single hyphen character for dash
elif tag == 'N':
genia_sents[i][j] = (token, 'NN') # Typo?
elif tag == 'PP':
genia_sents[i][j] = (token, 'PRP') # Typo?
elif tag == '' and token == ')':
genia_sents[i][j] = (token, '-RRB-') # Typo?
elif tag == '' and token == 'IFN-gamma':
genia_sents[i][j] = (token, 'NN') # Typo?
elif '|' in tag:
genia_sents[i][j] = (token, tag.split('|')[0]) # If contains |, choose first part
# Filter any tags not in the allowed tagset (Shouldn't be any left anyway)
genia_sents[i] = [t for t in genia_sent if t[1] in TAGS]
if corpus == 'wsj':
training_corpus = wsj_sents
elif corpus == 'genia':
training_corpus = genia_sents
elif corpus == 'wsj+genia':
training_corpus = wsj_sents + genia_sents
else:
raise click.ClickException('Invalid corpus')
tagger = ChemCrfPosTagger(clusters=clusters)
tagger.train(training_corpus, output)
@pos_cli.command()
@click.argument('model', required=True)
@click.option('--corpus', type=click.Choice(['wsj', 'genia']), help='Evaluation corpus')
@click.option('--clusters/--no-clusters', help='Whether to use cluster features', default=True)
@click.pass_context
def evaluate(ctx, model, corpus, clusters):
"""Evaluate performance of POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
sents[i][j] = (token, '-LRB-')
elif tag == ')':
sents[i][j] = (token, '-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemCrfPosTagger(model=model, clusters=clusters)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy))
@pos_cli.command()
@click.option('--output', '-o', type=click.File('wb'), help='Output model file.', required=True)
@click.option('--corpus', type=click.Choice(['wsj', 'genia', 'wsj+genia']), help='Training corpus')
@click.option('--clusters/--no-clusters', help='Whether to use cluster features', default=True)
@click.pass_obj
def train_perceptron(ctx, output, corpus, clusters):
"""Train Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.train')
click.echo('Output: %s' % output)
click.echo('Corpus: %s' % corpus)
click.echo('Clusters: %s' % clusters)
wsj_sents = []
genia_sents = []
if corpus == 'wsj' or corpus == 'wsj+genia':
wsj_sents = list(wsj_training.tagged_sents())
# For WSJ, remove all tokens with -NONE- tag
for i, wsj_sent in enumerate(wsj_sents):
wsj_sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
if corpus == 'genia' or corpus == 'wsj+genia':
genia_sents = list(genia_training.tagged_sents())
# Translate GENIA
for i, genia_sent in enumerate(genia_sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
genia_sents[i][j] = (token, '-LRB-') # ( to -RLB- (also do for evaluation)
elif tag == ')':
genia_sents[i][j] = (token, '-RRB-') # ) to -RRB- (also do for evaluation)
elif tag == 'CT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == 'XT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == '-':
genia_sents[i][j] = (token, ':') # Single hyphen character for dash
elif tag == 'N':
genia_sents[i][j] = (token, 'NN') # Typo?
elif tag == 'PP':
genia_sents[i][j] = (token, 'PRP') # Typo?
elif tag == '' and token == ')':
genia_sents[i][j] = (token, '-RRB-') # Typo?
elif tag == '' and token == 'IFN-gamma':
genia_sents[i][j] = (token, 'NN') # Typo?
elif '|' in tag:
genia_sents[i][j] = (token, tag.split('|')[0]) # If contains |, choose first part
# Filter any tags not in the allowed tagset (Shouldn't be any left anyway)
genia_sents[i] = [t for t in genia_sent if t[1] in TAGS]
if corpus == 'wsj':
training_corpus = wsj_sents
elif corpus == 'genia':
training_corpus = genia_sents
elif corpus == 'wsj+genia':
training_corpus = wsj_sents + genia_sents
else:
raise click.ClickException('Invalid corpus')
tagger = ChemApPosTagger(clusters=clusters)
tagger.train(training_corpus)
tagger.save(output)
@pos_cli.command()
@click.argument('model', required=True)
@click.option('--corpus', type=click.Choice(['wsj', 'genia']), help='Evaluation corpus')
@click.pass_obj
def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == u'-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == u'(':
sents[i][j] = (token, u'-LRB-')
elif tag == u')':
sents[i][j] = (token, u'-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemApPosTagger(model=model)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy))
@pos_cli.command()
@click.option('--output', '-o', type=click.File('w', encoding='utf8'), help='Output file.', default=click.get_text_stream('stdout'))
@click.argument('input', type=click.File('rb'), default=click.get_binary_stream('stdin'))
@click.pass_obj
def tag(ctx, input, output):
"""Output POS-tagged tokens."""
log.info('chemdataextractor.pos.tag')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences:
output.write(u' '.join(u'/'.join([token, tag]) for token, tag in sentence.pos_tagged_tokens))
output.write(u'\n')
| 44.676692 | 133 | 0.588186 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import click
from ..doc import Document, Text
from ..nlp.corpus import genia_training, wsj_training, wsj_evaluation, genia_evaluation
from ..nlp.pos import TAGS, ChemApPosTagger, ChemCrfPosTagger
log = logging.getLogger(__name__)
@click.group(name='pos')
@click.pass_context
def pos_cli(ctx):
pass
@pos_cli.command()
@click.option('--output', '-o', help='Output model file.', required=True)
@click.pass_context
def train_all(ctx, output):
click.echo('chemdataextractor.pos.train_all')
click.echo('Output: %s' % output)
ctx.invoke(train, output='%s_wsj_nocluster.pickle' % output, corpus='wsj', clusters=False)
ctx.invoke(train, output='%s_wsj.pickle' % output, corpus='wsj', clusters=True)
ctx.invoke(train, output='%s_genia_nocluster.pickle' % output, corpus='genia', clusters=False)
ctx.invoke(train, output='%s_genia.pickle' % output, corpus='genia', clusters=True)
ctx.invoke(train, output='%s_wsj_genia_nocluster.pickle' % output, corpus='wsj+genia', clusters=False)
ctx.invoke(train, output='%s_wsj_genia.pickle' % output, corpus='wsj+genia', clusters=True)
@pos_cli.command()
@click.argument('model', required=True)
@click.pass_context
def evaluate_all(ctx, model):
click.echo('chemdataextractor.pos.evaluate_all')
click.echo('Model: %s' % model)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_wsj.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_wsj.pickle' % model, corpus='genia', clusters=True)
ctx.invoke(evaluate, model='%s_genia_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_genia_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_genia.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_genia.pickle' % model, corpus='genia', clusters=True)
ctx.invoke(evaluate, model='%s_wsj_genia_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_genia_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_genia.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_wsj_genia.pickle' % model, corpus='genia', clusters=True)
@pos_cli.command()
@click.option('--output', '-o', help='Output model file.', required=True)
@click.option('--corpus', type=click.Choice(['wsj', 'genia', 'wsj+genia']), help='Training corpus')
@click.option('--clusters/--no-clusters', help='Whether to use cluster features', default=True)
@click.pass_context
def train(ctx, output, corpus, clusters):
click.echo('chemdataextractor.pos.train')
click.echo('Output: %s' % output)
click.echo('Corpus: %s' % corpus)
click.echo('Clusters: %s' % clusters)
wsj_sents = []
genia_sents = []
if corpus == 'wsj' or corpus == 'wsj+genia':
wsj_sents = list(wsj_training.tagged_sents())
for i, wsj_sent in enumerate(wsj_sents):
wsj_sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
if corpus == 'genia' or corpus == 'wsj+genia':
genia_sents = list(genia_training.tagged_sents())
for i, genia_sent in enumerate(genia_sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
genia_sents[i][j] = (token, '-LRB-')
elif tag == ')':
genia_sents[i][j] = (token, '-RRB-')
elif tag == 'CT':
genia_sents[i][j] = (token, 'DT')
elif tag == 'XT':
genia_sents[i][j] = (token, 'DT')
elif tag == '-':
genia_sents[i][j] = (token, ':')
elif tag == 'N':
genia_sents[i][j] = (token, 'NN')
elif tag == 'PP':
genia_sents[i][j] = (token, 'PRP')
elif tag == '' and token == ')':
genia_sents[i][j] = (token, '-RRB-')
elif tag == '' and token == 'IFN-gamma':
genia_sents[i][j] = (token, 'NN')
elif '|' in tag:
genia_sents[i][j] = (token, tag.split('|')[0])
genia_sents[i] = [t for t in genia_sent if t[1] in TAGS]
if corpus == 'wsj':
training_corpus = wsj_sents
elif corpus == 'genia':
training_corpus = genia_sents
elif corpus == 'wsj+genia':
training_corpus = wsj_sents + genia_sents
else:
raise click.ClickException('Invalid corpus')
tagger = ChemCrfPosTagger(clusters=clusters)
tagger.train(training_corpus, output)
@pos_cli.command()
@click.argument('model', required=True)
@click.option('--corpus', type=click.Choice(['wsj', 'genia']), help='Evaluation corpus')
@click.option('--clusters/--no-clusters', help='Whether to use cluster features', default=True)
@click.pass_context
def evaluate(ctx, model, corpus, clusters):
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
sents[i][j] = (token, '-LRB-')
elif tag == ')':
sents[i][j] = (token, '-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemCrfPosTagger(model=model, clusters=clusters)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy))
@pos_cli.command()
@click.option('--output', '-o', type=click.File('wb'), help='Output model file.', required=True)
@click.option('--corpus', type=click.Choice(['wsj', 'genia', 'wsj+genia']), help='Training corpus')
@click.option('--clusters/--no-clusters', help='Whether to use cluster features', default=True)
@click.pass_obj
def train_perceptron(ctx, output, corpus, clusters):
click.echo('chemdataextractor.pos.train')
click.echo('Output: %s' % output)
click.echo('Corpus: %s' % corpus)
click.echo('Clusters: %s' % clusters)
wsj_sents = []
genia_sents = []
if corpus == 'wsj' or corpus == 'wsj+genia':
wsj_sents = list(wsj_training.tagged_sents())
# For WSJ, remove all tokens with -NONE- tag
for i, wsj_sent in enumerate(wsj_sents):
wsj_sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
if corpus == 'genia' or corpus == 'wsj+genia':
genia_sents = list(genia_training.tagged_sents())
# Translate GENIA
for i, genia_sent in enumerate(genia_sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
genia_sents[i][j] = (token, '-LRB-') # ( to -RLB- (also do for evaluation)
elif tag == ')':
genia_sents[i][j] = (token, '-RRB-') # ) to -RRB- (also do for evaluation)
elif tag == 'CT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == 'XT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == '-':
genia_sents[i][j] = (token, ':') # Single hyphen character for dash
elif tag == 'N':
genia_sents[i][j] = (token, 'NN') # Typo?
elif tag == 'PP':
genia_sents[i][j] = (token, 'PRP') # Typo?
elif tag == '' and token == ')':
genia_sents[i][j] = (token, '-RRB-') # Typo?
elif tag == '' and token == 'IFN-gamma':
genia_sents[i][j] = (token, 'NN') # Typo?
elif '|' in tag:
genia_sents[i][j] = (token, tag.split('|')[0]) # If contains |, choose first part
# Filter any tags not in the allowed tagset (Shouldn't be any left anyway)
genia_sents[i] = [t for t in genia_sent if t[1] in TAGS]
if corpus == 'wsj':
training_corpus = wsj_sents
elif corpus == 'genia':
training_corpus = genia_sents
elif corpus == 'wsj+genia':
training_corpus = wsj_sents + genia_sents
else:
raise click.ClickException('Invalid corpus')
tagger = ChemApPosTagger(clusters=clusters)
tagger.train(training_corpus)
tagger.save(output)
@pos_cli.command()
@click.argument('model', required=True)
@click.option('--corpus', type=click.Choice(['wsj', 'genia']), help='Evaluation corpus')
@click.pass_obj
def evaluate_perceptron(ctx, model, corpus):
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == u'-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == u'(':
sents[i][j] = (token, u'-LRB-')
elif tag == u')':
sents[i][j] = (token, u'-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemApPosTagger(model=model)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy))
@pos_cli.command()
@click.option('--output', '-o', type=click.File('w', encoding='utf8'), help='Output file.', default=click.get_text_stream('stdout'))
@click.argument('input', type=click.File('rb'), default=click.get_binary_stream('stdin'))
@click.pass_obj
def tag(ctx, input, output):
log.info('chemdataextractor.pos.tag')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences:
output.write(u' '.join(u'/'.join([token, tag]) for token, tag in sentence.pos_tagged_tokens))
output.write(u'\n')
| true | true |
1c46da710b690df0d6804fd81ba494ce167bd99d | 394 | py | Python | serempre_todo/task/api/views.py | pygabo/Serempre | 6b29e337abd8d1b3f71ee889d318a2d473d6c744 | [
"MIT"
] | null | null | null | serempre_todo/task/api/views.py | pygabo/Serempre | 6b29e337abd8d1b3f71ee889d318a2d473d6c744 | [
"MIT"
] | null | null | null | serempre_todo/task/api/views.py | pygabo/Serempre | 6b29e337abd8d1b3f71ee889d318a2d473d6c744 | [
"MIT"
] | null | null | null | # Rest Framework
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
# Serializer
from serempre_todo.task.api.serializers import TaskSerializer
# Model
from serempre_todo.task.models import Task
class TaskViewSet(viewsets.ModelViewSet):
serializer_class = TaskSerializer
permission_classes = [IsAuthenticated]
queryset = Task.objects.all()
| 26.266667 | 61 | 0.819797 |
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from serempre_todo.task.api.serializers import TaskSerializer
from serempre_todo.task.models import Task
class TaskViewSet(viewsets.ModelViewSet):
serializer_class = TaskSerializer
permission_classes = [IsAuthenticated]
queryset = Task.objects.all()
| true | true |
1c46db55722edfbae9a686a7bac404d67cd50321 | 3,930 | py | Python | contractor_plugins/Manual/models.py | T3kton/contractor_plugins | a42c87f4d0713b2a461739f528f92fa572a7fec7 | [
"MIT"
] | null | null | null | contractor_plugins/Manual/models.py | T3kton/contractor_plugins | a42c87f4d0713b2a461739f528f92fa572a7fec7 | [
"MIT"
] | null | null | null | contractor_plugins/Manual/models.py | T3kton/contractor_plugins | a42c87f4d0713b2a461739f528f92fa572a7fec7 | [
"MIT"
] | 2 | 2017-05-05T03:39:11.000Z | 2018-05-11T13:06:25.000Z | from django.db import models
from django.core.exceptions import ValidationError
from cinp.orm_django import DjangoCInP as CInP
from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST
from contractor.BluePrint.models import FoundationBluePrint
from contractor_plugins.Manual.module import set_power, power_state, wait_for_poweroff
cinp = CInP( 'Manual', '0.1' )
FOUNDATION_SUBCLASS_LIST.append( 'manualfoundation' )
FOUNDATION_SUBCLASS_LIST.append( 'manualcomplexedfoundation' )
COMPLEX_SUBCLASS_LIST.append( 'manualcomplex' )
@cinp.model( property_list=( 'state', 'type' ) )
class ManualComplex( Complex ):
@property
def subclass( self ):
return self
@property
def type( self ):
return 'Manual'
def newFoundation( self, hostname ):
foundation = ManualComplexedFoundation( site=self.site, blueprint=FoundationBluePrint.objects.get( pk='manual-foundation-base' ), locator=hostname )
foundation.complex_host = self
foundation.full_clean()
foundation.save()
return foundation
@cinp.check_auth()
@staticmethod
def checkAuth( user, method, id_list, action=None ):
return True
def clean( self, *args, **kwargs ):
super().clean( *args, **kwargs )
errors = {}
if errors:
raise ValidationError( errors )
def __str__( self ):
return 'ManualComplex {0}'.format( self.pk )
@cinp.model( property_list=( 'state', 'type', 'class_list' ) )
class ManualFoundation( Foundation ):
@staticmethod
def getTscriptValues( write_mode=False ): # locator is handled seperatly
result = super( ManualFoundation, ManualFoundation ).getTscriptValues( write_mode )
return result
@staticmethod
def getTscriptFunctions():
result = super( ManualFoundation, ManualFoundation ).getTscriptFunctions()
result[ 'power_on' ] = lambda foundation: ( 'manual', set_power( foundation, 'on' ) )
result[ 'power_off' ] = lambda foundation: ( 'manual', set_power( foundation, 'off' ) )
result[ 'power_state' ] = lambda foundation: ( 'manual', power_state( foundation ) )
result[ 'wait_for_poweroff' ] = lambda foundation: ( 'manual', wait_for_poweroff( foundation ) )
return result
def configAttributes( self ):
result = super().configAttributes()
return result
@property
def subclass( self ):
return self
@property
def type( self ):
return 'Manual'
@property
def class_list( self ):
return [ 'Metal', 'VM', 'Container', 'Switch', 'Manual' ]
@cinp.list_filter( name='site', paramater_type_list=[ { 'type': 'Model', 'model': Site } ] )
@staticmethod
def filter_site( site ):
return ManualFoundation.objects.filter( site=site )
@cinp.check_auth()
@staticmethod
def checkAuth( user, method, id_list, action=None ):
return True
def __str__( self ):
return 'ManualFoundation {0}'.format( self.pk )
@cinp.model( property_list=( 'state', 'type', 'class_list' ) )
class ManualComplexedFoundation( Foundation ):
complex_host = models.ForeignKey( ManualComplex, on_delete=models.PROTECT )
def configAttributes( self ):
result = super().configAttributes()
result.update( { '_complex_host': self.complex_host.name } )
return result
@property
def subclass( self ):
return self
@property
def type( self ):
return 'ManualComplex'
@property
def class_list( self ):
return [ 'ManualComplex' ]
@property
def complex( self ):
return self.complex_host
@cinp.list_filter( name='site', paramater_type_list=[ { 'type': 'Model', 'model': Site } ] )
@staticmethod
def filter_site( site ):
return ManualComplexedFoundation.objects.filter( site=site )
@cinp.check_auth()
@staticmethod
def checkAuth( user, method, id_list, action=None ):
return True
def __str__( self ):
return 'ManualComplexedFoundation {0}'.format( self.pk )
| 28.071429 | 152 | 0.708142 | from django.db import models
from django.core.exceptions import ValidationError
from cinp.orm_django import DjangoCInP as CInP
from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST
from contractor.BluePrint.models import FoundationBluePrint
from contractor_plugins.Manual.module import set_power, power_state, wait_for_poweroff
cinp = CInP( 'Manual', '0.1' )
FOUNDATION_SUBCLASS_LIST.append( 'manualfoundation' )
FOUNDATION_SUBCLASS_LIST.append( 'manualcomplexedfoundation' )
COMPLEX_SUBCLASS_LIST.append( 'manualcomplex' )
@cinp.model( property_list=( 'state', 'type' ) )
class ManualComplex( Complex ):
@property
def subclass( self ):
return self
@property
def type( self ):
return 'Manual'
def newFoundation( self, hostname ):
foundation = ManualComplexedFoundation( site=self.site, blueprint=FoundationBluePrint.objects.get( pk='manual-foundation-base' ), locator=hostname )
foundation.complex_host = self
foundation.full_clean()
foundation.save()
return foundation
@cinp.check_auth()
@staticmethod
def checkAuth( user, method, id_list, action=None ):
return True
def clean( self, *args, **kwargs ):
super().clean( *args, **kwargs )
errors = {}
if errors:
raise ValidationError( errors )
def __str__( self ):
return 'ManualComplex {0}'.format( self.pk )
@cinp.model( property_list=( 'state', 'type', 'class_list' ) )
class ManualFoundation( Foundation ):
@staticmethod
def getTscriptValues( write_mode=False ):
result = super( ManualFoundation, ManualFoundation ).getTscriptValues( write_mode )
return result
@staticmethod
def getTscriptFunctions():
result = super( ManualFoundation, ManualFoundation ).getTscriptFunctions()
result[ 'power_on' ] = lambda foundation: ( 'manual', set_power( foundation, 'on' ) )
result[ 'power_off' ] = lambda foundation: ( 'manual', set_power( foundation, 'off' ) )
result[ 'power_state' ] = lambda foundation: ( 'manual', power_state( foundation ) )
result[ 'wait_for_poweroff' ] = lambda foundation: ( 'manual', wait_for_poweroff( foundation ) )
return result
def configAttributes( self ):
result = super().configAttributes()
return result
@property
def subclass( self ):
return self
@property
def type( self ):
return 'Manual'
@property
def class_list( self ):
return [ 'Metal', 'VM', 'Container', 'Switch', 'Manual' ]
@cinp.list_filter( name='site', paramater_type_list=[ { 'type': 'Model', 'model': Site } ] )
@staticmethod
def filter_site( site ):
return ManualFoundation.objects.filter( site=site )
@cinp.check_auth()
@staticmethod
def checkAuth( user, method, id_list, action=None ):
return True
def __str__( self ):
return 'ManualFoundation {0}'.format( self.pk )
@cinp.model( property_list=( 'state', 'type', 'class_list' ) )
class ManualComplexedFoundation( Foundation ):
complex_host = models.ForeignKey( ManualComplex, on_delete=models.PROTECT )
def configAttributes( self ):
result = super().configAttributes()
result.update( { '_complex_host': self.complex_host.name } )
return result
@property
def subclass( self ):
return self
@property
def type( self ):
return 'ManualComplex'
@property
def class_list( self ):
return [ 'ManualComplex' ]
@property
def complex( self ):
return self.complex_host
@cinp.list_filter( name='site', paramater_type_list=[ { 'type': 'Model', 'model': Site } ] )
@staticmethod
def filter_site( site ):
return ManualComplexedFoundation.objects.filter( site=site )
@cinp.check_auth()
@staticmethod
def checkAuth( user, method, id_list, action=None ):
return True
def __str__( self ):
return 'ManualComplexedFoundation {0}'.format( self.pk )
| true | true |
1c46dbb5413dcfd3678d4b0e6bd04adac93c69db | 1,330 | py | Python | src/shardBackup/copy.py | babarnescocke/shardBackup | ff62869ffd319b627edf2a2a4f5084ed19713f03 | [
"BSD-3-Clause"
] | null | null | null | src/shardBackup/copy.py | babarnescocke/shardBackup | ff62869ffd319b627edf2a2a4f5084ed19713f03 | [
"BSD-3-Clause"
] | null | null | null | src/shardBackup/copy.py | babarnescocke/shardBackup | ff62869ffd319b627edf2a2a4f5084ed19713f03 | [
"BSD-3-Clause"
] | null | null | null | from subprocess import run
from sys import exit
from shutil import copy2
import os # for unclear reasons importing just os.stat and os.chown doesn't work
import stat
def rsync(fobject0, fobject1): # takes two file objects and transmits 0 to 1
"""
a call to copying using rsync
>>>rsync('./.gitkeep','/other/')
rsync output....
"""
try:
run(['rsync', #rsync is a major program
'-avzz', #a = archive, v= verbose, zz=compress
'-n', # n = simulate
'--info=progress2', # prints info such as how fast it is downloading
fobject0,
fobject1
])
except:
print(f"Unable to launch rsync copying - despite finding rsync installed")
exit(1)
def copy(fobject0, fobject1): #copies file and then changes perms/owner - https://stackoverflow.com/questions/19787348/copy-file-keep-permissions-and-owner
"""
a function that copies and keeps group and owner attributes
>>>copy("file0", "file1")
"""
try:
copy2(fobject0, fobject1) # copy file
st = os.stat(fobject0) # make variable of source file attributes
os.chown(fobject1, st[stat.ST_UID], st[stat.ST_GID]) #
except:
print(f"Unable to copy {fobject0} to {fobject1}. I told you it was in alpha.")
exit(1) | 35.945946 | 155 | 0.626316 | from subprocess import run
from sys import exit
from shutil import copy2
import os
import stat
def rsync(fobject0, fobject1): # takes two file objects and transmits 0 to 1
try:
run(['rsync', #rsync is a major program
'-avzz', #a = archive, v= verbose, zz=compress
'-n', # n = simulate
'--info=progress2', # prints info such as how fast it is downloading
fobject0,
fobject1
])
except:
print(f"Unable to launch rsync copying - despite finding rsync installed")
exit(1)
def copy(fobject0, fobject1): #copies file and then changes perms/owner - https://stackoverflow.com/questions/19787348/copy-file-keep-permissions-and-owner
try:
copy2(fobject0, fobject1) # copy file
st = os.stat(fobject0) # make variable of source file attributes
os.chown(fobject1, st[stat.ST_UID], st[stat.ST_GID]) #
except:
print(f"Unable to copy {fobject0} to {fobject1}. I told you it was in alpha.")
exit(1) | true | true |
1c46dc5e623025be88f670a423523abba08c29d5 | 1,368 | py | Python | Diabetes_API/app.py | 18bce1151/proj | 96c0a299ccaec29a02a9486d192a7215f5a12566 | [
"Unlicense"
] | 86 | 2020-11-26T17:38:51.000Z | 2022-03-10T11:35:08.000Z | Diabetes_API/app.py | 18bce1151/proj | 96c0a299ccaec29a02a9486d192a7215f5a12566 | [
"Unlicense"
] | null | null | null | Diabetes_API/app.py | 18bce1151/proj | 96c0a299ccaec29a02a9486d192a7215f5a12566 | [
"Unlicense"
] | 62 | 2020-11-27T05:16:06.000Z | 2022-03-27T15:23:55.000Z | from flask import Flask, render_template, url_for, flash, redirect
import joblib
from flask import request
import numpy as np
app = Flask(__name__, template_folder='templates')
@app.route("/")
@app.route("/Diabetes")
def cancer():
return render_template("diabetes.html")
def ValuePredictor(to_predict_list, size):
to_predict = np.array(to_predict_list).reshape(1,size)
if(size==6):
loaded_model = joblib.load(r'C:\Users\Mahesh Sharma\Desktop\HealthApp\Indivisual_Deployment\Diabetes_API\diabetes_model.pkl')
result = loaded_model.predict(to_predict)
return result[0]
@app.route('/predict', methods = ["POST"])
def predict():
if request.method == "POST":
to_predict_list = request.form.to_dict()
to_predict_list = list(to_predict_list.values())
to_predict_list = list(map(float, to_predict_list))
#diabetes
if(len(to_predict_list)==6):
result = ValuePredictor(to_predict_list,6)
if(int(result)==1):
prediction = "Sorry you chances of getting the disease. Please consult the doctor immediately"
else:
prediction = "No need to fear. You have no dangerous symptoms of the disease"
return(render_template("result.html", prediction_text=prediction))
if __name__ == "__main__":
app.run(debug=True)
| 35.076923 | 134 | 0.679094 | from flask import Flask, render_template, url_for, flash, redirect
import joblib
from flask import request
import numpy as np
app = Flask(__name__, template_folder='templates')
@app.route("/")
@app.route("/Diabetes")
def cancer():
return render_template("diabetes.html")
def ValuePredictor(to_predict_list, size):
to_predict = np.array(to_predict_list).reshape(1,size)
if(size==6):
loaded_model = joblib.load(r'C:\Users\Mahesh Sharma\Desktop\HealthApp\Indivisual_Deployment\Diabetes_API\diabetes_model.pkl')
result = loaded_model.predict(to_predict)
return result[0]
@app.route('/predict', methods = ["POST"])
def predict():
if request.method == "POST":
to_predict_list = request.form.to_dict()
to_predict_list = list(to_predict_list.values())
to_predict_list = list(map(float, to_predict_list))
if(len(to_predict_list)==6):
result = ValuePredictor(to_predict_list,6)
if(int(result)==1):
prediction = "Sorry you chances of getting the disease. Please consult the doctor immediately"
else:
prediction = "No need to fear. You have no dangerous symptoms of the disease"
return(render_template("result.html", prediction_text=prediction))
if __name__ == "__main__":
app.run(debug=True)
| true | true |
1c46ded6115ecd16b3a79fe253d63b64f0698442 | 18,126 | py | Python | python/cloudtik/tests/test_cloudtik.py | jerrychenhf/cloudtik | 5ceab948c5c8b2e00f644d2fb801311572aaf381 | [
"Apache-2.0"
] | 2 | 2022-03-28T05:03:57.000Z | 2022-03-28T09:00:48.000Z | python/cloudtik/tests/test_cloudtik.py | jerrychenhf/cloudtik | 5ceab948c5c8b2e00f644d2fb801311572aaf381 | [
"Apache-2.0"
] | 12 | 2022-03-29T05:07:18.000Z | 2022-03-31T13:57:57.000Z | python/cloudtik/tests/test_cloudtik.py | jerrychenhf/cloudtik | 5ceab948c5c8b2e00f644d2fb801311572aaf381 | [
"Apache-2.0"
] | 6 | 2022-03-28T05:04:24.000Z | 2022-03-29T01:22:22.000Z | from enum import Enum
import os
import re
from subprocess import CalledProcessError
import tempfile
import threading
import time
import unittest
import yaml
import copy
from jsonschema.exceptions import ValidationError
from typing import Dict, Callable, List, Optional
from cloudtik.core._private.utils import prepare_config, validate_config
from cloudtik.core._private.cluster import cluster_operator
from cloudtik.core._private.cluster.cluster_metrics import ClusterMetrics
from cloudtik.core._private.providers import (
_NODE_PROVIDERS, _DEFAULT_CONFIGS)
from cloudtik.core.tags import CLOUDTIK_TAG_NODE_KIND, CLOUDTIK_TAG_NODE_STATUS, \
CLOUDTIK_TAG_USER_NODE_TYPE, CLOUDTIK_TAG_CLUSTER_NAME
from cloudtik.core.node_provider import NodeProvider
import grpc
import pytest
class DrainNodeOutcome(str, Enum):
"""Potential outcomes of DrainNode calls, each of which is handled
differently by the clusterscaler.
"""
# Return a reponse indicating all nodes were succesfully drained.
Succeeded = "Succeeded"
# Return response indicating at least one node failed to be drained.
NotAllDrained = "NotAllDrained"
# Return an unimplemented gRPC error, indicating an old GCS.
Unimplemented = "Unimplemented"
# Raise a generic unexpected RPC error.
GenericRpcError = "GenericRpcError"
# Raise a generic unexpected exception.
GenericException = "GenericException"
class MockRpcException(grpc.RpcError):
"""Mock RpcError with a specified status code.
Note: It might be possible to do this already with standard tools
in the `grpc` module, but how wasn't immediately obvious to me.
"""
def __init__(self, status_code: grpc.StatusCode):
self.status_code = status_code
def code(self):
return self.status_code
class CloudTikTestTimeoutException(Exception):
"""Exception used to identify timeouts from test utilities."""
pass
class MockNode:
def __init__(self, node_id, tags, node_config, node_type,
unique_ips=False):
self.node_id = node_id
self.state = "pending"
self.tags = tags
self.external_ip = "1.2.3.4"
self.internal_ip = "172.0.0.{}".format(self.node_id)
if unique_ips:
self.external_ip = f"1.2.3.{self.node_id}"
self.node_config = node_config
self.node_type = node_type
def matches(self, tags):
for k, v in tags.items():
if k not in self.tags or self.tags[k] != v:
return False
return True
class MockProcessRunner:
def __init__(self, fail_cmds=None, cmd_to_callback=None, print_out=False):
self.calls = []
self.cmd_to_callback = cmd_to_callback or {
} # type: Dict[str, Callable]
self.print_out = print_out
self.fail_cmds = fail_cmds or []
self.call_response = {}
self.ready_to_run = threading.Event()
self.ready_to_run.set()
self.lock = threading.RLock()
def check_call(self, cmd, *args, **kwargs):
with self.lock:
self.ready_to_run.wait()
self.calls.append(cmd)
if self.print_out:
print(f">>>Process runner: Executing \n {str(cmd)}")
for token in self.cmd_to_callback:
if token in str(cmd):
# Trigger a callback if token is in cmd.
# Can be used to simulate background events during a node
# update (e.g. node disconnected).
callback = self.cmd_to_callback[token]
callback()
for token in self.fail_cmds:
if token in str(cmd):
raise CalledProcessError(1, token,
"Failing command on purpose")
def check_output(self, cmd):
with self.lock:
self.check_call(cmd)
return_string = "command-output"
key_to_shrink = None
for pattern, response_list in self.call_response.items():
if pattern in str(cmd):
return_string = response_list[0]
key_to_shrink = pattern
break
if key_to_shrink:
self.call_response[key_to_shrink] = self.call_response[
key_to_shrink][1:]
if len(self.call_response[key_to_shrink]) == 0:
del self.call_response[key_to_shrink]
return return_string.encode()
def assert_has_call(self,
ip: str,
pattern: Optional[str] = None,
exact: Optional[List[str]] = None):
"""Checks if the given value was called by this process runner.
NOTE: Either pattern or exact must be specified, not both!
Args:
ip: IP address of the node that the given call was executed on.
pattern: RegEx that matches one specific call.
exact: List of strings that when joined exactly match one call.
"""
with self.lock:
assert bool(pattern) ^ bool(exact), \
"Must specify either a pattern or exact match."
debug_output = ""
if pattern is not None:
for cmd in self.command_history():
if ip in cmd:
debug_output += cmd
debug_output += "\n"
if re.search(pattern, cmd):
return True
else:
raise Exception(
f"Did not find [{pattern}] in [{debug_output}] for "
f"ip={ip}.\n\nFull output: {self.command_history()}")
elif exact is not None:
exact_cmd = " ".join(exact)
for cmd in self.command_history():
if ip in cmd:
debug_output += cmd
debug_output += "\n"
if cmd == exact_cmd:
return True
raise Exception(
f"Did not find [{exact_cmd}] in [{debug_output}] for "
f"ip={ip}.\n\nFull output: {self.command_history()}")
def assert_not_has_call(self, ip: str, pattern: str):
"""Ensure that the given regex pattern was never called.
"""
with self.lock:
out = ""
for cmd in self.command_history():
if ip in cmd:
out += cmd
out += "\n"
if re.search(pattern, out):
raise Exception("Found [{}] in [{}] for {}".format(
pattern, out, ip))
else:
return True
def clear_history(self):
with self.lock:
self.calls = []
def command_history(self):
with self.lock:
return [" ".join(cmd) for cmd in self.calls]
def respond_to_call(self, pattern, response_list):
with self.lock:
self.call_response[pattern] = response_list
class MockProvider(NodeProvider):
def __init__(self, cache_stopped=False, unique_ips=False):
self.mock_nodes = {}
self.next_id = 0
self.throw = False
self.error_creates = False
self.fail_creates = False
self.ready_to_create = threading.Event()
self.ready_to_create.set()
self.cache_stopped = cache_stopped
self.unique_ips = unique_ips
# Many of these functions are called by node_launcher or updater in
# different threads. This can be treated as a global lock for
# everything.
self.lock = threading.Lock()
super().__init__(None, None)
def non_terminated_nodes(self, tag_filters):
with self.lock:
if self.throw:
raise Exception("oops")
return [
n.node_id for n in self.mock_nodes.values()
if n.matches(tag_filters)
and n.state not in ["stopped", "terminated"]
]
def non_terminated_node_ips(self, tag_filters):
with self.lock:
if self.throw:
raise Exception("oops")
return [
n.internal_ip for n in self.mock_nodes.values()
if n.matches(tag_filters)
and n.state not in ["stopped", "terminated"]
]
def is_running(self, node_id):
with self.lock:
return self.mock_nodes[node_id].state == "running"
def is_terminated(self, node_id):
with self.lock:
return self.mock_nodes[node_id].state in ["stopped", "terminated"]
def node_tags(self, node_id):
# Don't assume that node providers can retrieve tags from
# terminated nodes.
if self.is_terminated(node_id):
raise Exception(f"The node with id {node_id} has been terminated!")
with self.lock:
return self.mock_nodes[node_id].tags
def internal_ip(self, node_id):
with self.lock:
return self.mock_nodes[node_id].internal_ip
def external_ip(self, node_id):
with self.lock:
return self.mock_nodes[node_id].external_ip
def create_node(self, node_config, tags, count, _skip_wait=False):
if self.error_creates:
raise Exception
if not _skip_wait:
self.ready_to_create.wait()
if self.fail_creates:
return
with self.lock:
if self.cache_stopped:
for node in self.mock_nodes.values():
if node.state == "stopped" and count > 0:
count -= 1
node.state = "pending"
node.tags.update(tags)
for _ in range(count):
self.mock_nodes[self.next_id] = MockNode(
self.next_id,
tags.copy(),
node_config,
tags.get(CLOUDTIK_TAG_USER_NODE_TYPE),
unique_ips=self.unique_ips)
self.next_id += 1
def set_node_tags(self, node_id, tags):
with self.lock:
self.mock_nodes[node_id].tags.update(tags)
def terminate_node(self, node_id):
with self.lock:
if self.cache_stopped:
self.mock_nodes[node_id].state = "stopped"
else:
self.mock_nodes[node_id].state = "terminated"
def finish_starting_nodes(self):
with self.lock:
for node in self.mock_nodes.values():
if node.state == "pending":
node.state = "running"
SMALL_CLUSTER = {
"cluster_name": "default",
"min_workers": 2,
"max_workers": 2,
"initial_workers": 0,
"autoscaling_mode": "default",
"target_utilization_fraction": 0.8,
"idle_timeout_minutes": 5,
"provider": {
"type": "mock",
"region": "us-east-1",
"availability_zone": "us-east-1a",
},
"docker": {
"enabled": True,
"image": "example",
"container_name": "mock",
},
"auth": {
"ssh_user": "ubuntu",
"ssh_private_key": os.devnull,
},
"head_node": {
"TestProp": 1,
},
"file_mounts": {},
"cluster_synced_files": [],
"initialization_commands": ["init_cmd"],
"setup_commands": ["setup_cmd"],
"head_setup_commands": ["head_setup_cmd"],
"worker_setup_commands": ["worker_setup_cmd"],
"head_start_commands": ["head_start_cmd"],
"worker_start_commands": ["worker_start_cmd"],
}
MOCK_DEFAULT_CONFIG = {
"cluster_name": "default",
"max_workers": 2,
"idle_timeout_minutes": 5,
"provider": {
"type": "mock",
"region": "us-east-1",
"availability_zone": "us-east-1a",
},
"docker": {
"enabled": True,
"image": "example",
"container_name": "mock",
},
"auth": {
"ssh_user": "ubuntu",
"ssh_private_key": os.devnull,
},
"available_node_types": {
"cloudtik.head.default": {
"resources": {},
"node_config": {
"head_default_prop": 4
}
},
"cloudtik.worker.default": {
"min_workers": 0,
"max_workers": 2,
"resources": {},
"node_config": {
"worker_default_prop": 7
}
}
},
"head_node_type": "cloudtik.head.default",
"head_node": {},
"file_mounts": {},
"cluster_synced_files": [],
"initialization_commands": [],
"setup_commands": [],
"head_setup_commands": [],
"worker_setup_commands": [],
"head_start_commands": [],
"worker_start_commands": [],
}
TYPES_A = {
"empty_node": {
"node_config": {
"FooProperty": 42,
},
"resources": {},
"max_workers": 0,
},
"m4.large": {
"node_config": {},
"resources": {
"CPU": 2
},
"max_workers": 10,
},
"m4.4xlarge": {
"node_config": {},
"resources": {
"CPU": 16
},
"max_workers": 8,
},
"m4.16xlarge": {
"node_config": {},
"resources": {
"CPU": 64
},
"max_workers": 4,
},
"p2.xlarge": {
"node_config": {},
"resources": {
"CPU": 16,
"GPU": 1
},
"max_workers": 10,
},
"p2.8xlarge": {
"node_config": {},
"resources": {
"CPU": 32,
"GPU": 8
},
"max_workers": 4,
},
}
MULTI_WORKER_CLUSTER = dict(
SMALL_CLUSTER, **{
"available_node_types": TYPES_A,
"head_node_type": "empty_node"
})
class ClusterMetricsTest(unittest.TestCase):
def testHeartbeat(self):
cluster_metrics = ClusterMetrics()
cluster_metrics.update("1.1.1.1", b'\xb6\x80\xbdw\xbd\x1c\xee\xf6@\x11', {"CPU": 2}, {"CPU": 1}, {})
cluster_metrics.mark_active("2.2.2.2")
assert "1.1.1.1" in cluster_metrics.last_heartbeat_time_by_ip
assert "2.2.2.2" in cluster_metrics.last_heartbeat_time_by_ip
assert "3.3.3.3" not in cluster_metrics.last_heartbeat_time_by_ip
class CloudTikTest(unittest.TestCase):
def setUp(self):
_NODE_PROVIDERS["mock"] = \
lambda config: self.create_provider
_DEFAULT_CONFIGS["mock"] = _DEFAULT_CONFIGS["aws"]
self.provider = None
self.tmpdir = tempfile.mkdtemp()
def waitFor(self, condition, num_retries=50, fail_msg=None):
for _ in range(num_retries):
if condition():
return
time.sleep(.1)
fail_msg = fail_msg or "Timed out waiting for {}".format(condition)
raise CloudTikTestTimeoutException(fail_msg)
def waitForNodes(self, expected, comparison=None, tag_filters=None):
if tag_filters is None:
tag_filters = {}
MAX_ITER = 50
for i in range(MAX_ITER):
n = len(self.provider.non_terminated_nodes(tag_filters))
if comparison is None:
comparison = self.assertEqual
try:
comparison(n, expected, msg="Unexpected node quantity.")
return
except Exception:
if i == MAX_ITER - 1:
raise
time.sleep(.1)
def create_provider(self, config, cluster_name):
assert self.provider
return self.provider
def write_config(self, config, call_prepare_config=True):
new_config = copy.deepcopy(config)
if call_prepare_config:
new_config = prepare_config(new_config)
path = os.path.join(self.tmpdir, "simple.yaml")
with open(path, "w") as f:
f.write(yaml.dump(new_config))
return path
def testValidateDefaultConfig(self):
config = {"provider": {
"type": "aws",
"region": "us-east-1",
"availability_zone": "us-east-1a",
}}
config = prepare_config(config)
try:
validate_config(config)
except ValidationError:
self.fail("Default config did not pass validation test!")
def testGetRunningHeadNode(self):
config = copy.deepcopy(SMALL_CLUSTER)
self.provider = MockProvider()
# Node 0 is failed.
self.provider.create_node({}, {
CLOUDTIK_TAG_CLUSTER_NAME: "default",
CLOUDTIK_TAG_NODE_KIND: "head",
CLOUDTIK_TAG_NODE_STATUS: "update-failed"
}, 1)
# `_allow_uninitialized_state` should return the head node
# in the `update-failed` state.
allow_failed = cluster_operator._get_running_head_node(
config,
_provider=self.provider,
_allow_uninitialized_state=True)
assert allow_failed == 0
# Node 1 is okay.
self.provider.create_node({}, {
CLOUDTIK_TAG_CLUSTER_NAME: "default",
CLOUDTIK_TAG_NODE_KIND: "head",
CLOUDTIK_TAG_NODE_STATUS: "up-to-date"
}, 1)
node = cluster_operator._get_running_head_node(
config,
_provider=self.provider)
assert node == 1
# `_allow_uninitialized_state` should return the up-to-date head node
# if it is present.
optionally_failed = cluster_operator._get_running_head_node(
config,
_provider=self.provider,
_allow_uninitialized_state=True)
assert optionally_failed == 1
def testDefaultMinMaxWorkers(self):
config = copy.deepcopy(MOCK_DEFAULT_CONFIG)
config = prepare_config(config)
node_types = config["available_node_types"]
head_node_config = node_types["cloudtik.head.default"]
assert head_node_config["min_workers"] == 0
assert head_node_config["max_workers"] == 0
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-v", __file__]))
| 32.138298 | 108 | 0.5667 | from enum import Enum
import os
import re
from subprocess import CalledProcessError
import tempfile
import threading
import time
import unittest
import yaml
import copy
from jsonschema.exceptions import ValidationError
from typing import Dict, Callable, List, Optional
from cloudtik.core._private.utils import prepare_config, validate_config
from cloudtik.core._private.cluster import cluster_operator
from cloudtik.core._private.cluster.cluster_metrics import ClusterMetrics
from cloudtik.core._private.providers import (
_NODE_PROVIDERS, _DEFAULT_CONFIGS)
from cloudtik.core.tags import CLOUDTIK_TAG_NODE_KIND, CLOUDTIK_TAG_NODE_STATUS, \
CLOUDTIK_TAG_USER_NODE_TYPE, CLOUDTIK_TAG_CLUSTER_NAME
from cloudtik.core.node_provider import NodeProvider
import grpc
import pytest
class DrainNodeOutcome(str, Enum):
Succeeded = "Succeeded"
NotAllDrained = "NotAllDrained"
Unimplemented = "Unimplemented"
GenericRpcError = "GenericRpcError"
GenericException = "GenericException"
class MockRpcException(grpc.RpcError):
def __init__(self, status_code: grpc.StatusCode):
self.status_code = status_code
def code(self):
return self.status_code
class CloudTikTestTimeoutException(Exception):
pass
class MockNode:
def __init__(self, node_id, tags, node_config, node_type,
unique_ips=False):
self.node_id = node_id
self.state = "pending"
self.tags = tags
self.external_ip = "1.2.3.4"
self.internal_ip = "172.0.0.{}".format(self.node_id)
if unique_ips:
self.external_ip = f"1.2.3.{self.node_id}"
self.node_config = node_config
self.node_type = node_type
def matches(self, tags):
for k, v in tags.items():
if k not in self.tags or self.tags[k] != v:
return False
return True
class MockProcessRunner:
def __init__(self, fail_cmds=None, cmd_to_callback=None, print_out=False):
self.calls = []
self.cmd_to_callback = cmd_to_callback or {
}
self.print_out = print_out
self.fail_cmds = fail_cmds or []
self.call_response = {}
self.ready_to_run = threading.Event()
self.ready_to_run.set()
self.lock = threading.RLock()
def check_call(self, cmd, *args, **kwargs):
with self.lock:
self.ready_to_run.wait()
self.calls.append(cmd)
if self.print_out:
print(f">>>Process runner: Executing \n {str(cmd)}")
for token in self.cmd_to_callback:
if token in str(cmd):
callback = self.cmd_to_callback[token]
callback()
for token in self.fail_cmds:
if token in str(cmd):
raise CalledProcessError(1, token,
"Failing command on purpose")
def check_output(self, cmd):
with self.lock:
self.check_call(cmd)
return_string = "command-output"
key_to_shrink = None
for pattern, response_list in self.call_response.items():
if pattern in str(cmd):
return_string = response_list[0]
key_to_shrink = pattern
break
if key_to_shrink:
self.call_response[key_to_shrink] = self.call_response[
key_to_shrink][1:]
if len(self.call_response[key_to_shrink]) == 0:
del self.call_response[key_to_shrink]
return return_string.encode()
def assert_has_call(self,
ip: str,
pattern: Optional[str] = None,
exact: Optional[List[str]] = None):
with self.lock:
assert bool(pattern) ^ bool(exact), \
"Must specify either a pattern or exact match."
debug_output = ""
if pattern is not None:
for cmd in self.command_history():
if ip in cmd:
debug_output += cmd
debug_output += "\n"
if re.search(pattern, cmd):
return True
else:
raise Exception(
f"Did not find [{pattern}] in [{debug_output}] for "
f"ip={ip}.\n\nFull output: {self.command_history()}")
elif exact is not None:
exact_cmd = " ".join(exact)
for cmd in self.command_history():
if ip in cmd:
debug_output += cmd
debug_output += "\n"
if cmd == exact_cmd:
return True
raise Exception(
f"Did not find [{exact_cmd}] in [{debug_output}] for "
f"ip={ip}.\n\nFull output: {self.command_history()}")
def assert_not_has_call(self, ip: str, pattern: str):
with self.lock:
out = ""
for cmd in self.command_history():
if ip in cmd:
out += cmd
out += "\n"
if re.search(pattern, out):
raise Exception("Found [{}] in [{}] for {}".format(
pattern, out, ip))
else:
return True
def clear_history(self):
with self.lock:
self.calls = []
def command_history(self):
with self.lock:
return [" ".join(cmd) for cmd in self.calls]
def respond_to_call(self, pattern, response_list):
with self.lock:
self.call_response[pattern] = response_list
class MockProvider(NodeProvider):
def __init__(self, cache_stopped=False, unique_ips=False):
self.mock_nodes = {}
self.next_id = 0
self.throw = False
self.error_creates = False
self.fail_creates = False
self.ready_to_create = threading.Event()
self.ready_to_create.set()
self.cache_stopped = cache_stopped
self.unique_ips = unique_ips
self.lock = threading.Lock()
super().__init__(None, None)
def non_terminated_nodes(self, tag_filters):
with self.lock:
if self.throw:
raise Exception("oops")
return [
n.node_id for n in self.mock_nodes.values()
if n.matches(tag_filters)
and n.state not in ["stopped", "terminated"]
]
def non_terminated_node_ips(self, tag_filters):
with self.lock:
if self.throw:
raise Exception("oops")
return [
n.internal_ip for n in self.mock_nodes.values()
if n.matches(tag_filters)
and n.state not in ["stopped", "terminated"]
]
def is_running(self, node_id):
with self.lock:
return self.mock_nodes[node_id].state == "running"
def is_terminated(self, node_id):
with self.lock:
return self.mock_nodes[node_id].state in ["stopped", "terminated"]
def node_tags(self, node_id):
# terminated nodes.
if self.is_terminated(node_id):
raise Exception(f"The node with id {node_id} has been terminated!")
with self.lock:
return self.mock_nodes[node_id].tags
def internal_ip(self, node_id):
with self.lock:
return self.mock_nodes[node_id].internal_ip
def external_ip(self, node_id):
with self.lock:
return self.mock_nodes[node_id].external_ip
def create_node(self, node_config, tags, count, _skip_wait=False):
if self.error_creates:
raise Exception
if not _skip_wait:
self.ready_to_create.wait()
if self.fail_creates:
return
with self.lock:
if self.cache_stopped:
for node in self.mock_nodes.values():
if node.state == "stopped" and count > 0:
count -= 1
node.state = "pending"
node.tags.update(tags)
for _ in range(count):
self.mock_nodes[self.next_id] = MockNode(
self.next_id,
tags.copy(),
node_config,
tags.get(CLOUDTIK_TAG_USER_NODE_TYPE),
unique_ips=self.unique_ips)
self.next_id += 1
def set_node_tags(self, node_id, tags):
with self.lock:
self.mock_nodes[node_id].tags.update(tags)
def terminate_node(self, node_id):
with self.lock:
if self.cache_stopped:
self.mock_nodes[node_id].state = "stopped"
else:
self.mock_nodes[node_id].state = "terminated"
def finish_starting_nodes(self):
with self.lock:
for node in self.mock_nodes.values():
if node.state == "pending":
node.state = "running"
SMALL_CLUSTER = {
"cluster_name": "default",
"min_workers": 2,
"max_workers": 2,
"initial_workers": 0,
"autoscaling_mode": "default",
"target_utilization_fraction": 0.8,
"idle_timeout_minutes": 5,
"provider": {
"type": "mock",
"region": "us-east-1",
"availability_zone": "us-east-1a",
},
"docker": {
"enabled": True,
"image": "example",
"container_name": "mock",
},
"auth": {
"ssh_user": "ubuntu",
"ssh_private_key": os.devnull,
},
"head_node": {
"TestProp": 1,
},
"file_mounts": {},
"cluster_synced_files": [],
"initialization_commands": ["init_cmd"],
"setup_commands": ["setup_cmd"],
"head_setup_commands": ["head_setup_cmd"],
"worker_setup_commands": ["worker_setup_cmd"],
"head_start_commands": ["head_start_cmd"],
"worker_start_commands": ["worker_start_cmd"],
}
MOCK_DEFAULT_CONFIG = {
"cluster_name": "default",
"max_workers": 2,
"idle_timeout_minutes": 5,
"provider": {
"type": "mock",
"region": "us-east-1",
"availability_zone": "us-east-1a",
},
"docker": {
"enabled": True,
"image": "example",
"container_name": "mock",
},
"auth": {
"ssh_user": "ubuntu",
"ssh_private_key": os.devnull,
},
"available_node_types": {
"cloudtik.head.default": {
"resources": {},
"node_config": {
"head_default_prop": 4
}
},
"cloudtik.worker.default": {
"min_workers": 0,
"max_workers": 2,
"resources": {},
"node_config": {
"worker_default_prop": 7
}
}
},
"head_node_type": "cloudtik.head.default",
"head_node": {},
"file_mounts": {},
"cluster_synced_files": [],
"initialization_commands": [],
"setup_commands": [],
"head_setup_commands": [],
"worker_setup_commands": [],
"head_start_commands": [],
"worker_start_commands": [],
}
TYPES_A = {
"empty_node": {
"node_config": {
"FooProperty": 42,
},
"resources": {},
"max_workers": 0,
},
"m4.large": {
"node_config": {},
"resources": {
"CPU": 2
},
"max_workers": 10,
},
"m4.4xlarge": {
"node_config": {},
"resources": {
"CPU": 16
},
"max_workers": 8,
},
"m4.16xlarge": {
"node_config": {},
"resources": {
"CPU": 64
},
"max_workers": 4,
},
"p2.xlarge": {
"node_config": {},
"resources": {
"CPU": 16,
"GPU": 1
},
"max_workers": 10,
},
"p2.8xlarge": {
"node_config": {},
"resources": {
"CPU": 32,
"GPU": 8
},
"max_workers": 4,
},
}
MULTI_WORKER_CLUSTER = dict(
SMALL_CLUSTER, **{
"available_node_types": TYPES_A,
"head_node_type": "empty_node"
})
class ClusterMetricsTest(unittest.TestCase):
def testHeartbeat(self):
cluster_metrics = ClusterMetrics()
cluster_metrics.update("1.1.1.1", b'\xb6\x80\xbdw\xbd\x1c\xee\xf6@\x11', {"CPU": 2}, {"CPU": 1}, {})
cluster_metrics.mark_active("2.2.2.2")
assert "1.1.1.1" in cluster_metrics.last_heartbeat_time_by_ip
assert "2.2.2.2" in cluster_metrics.last_heartbeat_time_by_ip
assert "3.3.3.3" not in cluster_metrics.last_heartbeat_time_by_ip
class CloudTikTest(unittest.TestCase):
def setUp(self):
_NODE_PROVIDERS["mock"] = \
lambda config: self.create_provider
_DEFAULT_CONFIGS["mock"] = _DEFAULT_CONFIGS["aws"]
self.provider = None
self.tmpdir = tempfile.mkdtemp()
def waitFor(self, condition, num_retries=50, fail_msg=None):
for _ in range(num_retries):
if condition():
return
time.sleep(.1)
fail_msg = fail_msg or "Timed out waiting for {}".format(condition)
raise CloudTikTestTimeoutException(fail_msg)
def waitForNodes(self, expected, comparison=None, tag_filters=None):
if tag_filters is None:
tag_filters = {}
MAX_ITER = 50
for i in range(MAX_ITER):
n = len(self.provider.non_terminated_nodes(tag_filters))
if comparison is None:
comparison = self.assertEqual
try:
comparison(n, expected, msg="Unexpected node quantity.")
return
except Exception:
if i == MAX_ITER - 1:
raise
time.sleep(.1)
def create_provider(self, config, cluster_name):
assert self.provider
return self.provider
def write_config(self, config, call_prepare_config=True):
new_config = copy.deepcopy(config)
if call_prepare_config:
new_config = prepare_config(new_config)
path = os.path.join(self.tmpdir, "simple.yaml")
with open(path, "w") as f:
f.write(yaml.dump(new_config))
return path
def testValidateDefaultConfig(self):
config = {"provider": {
"type": "aws",
"region": "us-east-1",
"availability_zone": "us-east-1a",
}}
config = prepare_config(config)
try:
validate_config(config)
except ValidationError:
self.fail("Default config did not pass validation test!")
def testGetRunningHeadNode(self):
config = copy.deepcopy(SMALL_CLUSTER)
self.provider = MockProvider()
# Node 0 is failed.
self.provider.create_node({}, {
CLOUDTIK_TAG_CLUSTER_NAME: "default",
CLOUDTIK_TAG_NODE_KIND: "head",
CLOUDTIK_TAG_NODE_STATUS: "update-failed"
}, 1)
# `_allow_uninitialized_state` should return the head node
# in the `update-failed` state.
allow_failed = cluster_operator._get_running_head_node(
config,
_provider=self.provider,
_allow_uninitialized_state=True)
assert allow_failed == 0
# Node 1 is okay.
self.provider.create_node({}, {
CLOUDTIK_TAG_CLUSTER_NAME: "default",
CLOUDTIK_TAG_NODE_KIND: "head",
CLOUDTIK_TAG_NODE_STATUS: "up-to-date"
}, 1)
node = cluster_operator._get_running_head_node(
config,
_provider=self.provider)
assert node == 1
# `_allow_uninitialized_state` should return the up-to-date head node
# if it is present.
optionally_failed = cluster_operator._get_running_head_node(
config,
_provider=self.provider,
_allow_uninitialized_state=True)
assert optionally_failed == 1
def testDefaultMinMaxWorkers(self):
config = copy.deepcopy(MOCK_DEFAULT_CONFIG)
config = prepare_config(config)
node_types = config["available_node_types"]
head_node_config = node_types["cloudtik.head.default"]
assert head_node_config["min_workers"] == 0
assert head_node_config["max_workers"] == 0
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-v", __file__]))
| true | true |
1c46e01057545892b524898477fb51b8ed2373e5 | 1,140 | py | Python | frida_mode/test/png/persistent/get_symbol_addr.py | hamzzi/AFLplusplus | 95f47ac3a4d23b28a573a0614893d7aac5f5d4b4 | [
"Apache-2.0"
] | 2,104 | 2020-03-19T16:17:10.000Z | 2022-03-31T16:22:30.000Z | frida_mode/test/png/persistent/get_symbol_addr.py | hamzzi/AFLplusplus | 95f47ac3a4d23b28a573a0614893d7aac5f5d4b4 | [
"Apache-2.0"
] | 788 | 2020-03-19T14:54:09.000Z | 2022-03-31T17:38:00.000Z | frida_mode/test/png/persistent/get_symbol_addr.py | hamzzi/AFLplusplus | 95f47ac3a4d23b28a573a0614893d7aac5f5d4b4 | [
"Apache-2.0"
] | 518 | 2020-03-21T01:24:55.000Z | 2022-03-30T21:05:53.000Z | #!/usr/bin/python3
import argparse
from elftools.elf.elffile import ELFFile
def process_file(file, symbol, base):
with open(file, 'rb') as f:
elf = ELFFile(f)
symtab = elf.get_section_by_name('.symtab')
mains = symtab.get_symbol_by_name(symbol)
if len(mains) != 1:
print ("Failed to find main")
return 1
main_addr = mains[0]['st_value']
main = base + main_addr
print ("0x%016x" % main)
return 0
def hex_value(x):
return int(x, 16)
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-f', '--file', dest='file', type=str,
help='elf file name', required=True)
parser.add_argument('-s', '--symbol', dest='symbol', type=str,
help='symbol name', required=True)
parser.add_argument('-b', '--base', dest='base', type=hex_value,
help='elf base address', required=True)
args = parser.parse_args()
return process_file (args.file, args.symbol, args.base)
if __name__ == "__main__":
ret = main()
exit(ret)
| 30.810811 | 74 | 0.598246 |
import argparse
from elftools.elf.elffile import ELFFile
def process_file(file, symbol, base):
with open(file, 'rb') as f:
elf = ELFFile(f)
symtab = elf.get_section_by_name('.symtab')
mains = symtab.get_symbol_by_name(symbol)
if len(mains) != 1:
print ("Failed to find main")
return 1
main_addr = mains[0]['st_value']
main = base + main_addr
print ("0x%016x" % main)
return 0
def hex_value(x):
return int(x, 16)
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-f', '--file', dest='file', type=str,
help='elf file name', required=True)
parser.add_argument('-s', '--symbol', dest='symbol', type=str,
help='symbol name', required=True)
parser.add_argument('-b', '--base', dest='base', type=hex_value,
help='elf base address', required=True)
args = parser.parse_args()
return process_file (args.file, args.symbol, args.base)
if __name__ == "__main__":
ret = main()
exit(ret)
| true | true |
1c46e1353606f6ac2e8eadd47d685475e3efc0f6 | 946 | py | Python | crypto.py | Esshahn/cryptoticker | 6fb32712e380cb2a0605bafcfa64fe7fdf0367b7 | [
"MIT"
] | null | null | null | crypto.py | Esshahn/cryptoticker | 6fb32712e380cb2a0605bafcfa64fe7fdf0367b7 | [
"MIT"
] | null | null | null | crypto.py | Esshahn/cryptoticker | 6fb32712e380cb2a0605bafcfa64fe7fdf0367b7 | [
"MIT"
] | null | null | null | # -------------------------------------------------
# Cryptoticker
# Python Script to get the current prices of crypto currencies
# and send an email with the current prices
# 2021 Ingo Hinterding
# https://github.com/Esshahn/cryptoticker
# -------------------------------------------------
from tracker import *
from downloader import *
# ------------------ downloader ------------------ #
config = load_json("user-data.json")
data = download_latest_crypto_data(config)
save_file("crypto-data.json", json.dumps(data))
# ------------------ tracker ------------------ #
crypto_all = load_json("crypto-data.json")
crypto = crypto_all["data"]
user_all = load_json("user-data.json")
symbols = user_all["symbols"]
portfolio = user_all["portfolio"]
email = load_json('email.json')
full_portfolio = create_portfolio(portfolio, crypto)
body = format_crypto_data(symbols, crypto)
body += format_portfolio(full_portfolio)
send_mail(body, email)
| 26.277778 | 62 | 0.620507 |
from tracker import *
from downloader import *
config = load_json("user-data.json")
data = download_latest_crypto_data(config)
save_file("crypto-data.json", json.dumps(data))
crypto_all = load_json("crypto-data.json")
crypto = crypto_all["data"]
user_all = load_json("user-data.json")
symbols = user_all["symbols"]
portfolio = user_all["portfolio"]
email = load_json('email.json')
full_portfolio = create_portfolio(portfolio, crypto)
body = format_crypto_data(symbols, crypto)
body += format_portfolio(full_portfolio)
send_mail(body, email)
| true | true |
1c46e16e22d0b4bc1b34d28281a937a613893ce7 | 27,393 | py | Python | python/mxnet/base.py | ChrisQiqiang/mxnet-combination | 015c02f8fa1b22133202e1c70488c439cd9e726d | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | python/mxnet/base.py | ChrisQiqiang/mxnet-combination | 015c02f8fa1b22133202e1c70488c439cd9e726d | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | python/mxnet/base.py | ChrisQiqiang/mxnet-combination | 015c02f8fa1b22133202e1c70488c439cd9e726d | [
"BSL-1.0",
"Apache-2.0"
] | 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.
# coding: utf-8
# pylint: disable=invalid-name, no-member, trailing-comma-tuple, bad-mcs-classmethod-argument, unnecessary-pass, too-many-lines, wrong-import-position
"""ctypes library of mxnet and helper functions."""
from __future__ import absolute_import
import re
import atexit
import ctypes
import os
import sys
import inspect
import platform
import numpy as _np
from . import libinfo
__all__ = ['MXNetError']
#----------------------------
# library loading
#----------------------------
# pylint: disable=pointless-statement
try:
basestring
long
except NameError:
basestring = str
long = int
# pylint: enable=pointless-statement
integer_types = (int, long, _np.int32, _np.int64)
numeric_types = (float, int, long, _np.generic)
string_types = basestring,
if sys.version_info[0] > 2:
# this function is needed for python3
# to convert ctypes.char_p .value back to python str
py_str = lambda x: x.decode('utf-8')
else:
py_str = lambda x: x
def data_dir_default():
"""
:return: default data directory depending on the platform and environment variables
"""
system = platform.system()
if system == 'Windows':
return os.path.join(os.environ.get('APPDATA'), 'mxnet')
else:
return os.path.join(os.path.expanduser("~"), '.mxnet')
def data_dir():
"""
:return: data directory in the filesystem for storage, for example when downloading models
"""
return os.getenv('MXNET_HOME', data_dir_default())
class _NullType(object):
"""Placeholder for arguments"""
def __repr__(self):
return '_Null'
_Null = _NullType()
class MXNetError(Exception):
"""Error that will be thrown by all mxnet functions."""
pass
class NotImplementedForSymbol(MXNetError):
"""Error: Not implemented for symbol"""
def __init__(self, function, alias, *args):
super(NotImplementedForSymbol, self).__init__()
self.function = function.__name__
self.alias = alias
self.args = [str(type(a)) for a in args]
def __str__(self):
msg = 'Function {}'.format(self.function)
if self.alias:
msg += ' (namely operator "{}")'.format(self.alias)
if self.args:
msg += ' with arguments ({})'.format(', '.join(self.args))
msg += ' is not implemented for Symbol and only available in NDArray.'
return msg
class NotSupportedForSparseNDArray(MXNetError):
"""Error: Not supported for SparseNDArray"""
def __init__(self, function, alias, *args):
super(NotSupportedForSparseNDArray, self).__init__()
self.function = function.__name__
self.alias = alias
self.args = [str(type(a)) for a in args]
def __str__(self):
msg = 'Function {}'.format(self.function)
if self.alias:
msg += ' (namely operator "{}")'.format(self.alias)
if self.args:
msg += ' with arguments ({})'.format(', '.join(self.args))
msg += ' is not supported for SparseNDArray and only available in NDArray.'
return msg
class MXCallbackList(ctypes.Structure):
"""Structure that holds Callback information. Passed to CustomOpProp."""
_fields_ = [
('num_callbacks', ctypes.c_int),
('callbacks', ctypes.POINTER(ctypes.CFUNCTYPE(ctypes.c_int))),
('contexts', ctypes.POINTER(ctypes.c_void_p))
]
# Please see: https://stackoverflow.com/questions/5189699/how-to-make-a-class-property
class _MXClassPropertyDescriptor(object):
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, clas=None):
if clas is None:
clas = type(obj)
return self.fget.__get__(obj, clas)()
def __set__(self, obj, value):
if not self.fset:
raise MXNetError("cannot use the setter: %s to set attribute" % obj.__name__)
if inspect.isclass(obj):
type_ = obj
obj = None
else:
type_ = type(obj)
return self.fset.__get__(obj, type_)(value)
def setter(self, func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
self.fset = func
return self
class _MXClassPropertyMetaClass(type):
def __setattr__(cls, key, value):
obj = cls.__dict__.get(key)
if obj and isinstance(obj, _MXClassPropertyDescriptor):
return obj.__set__(cls, value)
return super(_MXClassPropertyMetaClass, cls).__setattr__(key, value)
# with_metaclass function obtained from: https://github.com/benjaminp/six/blob/master/six.py
# pylint: disable=unused-argument
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
@classmethod
def __prepare__(cls, name, this_bases):
return meta.__prepare__(name, bases)
return type.__new__(metaclass, 'temporary_class', (), {})
# pylint: enable=unused-argument
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return _MXClassPropertyDescriptor(func)
def _load_lib():
"""Load library by searching possible path."""
lib_path = libinfo.find_lib_path()
lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL)
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib
# version number
__version__ = libinfo.__version__
# library instance of mxnet
_LIB = _load_lib()
# type definitions
mx_int = ctypes.c_int
mx_uint = ctypes.c_uint
mx_int64 = ctypes.c_int64
mx_float = ctypes.c_float
mx_float_p = ctypes.POINTER(mx_float)
mx_real_t = _np.float32
NDArrayHandle = ctypes.c_void_p
FunctionHandle = ctypes.c_void_p
OpHandle = ctypes.c_void_p
CachedOpHandle = ctypes.c_void_p
SymbolHandle = ctypes.c_void_p
ExecutorHandle = ctypes.c_void_p
DataIterCreatorHandle = ctypes.c_void_p
DataIterHandle = ctypes.c_void_p
KVStoreHandle = ctypes.c_void_p
RecordIOHandle = ctypes.c_void_p
RtcHandle = ctypes.c_void_p
CudaModuleHandle = ctypes.c_void_p
CudaKernelHandle = ctypes.c_void_p
ProfileHandle = ctypes.c_void_p
DLPackHandle = ctypes.c_void_p
#----------------------------
# helper function definition
#----------------------------
def check_call(ret):
"""Check the return value of C API call.
This function will raise an exception when an error occurs.
Wrap every API call with this function.
Parameters
----------
ret : int
return value from API calls.
"""
if ret != 0:
raise MXNetError(py_str(_LIB.MXGetLastError()))
if sys.version_info[0] < 3:
def c_str(string):
"""Create ctypes char * from a Python string.
Parameters
----------
string : string type
Python string.
Returns
-------
str : c_char_p
A char pointer that can be passed to C API.
Examples
--------
>>> x = mx.base.c_str("Hello, World")
>>> print x.value
Hello, World
"""
return ctypes.c_char_p(string)
def c_str_array(strings):
"""Create ctypes const char ** from a list of Python strings.
Parameters
----------
strings : list of string
Python strings.
Returns
-------
(ctypes.c_char_p * len(strings))
A const char ** pointer that can be passed to C API.
"""
arr = (ctypes.c_char_p * len(strings))()
arr[:] = strings
return arr
else:
def c_str(string):
"""Create ctypes char * from a Python string.
Parameters
----------
string : string type
Python string.
Returns
-------
str : c_char_p
A char pointer that can be passed to C API.
Examples
--------
>>> x = mx.base.c_str("Hello, World")
>>> print(x.value)
b"Hello, World"
"""
return ctypes.c_char_p(string.encode('utf-8'))
def c_str_array(strings):
"""Create ctypes const char ** from a list of Python strings.
Parameters
----------
strings : list of string
Python strings.
Returns
-------
(ctypes.c_char_p * len(strings))
A const char ** pointer that can be passed to C API.
"""
arr = (ctypes.c_char_p * len(strings))()
arr[:] = [s.encode('utf-8') for s in strings]
return arr
def c_array(ctype, values):
"""Create ctypes array from a Python array.
Parameters
----------
ctype : ctypes data type
Data type of the array we want to convert to, such as mx_float.
values : tuple or list
Data content.
Returns
-------
out : ctypes array
Created ctypes array.
Examples
--------
>>> x = mx.base.c_array(mx.base.mx_float, [1, 2, 3])
>>> print len(x)
3
>>> x[1]
2.0
"""
out = (ctype * len(values))()
out[:] = values
return out
def c_array_buf(ctype, buf):
"""Create ctypes array from a Python buffer.
For primitive types, using the buffer created with array.array is faster
than a c_array call.
Parameters
----------
ctype : ctypes data type
Data type of the array we want to convert to, such as mx_float.
buf : buffer type
Data content.
Returns
-------
out : ctypes array
Created ctypes array.
Examples
--------
>>> x = mx.base.c_array_buf(mx.base.mx_float, array.array('i', [1, 2, 3]))
>>> print len(x)
3
>>> x[1]
2.0
"""
return (ctype * len(buf)).from_buffer(buf)
def c_handle_array(objs):
"""Create ctypes const void ** from a list of MXNet objects with handles.
Parameters
----------
objs : list of NDArray/Symbol.
MXNet objects.
Returns
-------
(ctypes.c_void_p * len(objs))
A void ** pointer that can be passed to C API.
"""
arr = (ctypes.c_void_p * len(objs))()
arr[:] = [o.handle for o in objs]
return arr
def ctypes2buffer(cptr, length):
"""Convert ctypes pointer to buffer type.
Parameters
----------
cptr : ctypes.POINTER(ctypes.c_char)
Pointer to the raw memory region.
length : int
The length of the buffer.
Returns
-------
buffer : bytearray
The raw byte memory buffer.
"""
if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
raise TypeError('expected char pointer')
res = bytearray(length)
rptr = (ctypes.c_char * length).from_buffer(res)
if not ctypes.memmove(rptr, cptr, length):
raise RuntimeError('memmove failed')
return res
def ctypes2numpy_shared(cptr, shape):
"""Convert a ctypes pointer to a numpy array.
The resulting NumPy array shares the memory with the pointer.
Parameters
----------
cptr : ctypes.POINTER(mx_float)
pointer to the memory region
shape : tuple
Shape of target `NDArray`.
Returns
-------
out : numpy_array
A numpy array : numpy array.
"""
if not isinstance(cptr, ctypes.POINTER(mx_float)):
raise RuntimeError('expected float pointer')
size = 1
for s in shape:
size *= s
dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents))
return _np.frombuffer(dbuffer, dtype=_np.float32).reshape(shape)
def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True):
"""Build argument docs in python style.
arg_names : list of str
Argument names.
arg_types : list of str
Argument type information.
arg_descs : list of str
Argument description information.
remove_dup : boolean, optional
Whether remove duplication or not.
Returns
-------
docstr : str
Python docstring of parameter sections.
"""
param_keys = set()
param_str = []
for key, type_info, desc in zip(arg_names, arg_types, arg_descs):
if key in param_keys and remove_dup:
continue
if key == 'num_args':
continue
param_keys.add(key)
ret = '%s : %s' % (key, type_info)
if len(desc) != 0:
ret += '\n ' + desc
param_str.append(ret)
doc_str = ('Parameters\n' +
'----------\n' +
'%s\n')
doc_str = doc_str % ('\n'.join(param_str))
return doc_str
def _notify_shutdown():
"""Notify MXNet about a shutdown."""
check_call(_LIB.MXNotifyShutdown())
atexit.register(_notify_shutdown)
def add_fileline_to_docstring(module, incursive=True):
"""Append the definition position to each function contained in module.
Examples
--------
# Put the following codes at the end of a file
add_fileline_to_docstring(__name__)
"""
def _add_fileline(obj):
"""Add fileinto to a object.
"""
if obj.__doc__ is None or 'From:' in obj.__doc__:
return
fname = inspect.getsourcefile(obj)
if fname is None:
return
try:
line = inspect.getsourcelines(obj)[-1]
except IOError:
return
obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line)
if isinstance(module, str):
module = sys.modules[module]
for _, obj in inspect.getmembers(module):
if inspect.isbuiltin(obj):
continue
if inspect.isfunction(obj):
_add_fileline(obj)
if inspect.ismethod(obj):
_add_fileline(obj.__func__)
if inspect.isclass(obj) and incursive:
add_fileline_to_docstring(obj, False)
def _as_list(obj):
"""A utility function that converts the argument to a list if it is not already.
Parameters
----------
obj : object
Returns
-------
If `obj` is a list or tuple, return it. Otherwise, return `[obj]` as a
single-element list.
"""
if isinstance(obj, (list, tuple)):
return obj
else:
return [obj]
_OP_NAME_PREFIX_LIST = ['_contrib_', '_linalg_', '_sparse_', '_image_', '_random_']
def _get_op_name_prefix(op_name):
"""
Check whether the given op_name starts with any words in `_OP_NAME_PREFIX_LIST`.
If found, return the prefix; else, return an empty string.
"""
for prefix in _OP_NAME_PREFIX_LIST:
if op_name.startswith(prefix):
return prefix
return ""
# pylint: enable=invalid-name
def _init_op_module(root_namespace, module_name, make_op_func):
"""
Registers op functions created by `make_op_func` under
`root_namespace.module_name.[submodule_name]`,
where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`.
Parameters
----------
root_namespace : str
Top level module name, `mxnet` in the current cases.
module_name : str
Second level module name, `ndarray` and `symbol` in the current cases.
make_op_func : function
Function for creating op functions for `ndarray` and `symbol` modules.
"""
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListAllOpNames(ctypes.byref(size),
ctypes.byref(plist)))
op_names = []
for i in range(size.value):
op_name = py_str(plist[i])
if not _is_np_op(op_name):
op_names.append(op_name)
module_op = sys.modules["%s.%s.op" % (root_namespace, module_name)]
module_internal = sys.modules["%s.%s._internal" % (root_namespace, module_name)]
# contrib module in the old format (deprecated)
# kept here for backward compatibility
# use mx.nd.contrib or mx.sym.contrib from now on
contrib_module_name_old = "%s.contrib.%s" % (root_namespace, module_name)
contrib_module_old = sys.modules[contrib_module_name_old]
submodule_dict = {}
for op_name_prefix in _OP_NAME_PREFIX_LIST:
submodule_dict[op_name_prefix] =\
sys.modules["%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])]
for name in op_names:
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
op_name_prefix = _get_op_name_prefix(name)
module_name_local = module_name
if len(op_name_prefix) > 0:
if op_name_prefix != '_random_' or name.endswith('_like'):
func_name = name[len(op_name_prefix):]
cur_module = submodule_dict[op_name_prefix]
module_name_local = "%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])
else:
func_name = name
cur_module = module_internal
elif name.startswith('_'):
func_name = name
cur_module = module_internal
else:
func_name = name
cur_module = module_op
function = make_op_func(hdl, name, func_name)
function.__module__ = module_name_local
setattr(cur_module, function.__name__, function)
cur_module.__all__.append(function.__name__)
if op_name_prefix == '_contrib_':
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
func_name = name[len(op_name_prefix):]
function = make_op_func(hdl, name, func_name)
function.__module__ = contrib_module_name_old
setattr(contrib_module_old, function.__name__, function)
contrib_module_old.__all__.append(function.__name__)
def _generate_op_module_signature(root_namespace, module_name, op_code_gen_func):
"""
Generate op functions created by `op_code_gen_func` and write to the source file
of `root_namespace.module_name.[submodule_name]`,
where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`.
Parameters
----------
root_namespace : str
Top level module name, `mxnet` in the current cases.
module_name : str
Second level module name, `ndarray` and `symbol` in the current cases.
op_code_gen_func : function
Function for creating op functions for `ndarray` and `symbol` modules.
"""
def get_module_file(module_name):
"""Return the generated module file based on module name."""
path = os.path.dirname(__file__)
module_path = module_name.split('.')
module_path[-1] = 'gen_' + module_path[-1]
file_name = os.path.join(path, '..', *module_path) + '.py'
module_file = open(file_name, 'w', encoding="utf-8")
dependencies = {'symbol': ['from ._internal import SymbolBase',
'from ..base import _Null'],
'ndarray': ['from ._internal import NDArrayBase',
'from ..base import _Null']}
module_file.write('# coding: utf-8')
module_file.write('# File content is auto-generated. Do not modify.' + os.linesep)
module_file.write('# pylint: skip-file' + os.linesep)
module_file.write(os.linesep.join(dependencies[module_name.split('.')[1]]))
return module_file
def write_all_str(module_file, module_all_list):
"""Write the proper __all__ based on available operators."""
module_file.write(os.linesep)
module_file.write(os.linesep)
all_str = '__all__ = [' + ', '.join(["'%s'"%s for s in module_all_list]) + ']'
module_file.write(all_str)
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListAllOpNames(ctypes.byref(size),
ctypes.byref(plist)))
op_names = []
for i in range(size.value):
op_name = py_str(plist[i])
if not _is_np_op(op_name):
op_names.append(op_name)
module_op_file = get_module_file("%s.%s.op" % (root_namespace, module_name))
module_op_all = []
module_internal_file = get_module_file("%s.%s._internal"%(root_namespace, module_name))
module_internal_all = []
submodule_dict = {}
for op_name_prefix in _OP_NAME_PREFIX_LIST:
submodule_dict[op_name_prefix] =\
(get_module_file("%s.%s.%s" % (root_namespace, module_name,
op_name_prefix[1:-1])), [])
for name in op_names:
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
op_name_prefix = _get_op_name_prefix(name)
if len(op_name_prefix) > 0:
func_name = name[len(op_name_prefix):]
cur_module_file, cur_module_all = submodule_dict[op_name_prefix]
elif name.startswith('_'):
func_name = name
cur_module_file = module_internal_file
cur_module_all = module_internal_all
else:
func_name = name
cur_module_file = module_op_file
cur_module_all = module_op_all
code, _ = op_code_gen_func(hdl, name, func_name, True)
cur_module_file.write(os.linesep)
cur_module_file.write(code)
cur_module_all.append(func_name)
for (submodule_f, submodule_all) in submodule_dict.values():
write_all_str(submodule_f, submodule_all)
submodule_f.close()
write_all_str(module_op_file, module_op_all)
module_op_file.close()
write_all_str(module_internal_file, module_internal_all)
module_internal_file.close()
ctypes.pythonapi.PyCapsule_New.restype = ctypes.py_object
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
_NP_OP_PREFIX = '_np_'
_NP_OP_SUBMODULE_LIST = ['_random_', '_linalg_']
_NP_EXT_OP_PREFIX = '_npx_'
_NP_EXT_OP_SUBMODULE_LIST = ['_image_']
_NP_INTERNAL_OP_PREFIX = '_npi_'
def _is_np_op(op_name):
return op_name.startswith(_NP_OP_PREFIX) or op_name.startswith(_NP_EXT_OP_PREFIX)\
or op_name.startswith(_NP_INTERNAL_OP_PREFIX)
def _get_op_submodule_name(op_name, op_name_prefix, submodule_name_list):
"""Get the submodule name of a specific op"""
assert op_name.startswith(op_name_prefix)
for submodule_name in submodule_name_list:
if op_name[len(op_name_prefix):].startswith(submodule_name):
return submodule_name
return ""
def _init_np_op_module(root_module_name, np_module_name, mx_module_name, make_op_func):
"""
Register numpy operators in namespaces `mxnet.numpy`, `mxnet.ndarray.numpy`
and `mxnet.symbol.numpy`. They are used in imperative mode, Gluon APIs w/o hybridization,
and Gluon APIs w/ hybridization, respectively. Essentially, operators with the same name
registered in three namespaces, respectively share the same functionality in C++ backend.
Different namespaces are needed for dispatching operator calls in Gluon's `HybridBlock` by `F`.
Parameters
----------
root_module_name : str
Top level module name, `mxnet` in the current cases.
np_module_name : str
Second level module name, `numpy` or `numpy_extension` in the current case.
make_op_func : function
Function for creating op functions.
"""
from . import _numpy_op_doc as _np_op_doc
if np_module_name == 'numpy':
op_name_prefix = _NP_OP_PREFIX
submodule_name_list = _NP_OP_SUBMODULE_LIST
elif np_module_name == 'numpy_extension':
op_name_prefix = _NP_EXT_OP_PREFIX
submodule_name_list = _NP_EXT_OP_SUBMODULE_LIST
elif np_module_name == 'numpy._internal':
op_name_prefix = _NP_INTERNAL_OP_PREFIX
submodule_name_list = []
else:
raise ValueError('unsupported np module name {}'.format(np_module_name))
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist)))
op_names = []
for i in range(size.value):
name = py_str(plist[i])
if name.startswith(op_name_prefix):
op_names.append(name)
if mx_module_name is None:
# register np/npx ops for imperative programming
op_module_name = "%s.%s._op" % (root_module_name, np_module_name) # e.g. mxnet.numpy._op
op_submodule_name = "%s.%s" % (root_module_name, np_module_name) # e.g. mxnet.numpy.random
elif mx_module_name in ('ndarray', 'symbol'):
# register numpy internal ops and np/npx ops for use in Gluon
# np internal ops are registered in mxnet.ndarray/symbol.numpy._internal
# np ops are registered in mxnet.ndarray/symbol.numpy._op
# npx ops are registered in mxnet.ndarray/symbol.numpy_extension._op
op_module_name = "%s.%s.%s" % (root_module_name, mx_module_name, np_module_name)
if op_name_prefix != _NP_INTERNAL_OP_PREFIX:
op_module_name += '._op'
# e.g. mxnet.symbol.numpy.random
op_submodule_name = "%s.%s.%s" % (root_module_name, mx_module_name, np_module_name)
else:
raise ValueError('unsupported mxnet module {}'.format(mx_module_name))
op_submodule_name += '.%s'
op_module = sys.modules[op_module_name]
submodule_dict = {}
for submodule_name in submodule_name_list:
submodule_dict[submodule_name] = sys.modules[op_submodule_name % submodule_name[1:-1]]
for name in op_names:
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
submodule_name = _get_op_submodule_name(name, op_name_prefix, submodule_name_list)
if len(submodule_name) > 0:
func_name = name[(len(op_name_prefix) + len(submodule_name)):]
cur_module = submodule_dict[submodule_name]
module_name_local = op_submodule_name % submodule_name[1:-1]
else:
func_name = name[len(op_name_prefix):]
cur_module = op_module
module_name_local =\
op_module_name[:-len('._op')] if op_module_name.endswith('._op') else op_module_name
function = make_op_func(hdl, name, func_name)
function.__module__ = module_name_local
setattr(cur_module, function.__name__, function)
cur_module.__all__.append(function.__name__)
if hasattr(_np_op_doc, name):
function.__doc__ = getattr(_np_op_doc, name).__doc__
else:
function.__doc__ = re.sub('NDArray', 'ndarray', function.__doc__)
| 32.113716 | 150 | 0.639032 |
from __future__ import absolute_import
import re
import atexit
import ctypes
import os
import sys
import inspect
import platform
import numpy as _np
from . import libinfo
__all__ = ['MXNetError']
try:
basestring
long
except NameError:
basestring = str
long = int
integer_types = (int, long, _np.int32, _np.int64)
numeric_types = (float, int, long, _np.generic)
string_types = basestring,
if sys.version_info[0] > 2:
py_str = lambda x: x.decode('utf-8')
else:
py_str = lambda x: x
def data_dir_default():
system = platform.system()
if system == 'Windows':
return os.path.join(os.environ.get('APPDATA'), 'mxnet')
else:
return os.path.join(os.path.expanduser("~"), '.mxnet')
def data_dir():
return os.getenv('MXNET_HOME', data_dir_default())
class _NullType(object):
def __repr__(self):
return '_Null'
_Null = _NullType()
class MXNetError(Exception):
pass
class NotImplementedForSymbol(MXNetError):
def __init__(self, function, alias, *args):
super(NotImplementedForSymbol, self).__init__()
self.function = function.__name__
self.alias = alias
self.args = [str(type(a)) for a in args]
def __str__(self):
msg = 'Function {}'.format(self.function)
if self.alias:
msg += ' (namely operator "{}")'.format(self.alias)
if self.args:
msg += ' with arguments ({})'.format(', '.join(self.args))
msg += ' is not implemented for Symbol and only available in NDArray.'
return msg
class NotSupportedForSparseNDArray(MXNetError):
def __init__(self, function, alias, *args):
super(NotSupportedForSparseNDArray, self).__init__()
self.function = function.__name__
self.alias = alias
self.args = [str(type(a)) for a in args]
def __str__(self):
msg = 'Function {}'.format(self.function)
if self.alias:
msg += ' (namely operator "{}")'.format(self.alias)
if self.args:
msg += ' with arguments ({})'.format(', '.join(self.args))
msg += ' is not supported for SparseNDArray and only available in NDArray.'
return msg
class MXCallbackList(ctypes.Structure):
_fields_ = [
('num_callbacks', ctypes.c_int),
('callbacks', ctypes.POINTER(ctypes.CFUNCTYPE(ctypes.c_int))),
('contexts', ctypes.POINTER(ctypes.c_void_p))
]
class _MXClassPropertyDescriptor(object):
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, clas=None):
if clas is None:
clas = type(obj)
return self.fget.__get__(obj, clas)()
def __set__(self, obj, value):
if not self.fset:
raise MXNetError("cannot use the setter: %s to set attribute" % obj.__name__)
if inspect.isclass(obj):
type_ = obj
obj = None
else:
type_ = type(obj)
return self.fset.__get__(obj, type_)(value)
def setter(self, func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
self.fset = func
return self
class _MXClassPropertyMetaClass(type):
def __setattr__(cls, key, value):
obj = cls.__dict__.get(key)
if obj and isinstance(obj, _MXClassPropertyDescriptor):
return obj.__set__(cls, value)
return super(_MXClassPropertyMetaClass, cls).__setattr__(key, value)
def with_metaclass(meta, *bases):
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
@classmethod
def __prepare__(cls, name, this_bases):
return meta.__prepare__(name, bases)
return type.__new__(metaclass, 'temporary_class', (), {})
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return _MXClassPropertyDescriptor(func)
def _load_lib():
lib_path = libinfo.find_lib_path()
lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL)
lib.MXGetLastError.restype = ctypes.c_char_p
return lib
__version__ = libinfo.__version__
_LIB = _load_lib()
mx_int = ctypes.c_int
mx_uint = ctypes.c_uint
mx_int64 = ctypes.c_int64
mx_float = ctypes.c_float
mx_float_p = ctypes.POINTER(mx_float)
mx_real_t = _np.float32
NDArrayHandle = ctypes.c_void_p
FunctionHandle = ctypes.c_void_p
OpHandle = ctypes.c_void_p
CachedOpHandle = ctypes.c_void_p
SymbolHandle = ctypes.c_void_p
ExecutorHandle = ctypes.c_void_p
DataIterCreatorHandle = ctypes.c_void_p
DataIterHandle = ctypes.c_void_p
KVStoreHandle = ctypes.c_void_p
RecordIOHandle = ctypes.c_void_p
RtcHandle = ctypes.c_void_p
CudaModuleHandle = ctypes.c_void_p
CudaKernelHandle = ctypes.c_void_p
ProfileHandle = ctypes.c_void_p
DLPackHandle = ctypes.c_void_p
def check_call(ret):
if ret != 0:
raise MXNetError(py_str(_LIB.MXGetLastError()))
if sys.version_info[0] < 3:
def c_str(string):
return ctypes.c_char_p(string)
def c_str_array(strings):
arr = (ctypes.c_char_p * len(strings))()
arr[:] = strings
return arr
else:
def c_str(string):
"""Create ctypes char * from a Python string.
Parameters
----------
string : string type
Python string.
Returns
-------
str : c_char_p
A char pointer that can be passed to C API.
Examples
--------
>>> x = mx.base.c_str("Hello, World")
>>> print(x.value)
b"Hello, World"
"""
return ctypes.c_char_p(string.encode('utf-8'))
def c_str_array(strings):
"""Create ctypes const char ** from a list of Python strings.
Parameters
----------
strings : list of string
Python strings.
Returns
-------
(ctypes.c_char_p * len(strings))
A const char ** pointer that can be passed to C API.
"""
arr = (ctypes.c_char_p * len(strings))()
arr[:] = [s.encode('utf-8') for s in strings]
return arr
def c_array(ctype, values):
out = (ctype * len(values))()
out[:] = values
return out
def c_array_buf(ctype, buf):
return (ctype * len(buf)).from_buffer(buf)
def c_handle_array(objs):
arr = (ctypes.c_void_p * len(objs))()
arr[:] = [o.handle for o in objs]
return arr
def ctypes2buffer(cptr, length):
if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
raise TypeError('expected char pointer')
res = bytearray(length)
rptr = (ctypes.c_char * length).from_buffer(res)
if not ctypes.memmove(rptr, cptr, length):
raise RuntimeError('memmove failed')
return res
def ctypes2numpy_shared(cptr, shape):
if not isinstance(cptr, ctypes.POINTER(mx_float)):
raise RuntimeError('expected float pointer')
size = 1
for s in shape:
size *= s
dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents))
return _np.frombuffer(dbuffer, dtype=_np.float32).reshape(shape)
def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True):
param_keys = set()
param_str = []
for key, type_info, desc in zip(arg_names, arg_types, arg_descs):
if key in param_keys and remove_dup:
continue
if key == 'num_args':
continue
param_keys.add(key)
ret = '%s : %s' % (key, type_info)
if len(desc) != 0:
ret += '\n ' + desc
param_str.append(ret)
doc_str = ('Parameters\n' +
'----------\n' +
'%s\n')
doc_str = doc_str % ('\n'.join(param_str))
return doc_str
def _notify_shutdown():
check_call(_LIB.MXNotifyShutdown())
atexit.register(_notify_shutdown)
def add_fileline_to_docstring(module, incursive=True):
def _add_fileline(obj):
if obj.__doc__ is None or 'From:' in obj.__doc__:
return
fname = inspect.getsourcefile(obj)
if fname is None:
return
try:
line = inspect.getsourcelines(obj)[-1]
except IOError:
return
obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line)
if isinstance(module, str):
module = sys.modules[module]
for _, obj in inspect.getmembers(module):
if inspect.isbuiltin(obj):
continue
if inspect.isfunction(obj):
_add_fileline(obj)
if inspect.ismethod(obj):
_add_fileline(obj.__func__)
if inspect.isclass(obj) and incursive:
add_fileline_to_docstring(obj, False)
def _as_list(obj):
if isinstance(obj, (list, tuple)):
return obj
else:
return [obj]
_OP_NAME_PREFIX_LIST = ['_contrib_', '_linalg_', '_sparse_', '_image_', '_random_']
def _get_op_name_prefix(op_name):
for prefix in _OP_NAME_PREFIX_LIST:
if op_name.startswith(prefix):
return prefix
return ""
def _init_op_module(root_namespace, module_name, make_op_func):
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListAllOpNames(ctypes.byref(size),
ctypes.byref(plist)))
op_names = []
for i in range(size.value):
op_name = py_str(plist[i])
if not _is_np_op(op_name):
op_names.append(op_name)
module_op = sys.modules["%s.%s.op" % (root_namespace, module_name)]
module_internal = sys.modules["%s.%s._internal" % (root_namespace, module_name)]
contrib_module_name_old = "%s.contrib.%s" % (root_namespace, module_name)
contrib_module_old = sys.modules[contrib_module_name_old]
submodule_dict = {}
for op_name_prefix in _OP_NAME_PREFIX_LIST:
submodule_dict[op_name_prefix] =\
sys.modules["%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])]
for name in op_names:
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
op_name_prefix = _get_op_name_prefix(name)
module_name_local = module_name
if len(op_name_prefix) > 0:
if op_name_prefix != '_random_' or name.endswith('_like'):
func_name = name[len(op_name_prefix):]
cur_module = submodule_dict[op_name_prefix]
module_name_local = "%s.%s.%s" % (root_namespace, module_name, op_name_prefix[1:-1])
else:
func_name = name
cur_module = module_internal
elif name.startswith('_'):
func_name = name
cur_module = module_internal
else:
func_name = name
cur_module = module_op
function = make_op_func(hdl, name, func_name)
function.__module__ = module_name_local
setattr(cur_module, function.__name__, function)
cur_module.__all__.append(function.__name__)
if op_name_prefix == '_contrib_':
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
func_name = name[len(op_name_prefix):]
function = make_op_func(hdl, name, func_name)
function.__module__ = contrib_module_name_old
setattr(contrib_module_old, function.__name__, function)
contrib_module_old.__all__.append(function.__name__)
def _generate_op_module_signature(root_namespace, module_name, op_code_gen_func):
def get_module_file(module_name):
path = os.path.dirname(__file__)
module_path = module_name.split('.')
module_path[-1] = 'gen_' + module_path[-1]
file_name = os.path.join(path, '..', *module_path) + '.py'
module_file = open(file_name, 'w', encoding="utf-8")
dependencies = {'symbol': ['from ._internal import SymbolBase',
'from ..base import _Null'],
'ndarray': ['from ._internal import NDArrayBase',
'from ..base import _Null']}
module_file.write('# coding: utf-8')
module_file.write('# File content is auto-generated. Do not modify.' + os.linesep)
module_file.write('# pylint: skip-file' + os.linesep)
module_file.write(os.linesep.join(dependencies[module_name.split('.')[1]]))
return module_file
def write_all_str(module_file, module_all_list):
module_file.write(os.linesep)
module_file.write(os.linesep)
all_str = '__all__ = [' + ', '.join(["'%s'"%s for s in module_all_list]) + ']'
module_file.write(all_str)
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListAllOpNames(ctypes.byref(size),
ctypes.byref(plist)))
op_names = []
for i in range(size.value):
op_name = py_str(plist[i])
if not _is_np_op(op_name):
op_names.append(op_name)
module_op_file = get_module_file("%s.%s.op" % (root_namespace, module_name))
module_op_all = []
module_internal_file = get_module_file("%s.%s._internal"%(root_namespace, module_name))
module_internal_all = []
submodule_dict = {}
for op_name_prefix in _OP_NAME_PREFIX_LIST:
submodule_dict[op_name_prefix] =\
(get_module_file("%s.%s.%s" % (root_namespace, module_name,
op_name_prefix[1:-1])), [])
for name in op_names:
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
op_name_prefix = _get_op_name_prefix(name)
if len(op_name_prefix) > 0:
func_name = name[len(op_name_prefix):]
cur_module_file, cur_module_all = submodule_dict[op_name_prefix]
elif name.startswith('_'):
func_name = name
cur_module_file = module_internal_file
cur_module_all = module_internal_all
else:
func_name = name
cur_module_file = module_op_file
cur_module_all = module_op_all
code, _ = op_code_gen_func(hdl, name, func_name, True)
cur_module_file.write(os.linesep)
cur_module_file.write(code)
cur_module_all.append(func_name)
for (submodule_f, submodule_all) in submodule_dict.values():
write_all_str(submodule_f, submodule_all)
submodule_f.close()
write_all_str(module_op_file, module_op_all)
module_op_file.close()
write_all_str(module_internal_file, module_internal_all)
module_internal_file.close()
ctypes.pythonapi.PyCapsule_New.restype = ctypes.py_object
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
_NP_OP_PREFIX = '_np_'
_NP_OP_SUBMODULE_LIST = ['_random_', '_linalg_']
_NP_EXT_OP_PREFIX = '_npx_'
_NP_EXT_OP_SUBMODULE_LIST = ['_image_']
_NP_INTERNAL_OP_PREFIX = '_npi_'
def _is_np_op(op_name):
return op_name.startswith(_NP_OP_PREFIX) or op_name.startswith(_NP_EXT_OP_PREFIX)\
or op_name.startswith(_NP_INTERNAL_OP_PREFIX)
def _get_op_submodule_name(op_name, op_name_prefix, submodule_name_list):
assert op_name.startswith(op_name_prefix)
for submodule_name in submodule_name_list:
if op_name[len(op_name_prefix):].startswith(submodule_name):
return submodule_name
return ""
def _init_np_op_module(root_module_name, np_module_name, mx_module_name, make_op_func):
from . import _numpy_op_doc as _np_op_doc
if np_module_name == 'numpy':
op_name_prefix = _NP_OP_PREFIX
submodule_name_list = _NP_OP_SUBMODULE_LIST
elif np_module_name == 'numpy_extension':
op_name_prefix = _NP_EXT_OP_PREFIX
submodule_name_list = _NP_EXT_OP_SUBMODULE_LIST
elif np_module_name == 'numpy._internal':
op_name_prefix = _NP_INTERNAL_OP_PREFIX
submodule_name_list = []
else:
raise ValueError('unsupported np module name {}'.format(np_module_name))
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist)))
op_names = []
for i in range(size.value):
name = py_str(plist[i])
if name.startswith(op_name_prefix):
op_names.append(name)
if mx_module_name is None:
op_module_name = "%s.%s._op" % (root_module_name, np_module_name)
op_submodule_name = "%s.%s" % (root_module_name, np_module_name)
elif mx_module_name in ('ndarray', 'symbol'):
op_module_name = "%s.%s.%s" % (root_module_name, mx_module_name, np_module_name)
if op_name_prefix != _NP_INTERNAL_OP_PREFIX:
op_module_name += '._op'
op_submodule_name = "%s.%s.%s" % (root_module_name, mx_module_name, np_module_name)
else:
raise ValueError('unsupported mxnet module {}'.format(mx_module_name))
op_submodule_name += '.%s'
op_module = sys.modules[op_module_name]
submodule_dict = {}
for submodule_name in submodule_name_list:
submodule_dict[submodule_name] = sys.modules[op_submodule_name % submodule_name[1:-1]]
for name in op_names:
hdl = OpHandle()
check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
submodule_name = _get_op_submodule_name(name, op_name_prefix, submodule_name_list)
if len(submodule_name) > 0:
func_name = name[(len(op_name_prefix) + len(submodule_name)):]
cur_module = submodule_dict[submodule_name]
module_name_local = op_submodule_name % submodule_name[1:-1]
else:
func_name = name[len(op_name_prefix):]
cur_module = op_module
module_name_local =\
op_module_name[:-len('._op')] if op_module_name.endswith('._op') else op_module_name
function = make_op_func(hdl, name, func_name)
function.__module__ = module_name_local
setattr(cur_module, function.__name__, function)
cur_module.__all__.append(function.__name__)
if hasattr(_np_op_doc, name):
function.__doc__ = getattr(_np_op_doc, name).__doc__
else:
function.__doc__ = re.sub('NDArray', 'ndarray', function.__doc__)
| true | true |
1c46e19fe76854e8b0b97098ce1dda2257aca5d4 | 4,533 | py | Python | includes/NopSCAD/scripts/c14n_stl.py | codysandahl/3dprinting | 98d588864e5ba5826c7ed16959aa7b1040a760b3 | [
"MIT"
] | null | null | null | includes/NopSCAD/scripts/c14n_stl.py | codysandahl/3dprinting | 98d588864e5ba5826c7ed16959aa7b1040a760b3 | [
"MIT"
] | null | null | null | includes/NopSCAD/scripts/c14n_stl.py | codysandahl/3dprinting | 98d588864e5ba5826c7ed16959aa7b1040a760b3 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#
# NopSCADlib Copyright Chris Palmer 2018
# nop.head@gmail.com
# hydraraptor.blogspot.com
#
# This file is part of NopSCADlib.
#
# NopSCADlib 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.
#
# NopSCADlib 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 NopSCADlib.
# If not, see <https://www.gnu.org/licenses/>.
#
#
#! OpenSCAD produces randomly ordered STL files. This script re-orders them consistently so that GIT can tell if they have changed or not.
#
# OpenSCAD produces randomly ordered STL files so source control like GIT can't tell if they have changed or not.
# This scrip orders each triangle to start with the lowest vertex first (comparing x, then y, then z)
# It then sorts the triangles to start with the one with the lowest vertices first (comparing first vertex, second, then third)
# This has no effect on the model but makes the STL consistent. I.e. it makes a canonical form.
#
from __future__ import print_function
import sys
def cmz(x):
''' Convert "-0" to "0". '''
return '0' if x == '-0' else x
class Vertex:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
self.key = (float(x), float(y), float(z))
class Normal:
def __init__(self, dx, dy, dz):
self.dx, self.dy, self.dz = dx, dy, dz
class Facet:
def __init__(self, normal, v1, v2, v3):
self.normal = normal
if v1.key < v2.key:
if v1.key < v3.key:
self.vertices = (v1, v2, v3) #v1 is the smallest
else:
self.vertices = (v3, v1, v2) #v3 is the smallest
else:
if v2.key < v3.key:
self.vertices = (v2, v3, v1) #v2 is the smallest
else:
self.vertices = (v3, v1, v2) #v3 is the smallest
def key(self):
return (self.vertices[0].x, self.vertices[0].y, self.vertices[0].z,
self.vertices[1].x, self.vertices[1].y, self.vertices[1].z,
self.vertices[2].x, self.vertices[2].y, self.vertices[2].z)
class STL:
def __init__(self, fname):
self.facets = []
with open(fname) as f:
words = [cmz(s.strip()) for s in f.read().split()]
if words[0] == 'solid' and words[1] == 'OpenSCAD_Model':
i = 2
while words[i] == 'facet':
norm = Normal(words[i + 2], words[i + 3], words[i + 4])
v1 = Vertex(words[i + 8], words[i + 9], words[i + 10])
v2 = Vertex(words[i + 12], words[i + 13], words[i + 14])
v3 = Vertex(words[i + 16], words[i + 17], words[i + 18])
i += 21
self.facets.append(Facet(norm, v1, v2, v3))
self.facets.sort(key = Facet.key)
else:
print("Not an OpenSCAD ascii STL file")
sys.exit(1)
def write(self, fname):
mins = [float('inf'), float('inf'), float('inf')]
maxs = [float('-inf'), float('-inf'), float('-inf')]
with open(fname,"wt") as f:
print('solid OpenSCAD_Model', file=f)
for facet in self.facets:
print(' facet normal %s %s %s' % (facet.normal.dx, facet.normal.dy, facet.normal.dz), file=f)
print(' outer loop', file=f)
for vertex in facet.vertices:
print(' vertex %s %s %s' % (vertex.x, vertex.y, vertex.z), file=f)
for i in range(3):
ordinate = vertex.key[i]
if ordinate > maxs[i]: maxs[i] = ordinate
if ordinate < mins[i]: mins[i] = ordinate
print(' endloop', file=f)
print(' endfacet', file=f)
print('endsolid OpenSCAD_Model', file=f)
return mins, maxs
def canonicalise(fname):
stl = STL(fname)
return stl.write(fname)
if __name__ == '__main__':
if len(sys.argv) == 2:
canonicalise(sys.argv[1])
else:
print("\nusage:\n\t c14n_stl file - Canonicalise an STL file created by OpenSCAD.")
sys.exit(1)
| 38.415254 | 138 | 0.578425 |
# This scrip orders each triangle to start with the lowest vertex first (comparing x, then y, then z)
# It then sorts the triangles to start with the one with the lowest vertices first (comparing first vertex, second, then third)
# This has no effect on the model but makes the STL consistent. I.e. it makes a canonical form.
#
from __future__ import print_function
import sys
def cmz(x):
return '0' if x == '-0' else x
class Vertex:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
self.key = (float(x), float(y), float(z))
class Normal:
def __init__(self, dx, dy, dz):
self.dx, self.dy, self.dz = dx, dy, dz
class Facet:
def __init__(self, normal, v1, v2, v3):
self.normal = normal
if v1.key < v2.key:
if v1.key < v3.key:
self.vertices = (v1, v2, v3) #v1 is the smallest
else:
self.vertices = (v3, v1, v2) #v3 is the smallest
else:
if v2.key < v3.key:
self.vertices = (v2, v3, v1) #v2 is the smallest
else:
self.vertices = (v3, v1, v2) #v3 is the smallest
def key(self):
return (self.vertices[0].x, self.vertices[0].y, self.vertices[0].z,
self.vertices[1].x, self.vertices[1].y, self.vertices[1].z,
self.vertices[2].x, self.vertices[2].y, self.vertices[2].z)
class STL:
def __init__(self, fname):
self.facets = []
with open(fname) as f:
words = [cmz(s.strip()) for s in f.read().split()]
if words[0] == 'solid' and words[1] == 'OpenSCAD_Model':
i = 2
while words[i] == 'facet':
norm = Normal(words[i + 2], words[i + 3], words[i + 4])
v1 = Vertex(words[i + 8], words[i + 9], words[i + 10])
v2 = Vertex(words[i + 12], words[i + 13], words[i + 14])
v3 = Vertex(words[i + 16], words[i + 17], words[i + 18])
i += 21
self.facets.append(Facet(norm, v1, v2, v3))
self.facets.sort(key = Facet.key)
else:
print("Not an OpenSCAD ascii STL file")
sys.exit(1)
def write(self, fname):
mins = [float('inf'), float('inf'), float('inf')]
maxs = [float('-inf'), float('-inf'), float('-inf')]
with open(fname,"wt") as f:
print('solid OpenSCAD_Model', file=f)
for facet in self.facets:
print(' facet normal %s %s %s' % (facet.normal.dx, facet.normal.dy, facet.normal.dz), file=f)
print(' outer loop', file=f)
for vertex in facet.vertices:
print(' vertex %s %s %s' % (vertex.x, vertex.y, vertex.z), file=f)
for i in range(3):
ordinate = vertex.key[i]
if ordinate > maxs[i]: maxs[i] = ordinate
if ordinate < mins[i]: mins[i] = ordinate
print(' endloop', file=f)
print(' endfacet', file=f)
print('endsolid OpenSCAD_Model', file=f)
return mins, maxs
def canonicalise(fname):
stl = STL(fname)
return stl.write(fname)
if __name__ == '__main__':
if len(sys.argv) == 2:
canonicalise(sys.argv[1])
else:
print("\nusage:\n\t c14n_stl file - Canonicalise an STL file created by OpenSCAD.")
sys.exit(1)
| true | true |
1c46e1ea720a2cd127402c538d9c90de250108a5 | 3,717 | py | Python | twisted/internet/test/test_time.py | hawkowl/twisted | c413aac3888dea2202c0dc26f978d7f88b4b837a | [
"Unlicense",
"MIT"
] | 9,953 | 2019-04-03T23:41:04.000Z | 2022-03-31T11:54:44.000Z | stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/test/test_time.py | W4LKURE/learn_python3_spider | 98dd354a41598b31302641f9a0ea49d1ecfa0fb1 | [
"MIT"
] | 44 | 2019-05-27T10:59:29.000Z | 2022-03-31T14:14:29.000Z | stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/test/test_time.py | W4LKURE/learn_python3_spider | 98dd354a41598b31302641f9a0ea49d1ecfa0fb1 | [
"MIT"
] | 2,803 | 2019-04-06T13:15:33.000Z | 2022-03-31T07:42:01.000Z | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for implementations of L{IReactorTime}.
"""
__metaclass__ = type
from twisted.python.log import msg
from twisted.python.runtime import platform
from twisted.trial.unittest import SkipTest
from twisted.internet.test.reactormixins import ReactorBuilder
from twisted.internet.interfaces import IReactorTime, IReactorThreads
class TimeTestsBuilder(ReactorBuilder):
"""
Builder for defining tests relating to L{IReactorTime}.
"""
requiredInterfaces = (IReactorTime,)
def test_delayedCallStopsReactor(self):
"""
The reactor can be stopped by a delayed call.
"""
reactor = self.buildReactor()
reactor.callLater(0, reactor.stop)
reactor.run()
def test_distantDelayedCall(self):
"""
Scheduling a delayed call at a point in the extreme future does not
prevent normal reactor operation.
"""
reactor = self.buildReactor()
if IReactorThreads.providedBy(reactor):
def eventSource(reactor, event):
msg(format="Thread-based event-source scheduling %(event)r",
event=event)
reactor.callFromThread(event)
else:
raise SkipTest("Do not know how to synthesize non-time event to "
"stop the test")
# Pick a pretty big delay.
delayedCall = reactor.callLater(2 ** 128 + 1, lambda: None)
def stop():
msg("Stopping the reactor")
reactor.stop()
# Use repeated invocation of the event source to set up the call to stop
# the reactor. This makes it more likely at least one normal iteration
# will take place with the delayed call in place before the slightly
# different reactor shutdown logic alters things.
eventSource(reactor, lambda: eventSource(reactor, stop))
# Run the reactor directly, without a timeout. A timeout would
# interfere with the purpose of this test, which is to have the timeout
# passed to the reactor's doIterate implementation (potentially) be
# very, very large. Hopefully the event source defined above will work
# and cause the reactor to stop.
reactor.run()
# The reactor almost surely stopped before the delayed call
# fired... right?
self.assertTrue(delayedCall.active())
self.assertIn(delayedCall, reactor.getDelayedCalls())
class GlibTimeTestsBuilder(ReactorBuilder):
"""
Builder for defining tests relating to L{IReactorTime} for reactors based
off glib.
"""
requiredInterfaces = (IReactorTime,)
if platform.isWindows():
_reactors = ["twisted.internet.gtk2reactor.PortableGtkReactor"]
else:
_reactors = ["twisted.internet.glib2reactor.Glib2Reactor",
"twisted.internet.gtk2reactor.Gtk2Reactor"]
def test_timeout_add(self):
"""
A
L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>}
call scheduled from a C{gobject.timeout_add}
call is run on time.
"""
import gobject
reactor = self.buildReactor()
result = []
def gschedule():
reactor.callLater(0, callback)
return 0
def callback():
result.append(True)
reactor.stop()
reactor.callWhenRunning(gobject.timeout_add, 10, gschedule)
self.runReactor(reactor, 5)
self.assertEqual(result, [True])
globals().update(TimeTestsBuilder.makeTestCaseClasses())
globals().update(GlibTimeTestsBuilder.makeTestCaseClasses())
| 32.893805 | 80 | 0.651601 |
__metaclass__ = type
from twisted.python.log import msg
from twisted.python.runtime import platform
from twisted.trial.unittest import SkipTest
from twisted.internet.test.reactormixins import ReactorBuilder
from twisted.internet.interfaces import IReactorTime, IReactorThreads
class TimeTestsBuilder(ReactorBuilder):
requiredInterfaces = (IReactorTime,)
def test_delayedCallStopsReactor(self):
reactor = self.buildReactor()
reactor.callLater(0, reactor.stop)
reactor.run()
def test_distantDelayedCall(self):
reactor = self.buildReactor()
if IReactorThreads.providedBy(reactor):
def eventSource(reactor, event):
msg(format="Thread-based event-source scheduling %(event)r",
event=event)
reactor.callFromThread(event)
else:
raise SkipTest("Do not know how to synthesize non-time event to "
"stop the test")
delayedCall = reactor.callLater(2 ** 128 + 1, lambda: None)
def stop():
msg("Stopping the reactor")
reactor.stop()
eventSource(reactor, lambda: eventSource(reactor, stop))
# very, very large. Hopefully the event source defined above will work
# and cause the reactor to stop.
reactor.run()
# The reactor almost surely stopped before the delayed call
# fired... right?
self.assertTrue(delayedCall.active())
self.assertIn(delayedCall, reactor.getDelayedCalls())
class GlibTimeTestsBuilder(ReactorBuilder):
requiredInterfaces = (IReactorTime,)
if platform.isWindows():
_reactors = ["twisted.internet.gtk2reactor.PortableGtkReactor"]
else:
_reactors = ["twisted.internet.glib2reactor.Glib2Reactor",
"twisted.internet.gtk2reactor.Gtk2Reactor"]
def test_timeout_add(self):
import gobject
reactor = self.buildReactor()
result = []
def gschedule():
reactor.callLater(0, callback)
return 0
def callback():
result.append(True)
reactor.stop()
reactor.callWhenRunning(gobject.timeout_add, 10, gschedule)
self.runReactor(reactor, 5)
self.assertEqual(result, [True])
globals().update(TimeTestsBuilder.makeTestCaseClasses())
globals().update(GlibTimeTestsBuilder.makeTestCaseClasses())
| true | true |
1c46e2c4714a5d7a0da9a84287a162ed818906e7 | 3,529 | py | Python | backend/schedule_worker/utils/generate_graph.py | evemorgen/GdzieJestMojTramwajProject | 65a090ae4222053a2a0a1b145df5196f3658065c | [
"MIT"
] | null | null | null | backend/schedule_worker/utils/generate_graph.py | evemorgen/GdzieJestMojTramwajProject | 65a090ae4222053a2a0a1b145df5196f3658065c | [
"MIT"
] | null | null | null | backend/schedule_worker/utils/generate_graph.py | evemorgen/GdzieJestMojTramwajProject | 65a090ae4222053a2a0a1b145df5196f3658065c | [
"MIT"
] | null | null | null | import os
import logging
import networkx as nx
import matplotlib.pyplot as plt
import json
from geopy.distance import vincenty
from collections import deque
from db import MpkDb as DbApi
from utils import Config
def czy_skrzyzowanie(przystanek, skrzyzowania, wariant, punkty):
for skrzyzowanie in skrzyzowania:
if przystanek in punkty[skrzyzowanie]['between'] and wariant[1][wariant[1].index(przystanek) + 1] in punkty[skrzyzowanie]['between']:
return skrzyzowanie
return None
def generate_graph():
config = Config()
dbapi = DbApi()
#test = Przystanki()
linie = [str(linia) for linia in config['lines']]
#logging.info(test.petle)
dokladne_linie = {klucz: [] for klucz in linie}
for linia in linie:
warianty = dbapi.get_variants_for_line(linia)
for wariant in warianty:
przystanki = dbapi.get_stops_for_variant(wariant)
tupla = tuple([wariant, przystanki])
dokladne_linie[linia].append(tupla)
with open(os.environ['TRAM_ROOT'] + '/data/przystanki_0_159.json', 'r') as plik:
punkty = json.load(plik)
ogarniete = {klucz: (float(punkty[klucz]['y']) * (10**6), float(punkty[klucz]['x']) * (10**6)) for klucz in punkty}
petle = {k: v for k, v in ogarniete.items() if punkty[k]['petla'] is True}
skrzyzowania = {k: v for k, v in ogarniete.items() if punkty[k]['skrzyzowanie'] is True}
przystanki = {k: v for k, v in ogarniete.items() if punkty[k]['przystanek'] is True}
G = nx.Graph()
G.add_nodes_from(ogarniete.keys())
for n, p in ogarniete.items():
G.node[n]['pos'] = p
pos = nx.get_node_attributes(G, 'pos')
offset = {}
for k, v in pos.items():
offset[k] = (v[0], v[1] - 500)
plt.figure(3, figsize=(80, 80))
nx.draw_networkx_nodes(G, pos, nodelist=przystanki, node_color='b', node_size=150)
nx.draw_networkx_nodes(G, pos, nodelist=skrzyzowania, node_color='g', node_size=100)
nx.draw_networkx_nodes(G, pos, nodelist=petle, node_color='r', node_size=200)
nx.draw_networkx_labels(G, offset, font_size=12, font_family=('ubuntu', 'arial'))
edges = {}
for linia in linie:
for wariant in dokladne_linie[linia]:
for przystanek in wariant[1][:-1]:
ze_skrzyzowaniem = czy_skrzyzowanie(przystanek, skrzyzowania, wariant, punkty)
if ze_skrzyzowaniem is not None:
kraw1 = tuple([przystanek, ze_skrzyzowaniem])
if kraw1 in edges:
edges[kraw1].append(linia)
else:
edges[kraw1] = [linia]
else:
kraw = tuple([przystanek, wariant[1][wariant[1].index(przystanek) + 1]])
if kraw in edges:
edges[kraw].append(linia)
else:
edges[kraw] = [linia]
for edge, label in edges.items():
first = (punkty[edge[0]]['x'], punkty[edge[0]]['y'])
second = (punkty[edge[1]]['x'], punkty[edge[1]]['y'])
logging.info('%s - %s: %s', edge[0], edge[1], vincenty(first, second).meters)
G.add_edge(edge[0], edge[1], linie=label, kolejka_L=deque(), kolejka_R=deque(), odleglosc=vincenty(first, second).meters)
nx.draw_networkx_edges(G, pos)
# nx.draw_networkx_edge_labels(G, pos)
plt.savefig(os.environ['TRAM_ROOT'] + '/data/graph.png', format='png', dpi=75)
nx.write_yaml(G, os.environ['TRAM_ROOT'] + '/data/graph.yaml')
| 39.651685 | 141 | 0.614338 | import os
import logging
import networkx as nx
import matplotlib.pyplot as plt
import json
from geopy.distance import vincenty
from collections import deque
from db import MpkDb as DbApi
from utils import Config
def czy_skrzyzowanie(przystanek, skrzyzowania, wariant, punkty):
for skrzyzowanie in skrzyzowania:
if przystanek in punkty[skrzyzowanie]['between'] and wariant[1][wariant[1].index(przystanek) + 1] in punkty[skrzyzowanie]['between']:
return skrzyzowanie
return None
def generate_graph():
config = Config()
dbapi = DbApi()
linie = [str(linia) for linia in config['lines']]
dokladne_linie = {klucz: [] for klucz in linie}
for linia in linie:
warianty = dbapi.get_variants_for_line(linia)
for wariant in warianty:
przystanki = dbapi.get_stops_for_variant(wariant)
tupla = tuple([wariant, przystanki])
dokladne_linie[linia].append(tupla)
with open(os.environ['TRAM_ROOT'] + '/data/przystanki_0_159.json', 'r') as plik:
punkty = json.load(plik)
ogarniete = {klucz: (float(punkty[klucz]['y']) * (10**6), float(punkty[klucz]['x']) * (10**6)) for klucz in punkty}
petle = {k: v for k, v in ogarniete.items() if punkty[k]['petla'] is True}
skrzyzowania = {k: v for k, v in ogarniete.items() if punkty[k]['skrzyzowanie'] is True}
przystanki = {k: v for k, v in ogarniete.items() if punkty[k]['przystanek'] is True}
G = nx.Graph()
G.add_nodes_from(ogarniete.keys())
for n, p in ogarniete.items():
G.node[n]['pos'] = p
pos = nx.get_node_attributes(G, 'pos')
offset = {}
for k, v in pos.items():
offset[k] = (v[0], v[1] - 500)
plt.figure(3, figsize=(80, 80))
nx.draw_networkx_nodes(G, pos, nodelist=przystanki, node_color='b', node_size=150)
nx.draw_networkx_nodes(G, pos, nodelist=skrzyzowania, node_color='g', node_size=100)
nx.draw_networkx_nodes(G, pos, nodelist=petle, node_color='r', node_size=200)
nx.draw_networkx_labels(G, offset, font_size=12, font_family=('ubuntu', 'arial'))
edges = {}
for linia in linie:
for wariant in dokladne_linie[linia]:
for przystanek in wariant[1][:-1]:
ze_skrzyzowaniem = czy_skrzyzowanie(przystanek, skrzyzowania, wariant, punkty)
if ze_skrzyzowaniem is not None:
kraw1 = tuple([przystanek, ze_skrzyzowaniem])
if kraw1 in edges:
edges[kraw1].append(linia)
else:
edges[kraw1] = [linia]
else:
kraw = tuple([przystanek, wariant[1][wariant[1].index(przystanek) + 1]])
if kraw in edges:
edges[kraw].append(linia)
else:
edges[kraw] = [linia]
for edge, label in edges.items():
first = (punkty[edge[0]]['x'], punkty[edge[0]]['y'])
second = (punkty[edge[1]]['x'], punkty[edge[1]]['y'])
logging.info('%s - %s: %s', edge[0], edge[1], vincenty(first, second).meters)
G.add_edge(edge[0], edge[1], linie=label, kolejka_L=deque(), kolejka_R=deque(), odleglosc=vincenty(first, second).meters)
nx.draw_networkx_edges(G, pos)
plt.savefig(os.environ['TRAM_ROOT'] + '/data/graph.png', format='png', dpi=75)
nx.write_yaml(G, os.environ['TRAM_ROOT'] + '/data/graph.yaml')
| true | true |
1c46e31c48f99fa5dabe9c956cd41ecd0c86bcaf | 5,840 | py | Python | src/retrieval_core/models/modules/da.py | RImbriaco/OML | 4998cdebc3ac553ccd53b4caacf24d8c3d8fc07b | [
"MIT"
] | 2 | 2021-09-08T12:33:05.000Z | 2021-09-14T09:40:43.000Z | src/retrieval_core/models/modules/da.py | RImbriaco/OML | 4998cdebc3ac553ccd53b4caacf24d8c3d8fc07b | [
"MIT"
] | null | null | null | src/retrieval_core/models/modules/da.py | RImbriaco/OML | 4998cdebc3ac553ccd53b4caacf24d8c3d8fc07b | [
"MIT"
] | 1 | 2021-09-08T12:35:10.000Z | 2021-09-08T12:35:10.000Z | import torch
from torch import nn
"""
Attention module as implemented in "Dual Attention Network for Scene
Segmentation" https://arxiv.org/abs/1809.02983
"""
class ActivatedBatchNorm(nn.Module):
def __init__(self, num_features, activation='relu', **kwargs):
"""
Pre-activates tensor with activation function before applying batch norm.
See following link for details. Leads to better performance.
https://github.com/ducha-aiki/caffenet-benchmark/blob/master/batchnorm.md
:param num_features: number of incoming feature maps
:param activation: activation type
:param kwargs: key word arguments pertaining to BatchNorm
"""
super().__init__()
activation_map = {
'relu': nn.ReLU,
'leaky_relu': nn.LeakyReLU,
'elu': nn.ELU,
}
if activation not in activation_map:
self.act = None
else:
self.act = activation_map[activation](inplace=True)
self.bn = nn.BatchNorm2d(num_features, **kwargs)
def forward(self, x):
if self.act is not None:
x = self.act(x)
x = self.bn(x)
return x
class Conv1x1(nn.Module):
def __init__(self, in_dim, out_dim):
super(Conv1x1, self).__init__()
self.conv1x1 = nn.Conv2d(
in_channels=in_dim, out_channels=out_dim, kernel_size=1)
def forward(self, x):
return self.conv1x1(x)
class Conv3x3(nn.Module):
def __init__(self, in_dim, out_dim, kernel_size=3, padding=1):
"""
Conv 3x3
:param in_dim: input channels
:param out_dim: output_channels
:param kernel_size:
:param padding:
"""
super().__init__()
self.conv = nn.Conv2d(
in_dim, out_dim, kernel_size=kernel_size, padding=padding)
def forward(self, x):
x = self.conv(x)
return x
class ConvPreAct(nn.Module):
def __init__(self, in_dim, out_dim, kernel_size=3, padding=1):
"""
Conv 3x3 -> activation -> BatchNorm
:param in_dim: input channels
:param out_dim: output_channels
:param kernel_size:
:param padding:
"""
super().__init__()
self.conv = Conv3x3(in_dim, out_dim, kernel_size, padding)
self.act = ActivatedBatchNorm(out_dim)
def forward(self, x):
x = self.conv(x)
x = self.act(x)
return x
# Both PAModule & CAModule are taken from Dual attention network as per,
# https://github.com/junfu1115/DANet/blob/master/encoding/nn/attention.py
# See https://arxiv.org/pdf/1809.02983.pdf
class PAModule(nn.Module):
def __init__(self, in_dim):
"""
input feature maps( B X C X H X W)
Position attention module
Here, the generated attention map is based on the shape of the spatial
dimensions B x (H x W) x (H x W)
"""
super(PAModule, self).__init__()
self.in_dim = in_dim
self.query_conv = Conv1x1(self.in_dim, self.in_dim // 8)
self.key_conv = Conv1x1(self.in_dim, self.in_dim // 8)
self.value_conv = Conv1x1(self.in_dim, self.in_dim)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
m_batchsize, channels, height, width = x.size()
proj_query = self.query_conv(x).view(
m_batchsize, -1, width*height).permute(0, 2, 1)
proj_key = self.key_conv(x).view(m_batchsize, -1, width*height)
energy = torch.bmm(proj_query, proj_key)
attention = self.softmax(energy)
proj_value = self.value_conv(x).view(m_batchsize, -1, width*height)
out = torch.bmm(proj_value, attention.permute(0, 2, 1))
out = out.view(m_batchsize, channels, height, width)
out = self.gamma*out + x
return out
class CAModule(nn.Module):
"""
input feature maps( B X C X H X W)
Channel attention module
Here, the generated attention map is based on the shape of the channel
dimensions B x (C x C)
"""
def __init__(self, in_dim):
super(CAModule, self).__init__()
self.chanel_in = in_dim
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
m_batchsize, C, height, width = x.size()
proj_query = x.view(m_batchsize, C, -1)
proj_key = x.view(m_batchsize, C, -1).permute(0, 2, 1)
energy = torch.bmm(proj_query, proj_key)
energy_new = torch.max(energy, -1, keepdim=True)[0].expand_as(energy) - energy
attention = self.softmax(energy_new)
proj_value = x.view(m_batchsize, C, -1)
out = torch.bmm(attention, proj_value)
out = out.view(m_batchsize, C, height, width)
out = self.gamma*out + x
return out
class DAModule(nn.Module):
def __init__(self, in_dim):
"""
Dual attention module from https://arxiv.org/pdf/1809.02983.pdf
Features from CAM and PAM are summed
:param in_dim:input dimensions
"""
super(DAModule, self).__init__()
inter_dim = in_dim // 4
self.conv_pam1 = ConvPreAct(in_dim, inter_dim)
self.pam = PAModule(inter_dim)
self.conv_pam2 = ConvPreAct(inter_dim, inter_dim)
self.conv_cam1 = ConvPreAct(in_dim, inter_dim)
self.cam = CAModule(inter_dim)
self.conv_cam2 = ConvPreAct(inter_dim, inter_dim)
self.conv = ConvPreAct(inter_dim, in_dim)
self.out_dim = in_dim
def forward(self, x):
p = self.conv_pam1(x)
p = self.pam(p)
p = self.conv_pam2(p)
c = self.conv_cam1(x)
c = self.cam(c)
c = self.conv_cam2(c)
feat = p + c
feat = self.conv(feat)
return feat
| 30.899471 | 86 | 0.610445 | import torch
from torch import nn
class ActivatedBatchNorm(nn.Module):
def __init__(self, num_features, activation='relu', **kwargs):
super().__init__()
activation_map = {
'relu': nn.ReLU,
'leaky_relu': nn.LeakyReLU,
'elu': nn.ELU,
}
if activation not in activation_map:
self.act = None
else:
self.act = activation_map[activation](inplace=True)
self.bn = nn.BatchNorm2d(num_features, **kwargs)
def forward(self, x):
if self.act is not None:
x = self.act(x)
x = self.bn(x)
return x
class Conv1x1(nn.Module):
def __init__(self, in_dim, out_dim):
super(Conv1x1, self).__init__()
self.conv1x1 = nn.Conv2d(
in_channels=in_dim, out_channels=out_dim, kernel_size=1)
def forward(self, x):
return self.conv1x1(x)
class Conv3x3(nn.Module):
def __init__(self, in_dim, out_dim, kernel_size=3, padding=1):
super().__init__()
self.conv = nn.Conv2d(
in_dim, out_dim, kernel_size=kernel_size, padding=padding)
def forward(self, x):
x = self.conv(x)
return x
class ConvPreAct(nn.Module):
def __init__(self, in_dim, out_dim, kernel_size=3, padding=1):
super().__init__()
self.conv = Conv3x3(in_dim, out_dim, kernel_size, padding)
self.act = ActivatedBatchNorm(out_dim)
def forward(self, x):
x = self.conv(x)
x = self.act(x)
return x
class PAModule(nn.Module):
def __init__(self, in_dim):
super(PAModule, self).__init__()
self.in_dim = in_dim
self.query_conv = Conv1x1(self.in_dim, self.in_dim // 8)
self.key_conv = Conv1x1(self.in_dim, self.in_dim // 8)
self.value_conv = Conv1x1(self.in_dim, self.in_dim)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
m_batchsize, channels, height, width = x.size()
proj_query = self.query_conv(x).view(
m_batchsize, -1, width*height).permute(0, 2, 1)
proj_key = self.key_conv(x).view(m_batchsize, -1, width*height)
energy = torch.bmm(proj_query, proj_key)
attention = self.softmax(energy)
proj_value = self.value_conv(x).view(m_batchsize, -1, width*height)
out = torch.bmm(proj_value, attention.permute(0, 2, 1))
out = out.view(m_batchsize, channels, height, width)
out = self.gamma*out + x
return out
class CAModule(nn.Module):
def __init__(self, in_dim):
super(CAModule, self).__init__()
self.chanel_in = in_dim
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
m_batchsize, C, height, width = x.size()
proj_query = x.view(m_batchsize, C, -1)
proj_key = x.view(m_batchsize, C, -1).permute(0, 2, 1)
energy = torch.bmm(proj_query, proj_key)
energy_new = torch.max(energy, -1, keepdim=True)[0].expand_as(energy) - energy
attention = self.softmax(energy_new)
proj_value = x.view(m_batchsize, C, -1)
out = torch.bmm(attention, proj_value)
out = out.view(m_batchsize, C, height, width)
out = self.gamma*out + x
return out
class DAModule(nn.Module):
def __init__(self, in_dim):
super(DAModule, self).__init__()
inter_dim = in_dim // 4
self.conv_pam1 = ConvPreAct(in_dim, inter_dim)
self.pam = PAModule(inter_dim)
self.conv_pam2 = ConvPreAct(inter_dim, inter_dim)
self.conv_cam1 = ConvPreAct(in_dim, inter_dim)
self.cam = CAModule(inter_dim)
self.conv_cam2 = ConvPreAct(inter_dim, inter_dim)
self.conv = ConvPreAct(inter_dim, in_dim)
self.out_dim = in_dim
def forward(self, x):
p = self.conv_pam1(x)
p = self.pam(p)
p = self.conv_pam2(p)
c = self.conv_cam1(x)
c = self.cam(c)
c = self.conv_cam2(c)
feat = p + c
feat = self.conv(feat)
return feat
| true | true |
1c46e32070cf0c01bff98632cd40042af2562b9c | 22,730 | py | Python | plugins/sqlfluff-templater-dbt/sqlfluff_templater_dbt/templater.py | fdw/sqlfluff | e49c974e3fc886a28b358b59442d9471e6f6e89d | [
"MIT"
] | null | null | null | plugins/sqlfluff-templater-dbt/sqlfluff_templater_dbt/templater.py | fdw/sqlfluff | e49c974e3fc886a28b358b59442d9471e6f6e89d | [
"MIT"
] | null | null | null | plugins/sqlfluff-templater-dbt/sqlfluff_templater_dbt/templater.py | fdw/sqlfluff | e49c974e3fc886a28b358b59442d9471e6f6e89d | [
"MIT"
] | null | null | null | """Defines the templaters."""
from collections import deque
from contextlib import contextmanager
import os
import os.path
import logging
from typing import List, Optional, Iterator, Tuple, Any, Dict, Deque
from dataclasses import dataclass
from functools import partial
from dbt.version import get_installed_version
from dbt.config.runtime import RuntimeConfig as DbtRuntimeConfig
from dbt.adapters.factory import register_adapter, get_adapter
from dbt.compilation import Compiler as DbtCompiler
from dbt.exceptions import (
CompilationException as DbtCompilationException,
FailedToConnectException as DbtFailedToConnectException,
)
from dbt import flags
from jinja2 import Environment
from jinja2_simple_tags import StandaloneTag
from sqlfluff.core.cached_property import cached_property
from sqlfluff.core.errors import SQLTemplaterError, SQLTemplaterSkipFile
from sqlfluff.core.templaters.base import (
RawFileSlice,
TemplatedFile,
TemplatedFileSlice,
)
from sqlfluff.core.templaters.slicers.heuristic import slice_template
from sqlfluff.core.templaters.jinja import JinjaTemplater
# Instantiate the templater logger
templater_logger = logging.getLogger("sqlfluff.templater")
DBT_VERSION = get_installed_version()
DBT_VERSION_STRING = DBT_VERSION.to_version_string()
DBT_VERSION_TUPLE = (int(DBT_VERSION.major), int(DBT_VERSION.minor))
if DBT_VERSION_TUPLE >= (1, 0):
from dbt.flags import PROFILES_DIR
else:
from dbt.config.profile import PROFILES_DIR
@dataclass
class DbtConfigArgs:
"""Arguments to load dbt runtime config."""
project_dir: Optional[str] = None
profiles_dir: Optional[str] = None
profile: Optional[str] = None
target: Optional[str] = None
single_threaded: bool = False
class DbtTemplater(JinjaTemplater):
"""A templater using dbt."""
name = "dbt"
sequential_fail_limit = 3
def __init__(self, **kwargs):
self.sqlfluff_config = None
self.formatter = None
self.project_dir = None
self.profiles_dir = None
self.working_dir = os.getcwd()
self._sequential_fails = 0
super().__init__(**kwargs)
def config_pairs(self): # pragma: no cover TODO?
"""Returns info about the given templater for output by the cli."""
return [("templater", self.name), ("dbt", self.dbt_version)]
@property
def dbt_version(self):
"""Gets the dbt version."""
return DBT_VERSION_STRING
@property
def dbt_version_tuple(self):
"""Gets the dbt version as a tuple on (major, minor)."""
return DBT_VERSION_TUPLE
@cached_property
def dbt_config(self):
"""Loads the dbt config."""
if self.dbt_version_tuple >= (1, 0):
flags.set_from_args(
"",
DbtConfigArgs(
project_dir=self.project_dir,
profiles_dir=self.profiles_dir,
profile=self._get_profile(),
target=self._get_target(),
),
)
self.dbt_config = DbtRuntimeConfig.from_args(
DbtConfigArgs(
project_dir=self.project_dir,
profiles_dir=self.profiles_dir,
profile=self._get_profile(),
target=self._get_target(),
)
)
register_adapter(self.dbt_config)
return self.dbt_config
@cached_property
def dbt_compiler(self):
"""Loads the dbt compiler."""
self.dbt_compiler = DbtCompiler(self.dbt_config)
return self.dbt_compiler
@cached_property
def dbt_manifest(self):
"""Loads the dbt manifest."""
# Identity function used for macro hooks
def identity(x):
return x
# Set dbt not to run tracking. We don't load
# a dull project and so some tracking routines
# may fail.
from dbt.tracking import do_not_track
do_not_track()
if self.dbt_version_tuple <= (0, 19):
if self.dbt_version_tuple == (0, 17): # pragma: no cover TODO?
# dbt version 0.17.*
from dbt.parser.manifest import (
load_internal_manifest as load_macro_manifest,
)
else:
# dbt version 0.18.* & # 0.19.*
from dbt.parser.manifest import load_macro_manifest
load_macro_manifest = partial(load_macro_manifest, macro_hook=identity)
from dbt.parser.manifest import load_manifest
dbt_macros_manifest = load_macro_manifest(self.dbt_config)
self.dbt_manifest = load_manifest(
self.dbt_config, dbt_macros_manifest, macro_hook=identity
)
else:
# dbt 0.20.* and onward
from dbt.parser.manifest import ManifestLoader
projects = self.dbt_config.load_dependencies()
loader = ManifestLoader(self.dbt_config, projects, macro_hook=identity)
self.dbt_manifest = loader.load()
return self.dbt_manifest
@cached_property
def dbt_selector_method(self):
"""Loads the dbt selector method."""
if self.formatter: # pragma: no cover TODO?
self.formatter.dispatch_compilation_header(
"dbt templater", "Compiling dbt project..."
)
if self.dbt_version_tuple == (0, 17): # pragma: no cover TODO?
from dbt.graph.selector import PathSelector
self.dbt_selector_method = PathSelector(self.dbt_manifest)
else:
from dbt.graph.selector_methods import (
MethodManager as DbtSelectorMethodManager,
MethodName as DbtMethodName,
)
selector_methods_manager = DbtSelectorMethodManager(
self.dbt_manifest, previous_state=None
)
self.dbt_selector_method = selector_methods_manager.get_method(
DbtMethodName.Path, method_arguments=[]
)
if self.formatter: # pragma: no cover TODO?
self.formatter.dispatch_compilation_header(
"dbt templater", "Project Compiled."
)
return self.dbt_selector_method
def _get_profiles_dir(self):
"""Get the dbt profiles directory from the configuration.
The default is `~/.dbt` in 0.17 but we use the
PROFILES_DIR variable from the dbt library to
support a change of default in the future, as well
as to support the same overwriting mechanism as
dbt (currently an environment variable).
"""
dbt_profiles_dir = os.path.abspath(
os.path.expanduser(
self.sqlfluff_config.get_section(
(self.templater_selector, self.name, "profiles_dir")
)
or PROFILES_DIR
)
)
if not os.path.exists(dbt_profiles_dir):
templater_logger.error(
f"dbt_profiles_dir: {dbt_profiles_dir} could not be accessed. Check it exists."
)
return dbt_profiles_dir
def _get_project_dir(self):
"""Get the dbt project directory from the configuration.
Defaults to the working directory.
"""
dbt_project_dir = os.path.abspath(
os.path.expanduser(
self.sqlfluff_config.get_section(
(self.templater_selector, self.name, "project_dir")
)
or os.getcwd()
)
)
if not os.path.exists(dbt_project_dir):
templater_logger.error(
f"dbt_project_dir: {dbt_project_dir} could not be accessed. Check it exists."
)
return dbt_project_dir
def _get_profile(self):
"""Get a dbt profile name from the configuration."""
return self.sqlfluff_config.get_section(
(self.templater_selector, self.name, "profile")
)
def _get_target(self):
"""Get a dbt target name from the configuration."""
return self.sqlfluff_config.get_section(
(self.templater_selector, self.name, "target")
)
def sequence_files(
self, fnames: List[str], config=None, formatter=None
) -> Iterator[str]:
"""Reorder fnames to process dependent files first.
This avoids errors when an ephemeral model is processed before use.
"""
if formatter: # pragma: no cover
formatter.dispatch_compilation_header("dbt templater", "Sorting Nodes...")
# Initialise config if not already done
self.sqlfluff_config = config
if not self.project_dir:
self.project_dir = self._get_project_dir()
if not self.profiles_dir:
self.profiles_dir = self._get_profiles_dir()
# Populate full paths for selected files
full_paths: Dict[str, str] = {}
selected_files = set()
for fname in fnames:
fpath = os.path.join(self.working_dir, fname)
full_paths[fpath] = fname
selected_files.add(fpath)
ephemeral_nodes: Dict[str, Tuple[str, Any]] = {}
# Extract the ephemeral models
for key, node in self.dbt_manifest.nodes.items():
if node.config.materialized == "ephemeral":
# The key is the full filepath.
# The value tuple, with the filepath and a list of dependent keys
ephemeral_nodes[key] = (
os.path.join(self.project_dir, node.original_file_path),
node.depends_on.nodes,
)
# Yield ephemeral nodes first. We use a Deque for efficient requeing.
# We iterate through the deque, yielding any nodes without dependents,
# or where those dependents have already yielded, first. The original
# mapping is still used to hold the metadata on each key.
already_yielded = set()
ephemeral_buffer: Deque[str] = deque(ephemeral_nodes.keys())
while ephemeral_buffer:
key = ephemeral_buffer.popleft()
fpath, dependents = ephemeral_nodes[key]
# If it's not in our selection, skip it
if fpath not in selected_files:
templater_logger.debug("- Purging unselected ephemeral: %r", fpath)
# If there are dependent nodes in the set, don't process it yet.
elif any(
dependent in ephemeral_buffer for dependent in dependents
): # pragma: no cover
templater_logger.debug(
"- Requeuing ephemeral with dependents: %r", fpath
)
# Requeue it for later
ephemeral_buffer.append(key)
# Otherwise yield it.
else:
templater_logger.debug("- Yielding Ephemeral: %r", fpath)
yield full_paths[fpath]
already_yielded.add(full_paths[fpath])
for fname in fnames:
if fname not in already_yielded:
yield fname
def process(self, *, fname, in_str=None, config=None, formatter=None):
"""Compile a dbt model and return the compiled SQL.
Args:
fname (:obj:`str`): Path to dbt model(s)
in_str (:obj:`str`, optional): This is ignored for dbt
config (:obj:`FluffConfig`, optional): A specific config to use for this
templating operation. Only necessary for some templaters.
formatter (:obj:`CallbackFormatter`): Optional object for output.
"""
# Stash the formatter if provided to use in cached methods.
self.formatter = formatter
self.sqlfluff_config = config
self.project_dir = self._get_project_dir()
self.profiles_dir = self._get_profiles_dir()
fname_absolute_path = os.path.abspath(fname)
try:
os.chdir(self.project_dir)
processed_result = self._unsafe_process(fname_absolute_path, in_str, config)
# Reset the fail counter
self._sequential_fails = 0
return processed_result
except DbtCompilationException as e:
# Increment the counter
self._sequential_fails += 1
if e.node:
return None, [
SQLTemplaterError(
f"dbt compilation error on file '{e.node.original_file_path}', {e.msg}",
# It's fatal if we're over the limit
fatal=self._sequential_fails > self.sequential_fail_limit,
)
]
else:
raise # pragma: no cover
except DbtFailedToConnectException as e:
return None, [
SQLTemplaterError(
"dbt tried to connect to the database and failed: "
"you could use 'execute' https://docs.getdbt.com/reference/dbt-jinja-functions/execute/ "
f"to skip the database calls. Error: {e.msg}",
fatal=True,
)
]
# If a SQLFluff error is raised, just pass it through
except SQLTemplaterError as e: # pragma: no cover
return None, [e]
finally:
os.chdir(self.working_dir)
def _find_node(self, fname, config=None):
if not config: # pragma: no cover
raise ValueError(
"For the dbt templater, the `process()` method requires a config object."
)
if not fname: # pragma: no cover
raise ValueError(
"For the dbt templater, the `process()` method requires a file name"
)
elif fname == "stdin": # pragma: no cover
raise ValueError(
"The dbt templater does not support stdin input, provide a path instead"
)
selected = self.dbt_selector_method.search(
included_nodes=self.dbt_manifest.nodes,
# Selector needs to be a relative path
selector=os.path.relpath(fname, start=os.getcwd()),
)
results = [self.dbt_manifest.expect(uid) for uid in selected]
if not results:
model_name = os.path.splitext(os.path.basename(fname))[0]
if DBT_VERSION_TUPLE >= (1, 0):
disabled_model = None
for key, disabled_model_nodes in self.dbt_manifest.disabled.items():
for disabled_model_node in disabled_model_nodes:
if os.path.abspath(
disabled_model_node.original_file_path
) == os.path.abspath(fname):
disabled_model = disabled_model_node
else:
disabled_model = self.dbt_manifest.find_disabled_by_name(
name=model_name
)
if disabled_model and os.path.abspath(
disabled_model.original_file_path
) == os.path.abspath(fname):
raise SQLTemplaterSkipFile(
f"Skipped file {fname} because the model was disabled"
)
raise RuntimeError(
"File %s was not found in dbt project" % fname
) # pragma: no cover
return results[0]
def _unsafe_process(self, fname, in_str=None, config=None):
original_file_path = os.path.relpath(fname, start=os.getcwd())
# Below, we monkeypatch Environment.from_string() to intercept when dbt
# compiles (i.e. runs Jinja) to expand the "node" corresponding to fname.
# We do this to capture the Jinja context at the time of compilation, i.e.:
# - Jinja Environment object
# - Jinja "globals" dictionary
#
# This info is captured by the "make_template()" function, which in
# turn is used by our parent class' (JinjaTemplater) slice_file()
# function.
old_from_string = Environment.from_string
try:
make_template = None
def from_string(*args, **kwargs):
"""Replaces (via monkeypatch) the jinja2.Environment function."""
nonlocal make_template
# Is it processing the node corresponding to fname?
globals = kwargs.get("globals")
if globals:
model = globals.get("model")
if model:
if model.get("original_file_path") == original_file_path:
# Yes. Capture the important arguments and create
# a make_template() function.
env = args[0]
globals = args[2] if len(args) >= 3 else kwargs["globals"]
def make_template(in_str):
env.add_extension(SnapshotExtension)
return env.from_string(in_str, globals=globals)
return old_from_string(*args, **kwargs)
finally:
# Undo the monkeypatch.
Environment.from_string = from_string
node = self._find_node(fname, config)
with self.connection():
node = self.dbt_compiler.compile_node(
node=node,
manifest=self.dbt_manifest,
)
Environment.from_string = old_from_string
if hasattr(node, "injected_sql"):
# If injected SQL is present, it contains a better picture
# of what will actually hit the database (e.g. with tests).
# However it's not always present.
compiled_sql = node.injected_sql
else:
compiled_sql = node.compiled_sql
if not compiled_sql: # pragma: no cover
raise SQLTemplaterError(
"dbt templater compilation failed silently, check your configuration "
"by running `dbt compile` directly."
)
with open(fname) as source_dbt_model:
source_dbt_sql = source_dbt_model.read()
n_trailing_newlines = len(source_dbt_sql) - len(source_dbt_sql.rstrip("\n"))
templater_logger.debug(
" Trailing newline count in source dbt model: %r",
n_trailing_newlines,
)
templater_logger.debug(" Raw SQL before compile: %r", source_dbt_sql)
templater_logger.debug(" Node raw SQL: %r", node.raw_sql)
templater_logger.debug(" Node compiled SQL: %r", compiled_sql)
# When using dbt-templater, trailing newlines are ALWAYS REMOVED during
# compiling. Unless fixed (like below), this will cause:
# 1. L009 linting errors when running "sqlfluff lint foo_bar.sql"
# since the linter will use the compiled code with the newlines
# removed.
# 2. "No newline at end of file" warnings in Git/GitHub since
# sqlfluff uses the compiled SQL to write fixes back to the
# source SQL in the dbt model.
# The solution is:
# 1. Check for trailing newlines before compiling by looking at the
# raw SQL in the source dbt file, store the count of trailing newlines.
# 2. Append the count from #1 above to the node.raw_sql and
# compiled_sql objects, both of which have had the trailing
# newlines removed by the dbt-templater.
node.raw_sql = node.raw_sql + "\n" * n_trailing_newlines
compiled_sql = compiled_sql + "\n" * n_trailing_newlines
raw_sliced, sliced_file, templated_sql = self.slice_file(
source_dbt_sql,
compiled_sql,
config=config,
make_template=make_template,
)
if make_template and n_trailing_newlines:
# Update templated_sql as we updated the other strings above. Update
# sliced_file to reflect the mapping of the added character(s) back
# to the raw SQL.
templated_sql = templated_sql + "\n" * n_trailing_newlines
sliced_file.append(
TemplatedFileSlice(
slice_type="literal",
source_slice=slice(
len(source_dbt_sql) - n_trailing_newlines, len(source_dbt_sql)
),
templated_slice=slice(
len(templated_sql) - n_trailing_newlines, len(templated_sql)
),
)
)
return (
TemplatedFile(
source_str=source_dbt_sql,
templated_str=templated_sql,
fname=fname,
sliced_file=sliced_file,
raw_sliced=raw_sliced,
),
# No violations returned in this way.
[],
)
def _slice_template(self, in_str: str) -> List[RawFileSlice]:
# DbtTemplater uses the original heuristic-based template slicer.
# TODO: Can it be updated to use TemplateTracer?
return slice_template(in_str, self._get_jinja_env())
@contextmanager
def connection(self):
"""Context manager that manages a dbt connection, if needed."""
# We have to register the connection in dbt >= 1.0.0 ourselves
# In previous versions, we relied on the functionality removed in
# https://github.com/dbt-labs/dbt-core/pull/4062.
if DBT_VERSION_TUPLE >= (1, 0):
adapter = get_adapter(self.dbt_config)
with adapter.connection_named("master"):
adapter.set_relations_cache(self.dbt_manifest)
yield
else:
yield
class SnapshotExtension(StandaloneTag):
"""Dummy "snapshot" tags so raw dbt templates will parse.
Context: dbt snapshots (https://docs.getdbt.com/docs/building-a-dbt-project/snapshots/#example)
use custom Jinja "snapshot" and "endsnapshot" tags. However, dbt does not
actually register those tags with Jinja. Instead, it finds and removes these
tags during a preprocessing step. However, DbtTemplater needs those tags to
actually parse, because JinjaTracer creates and uses Jinja to process
another template similar to the original one.
"""
tags = {"snapshot", "endsnapshot"}
def render(self, format_string=None):
"""Dummy method that renders the tag."""
return ""
| 39.054983 | 109 | 0.593797 |
from collections import deque
from contextlib import contextmanager
import os
import os.path
import logging
from typing import List, Optional, Iterator, Tuple, Any, Dict, Deque
from dataclasses import dataclass
from functools import partial
from dbt.version import get_installed_version
from dbt.config.runtime import RuntimeConfig as DbtRuntimeConfig
from dbt.adapters.factory import register_adapter, get_adapter
from dbt.compilation import Compiler as DbtCompiler
from dbt.exceptions import (
CompilationException as DbtCompilationException,
FailedToConnectException as DbtFailedToConnectException,
)
from dbt import flags
from jinja2 import Environment
from jinja2_simple_tags import StandaloneTag
from sqlfluff.core.cached_property import cached_property
from sqlfluff.core.errors import SQLTemplaterError, SQLTemplaterSkipFile
from sqlfluff.core.templaters.base import (
RawFileSlice,
TemplatedFile,
TemplatedFileSlice,
)
from sqlfluff.core.templaters.slicers.heuristic import slice_template
from sqlfluff.core.templaters.jinja import JinjaTemplater
templater_logger = logging.getLogger("sqlfluff.templater")
DBT_VERSION = get_installed_version()
DBT_VERSION_STRING = DBT_VERSION.to_version_string()
DBT_VERSION_TUPLE = (int(DBT_VERSION.major), int(DBT_VERSION.minor))
if DBT_VERSION_TUPLE >= (1, 0):
from dbt.flags import PROFILES_DIR
else:
from dbt.config.profile import PROFILES_DIR
@dataclass
class DbtConfigArgs:
project_dir: Optional[str] = None
profiles_dir: Optional[str] = None
profile: Optional[str] = None
target: Optional[str] = None
single_threaded: bool = False
class DbtTemplater(JinjaTemplater):
name = "dbt"
sequential_fail_limit = 3
def __init__(self, **kwargs):
self.sqlfluff_config = None
self.formatter = None
self.project_dir = None
self.profiles_dir = None
self.working_dir = os.getcwd()
self._sequential_fails = 0
super().__init__(**kwargs)
def config_pairs(self):
return [("templater", self.name), ("dbt", self.dbt_version)]
@property
def dbt_version(self):
return DBT_VERSION_STRING
@property
def dbt_version_tuple(self):
return DBT_VERSION_TUPLE
@cached_property
def dbt_config(self):
if self.dbt_version_tuple >= (1, 0):
flags.set_from_args(
"",
DbtConfigArgs(
project_dir=self.project_dir,
profiles_dir=self.profiles_dir,
profile=self._get_profile(),
target=self._get_target(),
),
)
self.dbt_config = DbtRuntimeConfig.from_args(
DbtConfigArgs(
project_dir=self.project_dir,
profiles_dir=self.profiles_dir,
profile=self._get_profile(),
target=self._get_target(),
)
)
register_adapter(self.dbt_config)
return self.dbt_config
@cached_property
def dbt_compiler(self):
self.dbt_compiler = DbtCompiler(self.dbt_config)
return self.dbt_compiler
@cached_property
def dbt_manifest(self):
def identity(x):
return x
# a dull project and so some tracking routines
# may fail.
from dbt.tracking import do_not_track
do_not_track()
if self.dbt_version_tuple <= (0, 19):
if self.dbt_version_tuple == (0, 17): # pragma: no cover TODO?
# dbt version 0.17.*
from dbt.parser.manifest import (
load_internal_manifest as load_macro_manifest,
)
else:
# dbt version 0.18.* & # 0.19.*
from dbt.parser.manifest import load_macro_manifest
load_macro_manifest = partial(load_macro_manifest, macro_hook=identity)
from dbt.parser.manifest import load_manifest
dbt_macros_manifest = load_macro_manifest(self.dbt_config)
self.dbt_manifest = load_manifest(
self.dbt_config, dbt_macros_manifest, macro_hook=identity
)
else:
# dbt 0.20.* and onward
from dbt.parser.manifest import ManifestLoader
projects = self.dbt_config.load_dependencies()
loader = ManifestLoader(self.dbt_config, projects, macro_hook=identity)
self.dbt_manifest = loader.load()
return self.dbt_manifest
@cached_property
def dbt_selector_method(self):
if self.formatter: # pragma: no cover TODO?
self.formatter.dispatch_compilation_header(
"dbt templater", "Compiling dbt project..."
)
if self.dbt_version_tuple == (0, 17): # pragma: no cover TODO?
from dbt.graph.selector import PathSelector
self.dbt_selector_method = PathSelector(self.dbt_manifest)
else:
from dbt.graph.selector_methods import (
MethodManager as DbtSelectorMethodManager,
MethodName as DbtMethodName,
)
selector_methods_manager = DbtSelectorMethodManager(
self.dbt_manifest, previous_state=None
)
self.dbt_selector_method = selector_methods_manager.get_method(
DbtMethodName.Path, method_arguments=[]
)
if self.formatter: # pragma: no cover TODO?
self.formatter.dispatch_compilation_header(
"dbt templater", "Project Compiled."
)
return self.dbt_selector_method
def _get_profiles_dir(self):
dbt_profiles_dir = os.path.abspath(
os.path.expanduser(
self.sqlfluff_config.get_section(
(self.templater_selector, self.name, "profiles_dir")
)
or PROFILES_DIR
)
)
if not os.path.exists(dbt_profiles_dir):
templater_logger.error(
f"dbt_profiles_dir: {dbt_profiles_dir} could not be accessed. Check it exists."
)
return dbt_profiles_dir
def _get_project_dir(self):
dbt_project_dir = os.path.abspath(
os.path.expanduser(
self.sqlfluff_config.get_section(
(self.templater_selector, self.name, "project_dir")
)
or os.getcwd()
)
)
if not os.path.exists(dbt_project_dir):
templater_logger.error(
f"dbt_project_dir: {dbt_project_dir} could not be accessed. Check it exists."
)
return dbt_project_dir
def _get_profile(self):
return self.sqlfluff_config.get_section(
(self.templater_selector, self.name, "profile")
)
def _get_target(self):
return self.sqlfluff_config.get_section(
(self.templater_selector, self.name, "target")
)
def sequence_files(
self, fnames: List[str], config=None, formatter=None
) -> Iterator[str]:
if formatter: # pragma: no cover
formatter.dispatch_compilation_header("dbt templater", "Sorting Nodes...")
# Initialise config if not already done
self.sqlfluff_config = config
if not self.project_dir:
self.project_dir = self._get_project_dir()
if not self.profiles_dir:
self.profiles_dir = self._get_profiles_dir()
# Populate full paths for selected files
full_paths: Dict[str, str] = {}
selected_files = set()
for fname in fnames:
fpath = os.path.join(self.working_dir, fname)
full_paths[fpath] = fname
selected_files.add(fpath)
ephemeral_nodes: Dict[str, Tuple[str, Any]] = {}
# Extract the ephemeral models
for key, node in self.dbt_manifest.nodes.items():
if node.config.materialized == "ephemeral":
# The key is the full filepath.
# The value tuple, with the filepath and a list of dependent keys
ephemeral_nodes[key] = (
os.path.join(self.project_dir, node.original_file_path),
node.depends_on.nodes,
)
# Yield ephemeral nodes first. We use a Deque for efficient requeing.
# We iterate through the deque, yielding any nodes without dependents,
# or where those dependents have already yielded, first. The original
# mapping is still used to hold the metadata on each key.
already_yielded = set()
ephemeral_buffer: Deque[str] = deque(ephemeral_nodes.keys())
while ephemeral_buffer:
key = ephemeral_buffer.popleft()
fpath, dependents = ephemeral_nodes[key]
# If it's not in our selection, skip it
if fpath not in selected_files:
templater_logger.debug("- Purging unselected ephemeral: %r", fpath)
elif any(
dependent in ephemeral_buffer for dependent in dependents
): # pragma: no cover
templater_logger.debug(
"- Requeuing ephemeral with dependents: %r", fpath
)
# Requeue it for later
ephemeral_buffer.append(key)
# Otherwise yield it.
else:
templater_logger.debug("- Yielding Ephemeral: %r", fpath)
yield full_paths[fpath]
already_yielded.add(full_paths[fpath])
for fname in fnames:
if fname not in already_yielded:
yield fname
def process(self, *, fname, in_str=None, config=None, formatter=None):
# Stash the formatter if provided to use in cached methods.
self.formatter = formatter
self.sqlfluff_config = config
self.project_dir = self._get_project_dir()
self.profiles_dir = self._get_profiles_dir()
fname_absolute_path = os.path.abspath(fname)
try:
os.chdir(self.project_dir)
processed_result = self._unsafe_process(fname_absolute_path, in_str, config)
# Reset the fail counter
self._sequential_fails = 0
return processed_result
except DbtCompilationException as e:
# Increment the counter
self._sequential_fails += 1
if e.node:
return None, [
SQLTemplaterError(
f"dbt compilation error on file '{e.node.original_file_path}', {e.msg}",
# It's fatal if we're over the limit
fatal=self._sequential_fails > self.sequential_fail_limit,
)
]
else:
raise # pragma: no cover
except DbtFailedToConnectException as e:
return None, [
SQLTemplaterError(
"dbt tried to connect to the database and failed: "
"you could use 'execute' https://docs.getdbt.com/reference/dbt-jinja-functions/execute/ "
f"to skip the database calls. Error: {e.msg}",
fatal=True,
)
]
# If a SQLFluff error is raised, just pass it through
except SQLTemplaterError as e: # pragma: no cover
return None, [e]
finally:
os.chdir(self.working_dir)
def _find_node(self, fname, config=None):
if not config: # pragma: no cover
raise ValueError(
"For the dbt templater, the `process()` method requires a config object."
)
if not fname: # pragma: no cover
raise ValueError(
"For the dbt templater, the `process()` method requires a file name"
)
elif fname == "stdin": # pragma: no cover
raise ValueError(
"The dbt templater does not support stdin input, provide a path instead"
)
selected = self.dbt_selector_method.search(
included_nodes=self.dbt_manifest.nodes,
# Selector needs to be a relative path
selector=os.path.relpath(fname, start=os.getcwd()),
)
results = [self.dbt_manifest.expect(uid) for uid in selected]
if not results:
model_name = os.path.splitext(os.path.basename(fname))[0]
if DBT_VERSION_TUPLE >= (1, 0):
disabled_model = None
for key, disabled_model_nodes in self.dbt_manifest.disabled.items():
for disabled_model_node in disabled_model_nodes:
if os.path.abspath(
disabled_model_node.original_file_path
) == os.path.abspath(fname):
disabled_model = disabled_model_node
else:
disabled_model = self.dbt_manifest.find_disabled_by_name(
name=model_name
)
if disabled_model and os.path.abspath(
disabled_model.original_file_path
) == os.path.abspath(fname):
raise SQLTemplaterSkipFile(
f"Skipped file {fname} because the model was disabled"
)
raise RuntimeError(
"File %s was not found in dbt project" % fname
) # pragma: no cover
return results[0]
def _unsafe_process(self, fname, in_str=None, config=None):
original_file_path = os.path.relpath(fname, start=os.getcwd())
# Below, we monkeypatch Environment.from_string() to intercept when dbt
# compiles (i.e. runs Jinja) to expand the "node" corresponding to fname.
# We do this to capture the Jinja context at the time of compilation, i.e.:
# - Jinja Environment object
# - Jinja "globals" dictionary
#
# This info is captured by the "make_template()" function, which in
# turn is used by our parent class' (JinjaTemplater) slice_file()
old_from_string = Environment.from_string
try:
make_template = None
def from_string(*args, **kwargs):
nonlocal make_template
globals = kwargs.get("globals")
if globals:
model = globals.get("model")
if model:
if model.get("original_file_path") == original_file_path:
env = args[0]
globals = args[2] if len(args) >= 3 else kwargs["globals"]
def make_template(in_str):
env.add_extension(SnapshotExtension)
return env.from_string(in_str, globals=globals)
return old_from_string(*args, **kwargs)
finally:
Environment.from_string = from_string
node = self._find_node(fname, config)
with self.connection():
node = self.dbt_compiler.compile_node(
node=node,
manifest=self.dbt_manifest,
)
Environment.from_string = old_from_string
if hasattr(node, "injected_sql"):
compiled_sql = node.injected_sql
else:
compiled_sql = node.compiled_sql
if not compiled_sql: # pragma: no cover
raise SQLTemplaterError(
"dbt templater compilation failed silently, check your configuration "
"by running `dbt compile` directly."
)
with open(fname) as source_dbt_model:
source_dbt_sql = source_dbt_model.read()
n_trailing_newlines = len(source_dbt_sql) - len(source_dbt_sql.rstrip("\n"))
templater_logger.debug(
" Trailing newline count in source dbt model: %r",
n_trailing_newlines,
)
templater_logger.debug(" Raw SQL before compile: %r", source_dbt_sql)
templater_logger.debug(" Node raw SQL: %r", node.raw_sql)
templater_logger.debug(" Node compiled SQL: %r", compiled_sql)
# When using dbt-templater, trailing newlines are ALWAYS REMOVED during
# compiling. Unless fixed (like below), this will cause:
# 1. L009 linting errors when running "sqlfluff lint foo_bar.sql"
# since the linter will use the compiled code with the newlines
# removed.
# 2. "No newline at end of file" warnings in Git/GitHub since
# sqlfluff uses the compiled SQL to write fixes back to the
# source SQL in the dbt model.
# The solution is:
# 1. Check for trailing newlines before compiling by looking at the
# raw SQL in the source dbt file, store the count of trailing newlines.
# 2. Append the count from #1 above to the node.raw_sql and
# compiled_sql objects, both of which have had the trailing
# newlines removed by the dbt-templater.
node.raw_sql = node.raw_sql + "\n" * n_trailing_newlines
compiled_sql = compiled_sql + "\n" * n_trailing_newlines
raw_sliced, sliced_file, templated_sql = self.slice_file(
source_dbt_sql,
compiled_sql,
config=config,
make_template=make_template,
)
if make_template and n_trailing_newlines:
# Update templated_sql as we updated the other strings above. Update
# sliced_file to reflect the mapping of the added character(s) back
# to the raw SQL.
templated_sql = templated_sql + "\n" * n_trailing_newlines
sliced_file.append(
TemplatedFileSlice(
slice_type="literal",
source_slice=slice(
len(source_dbt_sql) - n_trailing_newlines, len(source_dbt_sql)
),
templated_slice=slice(
len(templated_sql) - n_trailing_newlines, len(templated_sql)
),
)
)
return (
TemplatedFile(
source_str=source_dbt_sql,
templated_str=templated_sql,
fname=fname,
sliced_file=sliced_file,
raw_sliced=raw_sliced,
),
# No violations returned in this way.
[],
)
def _slice_template(self, in_str: str) -> List[RawFileSlice]:
# DbtTemplater uses the original heuristic-based template slicer.
# TODO: Can it be updated to use TemplateTracer?
return slice_template(in_str, self._get_jinja_env())
@contextmanager
def connection(self):
# We have to register the connection in dbt >= 1.0.0 ourselves
# In previous versions, we relied on the functionality removed in
# https://github.com/dbt-labs/dbt-core/pull/4062.
if DBT_VERSION_TUPLE >= (1, 0):
adapter = get_adapter(self.dbt_config)
with adapter.connection_named("master"):
adapter.set_relations_cache(self.dbt_manifest)
yield
else:
yield
class SnapshotExtension(StandaloneTag):
tags = {"snapshot", "endsnapshot"}
def render(self, format_string=None):
return ""
| true | true |
1c46e354feed5cf4980e4dc9638c9d72ef429a1d | 7,419 | py | Python | east/utils/image_utils.py | embracesource-cv-com/keras-east | 0733a9a99c4446a30c8b8e1d62e102391f7a854a | [
"Apache-2.0"
] | 12 | 2019-04-01T01:58:13.000Z | 2019-12-10T02:54:18.000Z | east/utils/image_utils.py | embracesource-cv-com/keras-east | 0733a9a99c4446a30c8b8e1d62e102391f7a854a | [
"Apache-2.0"
] | 5 | 2019-04-22T16:00:02.000Z | 2020-08-12T07:03:05.000Z | east/utils/image_utils.py | embracesource-cv-com/keras-east | 0733a9a99c4446a30c8b8e1d62e102391f7a854a | [
"Apache-2.0"
] | 1 | 2019-05-24T11:34:44.000Z | 2019-05-24T11:34:44.000Z | # -*- coding: utf-8 -*-
"""
File Name: image
Description : 图像处理工具类
Author : mick.yi
date: 2019/2/18
"""
import skimage
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
import random
def load_image(image_path):
"""
加载图像
:param image_path: 图像路径
:return: [h,w,3] numpy数组
"""
image = plt.imread(image_path)
# 灰度图转为RGB
if len(image.shape) == 2:
image = np.expand_dims(image, axis=2)
image = np.tile(image, (1, 1, 3))
elif image.shape[-1] == 1:
image = skimage.color.gray2rgb(image) # io.imread 报ValueError: Input image expected to be RGB, RGBA or gray
# 标准化为0~255之间
if image.dtype == np.float32:
image *= 255
image = image.astype(np.uint8)
# 删除alpha通道
return image[..., :3]
def resize_image_and_gt(image, output_size, gt_polygons=None):
"""
按照输入大小缩放图像
:param image:
:param output_size:
:param gt_polygons:
:return:
image: (H,W,3)
image_meta: 元数据信息,详见compose_image_meta
gt_boxes:图像缩放及padding后对于的GT 边框坐标 [N,(y1,x1,y2,x2)]
"""
original_shape = image.shape
# resize图像,并获取相关元数据信息
h, w, window, scale, padding = resize_meta(original_shape[0], original_shape[1], output_size)
image = resize_image(image, h, w, padding)
# 组合元数据信息
image_meta = compose_image_meta(np.random.randint(10000), original_shape, image.shape,
window, scale)
# 根据缩放及padding调整GT边框
if gt_polygons is not None and gt_polygons.shape[0] > 0:
gt_polygons = adjust_polygons(gt_polygons, padding, scale)
return image, image_meta, gt_polygons
def random_crop_image(image, gt_window):
"""
随机裁剪图像
:param image: [H,W,C]
:param gt_window: 标注区域 (y1,x1,y2,x2)
:return: 裁剪后的图像和裁剪窗口
"""
h, w = list(image.shape)[:2]
y1, x1, y2, x2 = gt_window
# 每边最多裁剪1/10
crop_ratio = 0.1
wy1 = np.random.randint(min(y1 + 1, h * crop_ratio))
wx1 = np.random.randint(min(x1 + 1, w * crop_ratio))
wy2 = h - np.random.randint(min(h - y2 + 1, h * crop_ratio))
wx2 = w - np.random.randint(min(w - x2 + 1, w * crop_ratio))
return image[wy1:wy2, wx1:wx2], [wy1, wx1, wy2, wx2]
def resize_image(image, h, w, padding):
"""
缩放图像为正方形,指定长边大小,短边padding;
:param image: numpy 数组(H,W,3)
:param h: 缩放后的高度
:param w: 缩放后的宽度
:param padding:缩放后增加的padding
:return: 缩放后的图像,元素图像的宽口位置,缩放尺寸,padding
"""
image_dtype = image.dtype
image = transform.resize(image, (h, w), order=1, mode='constant',
cval=0, clip=True, preserve_range=True)
image = np.pad(image, padding, mode='constant', constant_values=0)
return image.astype(image_dtype)
def resize_meta(h, w, max_dim):
"""
计算resize的元数据信息
:param h: 图像原始高度
:param w: 图像原始宽度
:param max_dim: 缩放后的边长
:return:
"""
scale = max_dim / max(h, w) # 缩放尺寸
# 新的高度和宽度
h, w = round(h * scale), round(w * scale)
# 计算padding
top_pad = (max_dim - h) // 2
bottom_pad = max_dim - h - top_pad
left_pad = (max_dim - w) // 2
right_pad = max_dim - w - left_pad
padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
# 计算窗口
window = (top_pad, left_pad, h + top_pad, w + left_pad) #
return h, w, window, scale, padding
def compose_image_meta(image_id, original_image_shape, image_shape,
window, scale):
"""
组合图像元数据信息,返回numpy数据
:param image_id:
:param original_image_shape: 原始图像形状,tuple(H,W,3)
:param image_shape: 缩放后图像形状tuple(H,W,3)
:param window: 原始图像在缩放图像上的窗口位置(y1,x1,y2,x2)
:param scale: 缩放因子
:return:
"""
meta = np.array(
[image_id] + # size=1
list(original_image_shape) + # size=3
list(image_shape) + # size=3
list(window) + # size=4 (y1, x1, y2, x2) in image cooredinates
[scale] # size=1
)
return meta
def parse_image_meta(meta):
"""
解析图像元数据信息,注意输入是元数据信息数组
:param meta: [12]
:return:
"""
image_id = meta[0]
original_image_shape = meta[1:4]
image_shape = meta[4:7]
window = meta[7:11] # (y1, x1, y2, x2) window of image in in pixels
scale = meta[11]
return {
"image_id": image_id.astype(np.int32),
"original_image_shape": original_image_shape.astype(np.int32),
"image_shape": image_shape.astype(np.int32),
"window": window.astype(np.int32),
"scale": scale.astype(np.float32)
}
def batch_parse_image_meta(meta):
"""
解析图像元数据信息,注意输入是元数据信息数组
:param meta: [batch,12]
:return:
"""
image_id = meta[:, 0]
original_image_shape = meta[:, 1:4]
image_shape = meta[:, 4:7]
window = meta[:, 7:11] # (y1, x1, y2, x2) window of image in in pixels
scale = meta[:, 11]
return {
"image_id": image_id.astype(np.int32),
"original_image_shape": original_image_shape.astype(np.int32),
"image_shape": image_shape.astype(np.int32),
"window": window.astype(np.int32),
"scale": scale.astype(np.float32)
}
def adjust_box(boxes, padding, scale):
"""
根据填充和缩放因子,调整boxes的值
:param boxes: numpy 数组; GT boxes [N,(y1,x1,y2,x2)]
:param padding: [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
:param scale: 缩放因子
:return:
"""
boxes = boxes * scale
boxes[:, 0::2] += padding[0][0] # 高度padding
boxes[:, 1::2] += padding[1][0] # 宽度padding
return boxes
def adjust_polygons(polygons, padding, scale):
"""
根据填充和缩放因子,调整四边形的值
:param polygons: numpy 数组; GT polygons[N,4,(x,y)]
:param padding: [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
:param scale: 缩放因子
:return:
"""
polygons = polygons * scale
polygons[:, :, 1] += padding[0][0] # 高度padding
polygons[:, :, 0] += padding[1][0] # 宽度padding
return polygons
def recover_detect_boxes(boxes, window, scale):
"""
将检测边框映射到原始图像上,去除padding和缩放
:param boxes: numpy数组,[n,(y1,x1,y2,x2)]
:param window: [(y1,x1,y2,x2)]
:param scale: 标量
:return:
"""
# 去除padding
boxes[:, 0::2] -= window[0]
boxes[:, 1::2] -= window[1]
# 还原缩放
boxes /= scale
return boxes
def clip_polygons(polygons, window):
"""
将检测四边形映射到原始图像上,去除padding和缩放
:param polygons: numpy数组,[n,4,(x,y)]
:param window: [(y1,x1,y2,x2)]
:return:
"""
if len(polygons) == 0:
return polygons
y1, x1, y2, x2 = window
# 保证不越界
polygons[:, :, 1] = np.maximum(y1, np.minimum(y2, polygons[:, :, 1]))
polygons[:, :, 0] = np.maximum(x1, np.minimum(x2, polygons[:, :, 0]))
return polygons
def recover_detect_polygons(polygons, window, scale):
"""
将检测四边形映射到原始图像上,去除padding和缩放
:param polygons: numpy数组,[n,4,(x,y)]
:param window: [(y1,x1,y2,x2)]
:param scale: 标量
:return:
"""
if len(polygons) == 0:
return polygons
clip_polygons(polygons, window)
# 去除padding
polygons[:, :, 1] -= window[0] # 高度
polygons[:, :, 0] -= window[1] # 宽度
# 还原缩放
polygons /= scale
return polygons
| 28.755814 | 117 | 0.579189 |
import skimage
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
import random
def load_image(image_path):
image = plt.imread(image_path)
if len(image.shape) == 2:
image = np.expand_dims(image, axis=2)
image = np.tile(image, (1, 1, 3))
elif image.shape[-1] == 1:
image = skimage.color.gray2rgb(image)
if image.dtype == np.float32:
image *= 255
image = image.astype(np.uint8)
return image[..., :3]
def resize_image_and_gt(image, output_size, gt_polygons=None):
original_shape = image.shape
h, w, window, scale, padding = resize_meta(original_shape[0], original_shape[1], output_size)
image = resize_image(image, h, w, padding)
image_meta = compose_image_meta(np.random.randint(10000), original_shape, image.shape,
window, scale)
if gt_polygons is not None and gt_polygons.shape[0] > 0:
gt_polygons = adjust_polygons(gt_polygons, padding, scale)
return image, image_meta, gt_polygons
def random_crop_image(image, gt_window):
h, w = list(image.shape)[:2]
y1, x1, y2, x2 = gt_window
crop_ratio = 0.1
wy1 = np.random.randint(min(y1 + 1, h * crop_ratio))
wx1 = np.random.randint(min(x1 + 1, w * crop_ratio))
wy2 = h - np.random.randint(min(h - y2 + 1, h * crop_ratio))
wx2 = w - np.random.randint(min(w - x2 + 1, w * crop_ratio))
return image[wy1:wy2, wx1:wx2], [wy1, wx1, wy2, wx2]
def resize_image(image, h, w, padding):
image_dtype = image.dtype
image = transform.resize(image, (h, w), order=1, mode='constant',
cval=0, clip=True, preserve_range=True)
image = np.pad(image, padding, mode='constant', constant_values=0)
return image.astype(image_dtype)
def resize_meta(h, w, max_dim):
scale = max_dim / max(h, w)
h, w = round(h * scale), round(w * scale)
top_pad = (max_dim - h) // 2
bottom_pad = max_dim - h - top_pad
left_pad = (max_dim - w) // 2
right_pad = max_dim - w - left_pad
padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
window = (top_pad, left_pad, h + top_pad, w + left_pad)
return h, w, window, scale, padding
def compose_image_meta(image_id, original_image_shape, image_shape,
window, scale):
meta = np.array(
[image_id] +
list(original_image_shape) +
list(image_shape) +
list(window) +
[scale]
)
return meta
def parse_image_meta(meta):
image_id = meta[0]
original_image_shape = meta[1:4]
image_shape = meta[4:7]
window = meta[7:11]
scale = meta[11]
return {
"image_id": image_id.astype(np.int32),
"original_image_shape": original_image_shape.astype(np.int32),
"image_shape": image_shape.astype(np.int32),
"window": window.astype(np.int32),
"scale": scale.astype(np.float32)
}
def batch_parse_image_meta(meta):
image_id = meta[:, 0]
original_image_shape = meta[:, 1:4]
image_shape = meta[:, 4:7]
window = meta[:, 7:11]
scale = meta[:, 11]
return {
"image_id": image_id.astype(np.int32),
"original_image_shape": original_image_shape.astype(np.int32),
"image_shape": image_shape.astype(np.int32),
"window": window.astype(np.int32),
"scale": scale.astype(np.float32)
}
def adjust_box(boxes, padding, scale):
boxes = boxes * scale
boxes[:, 0::2] += padding[0][0]
boxes[:, 1::2] += padding[1][0]
return boxes
def adjust_polygons(polygons, padding, scale):
polygons = polygons * scale
polygons[:, :, 1] += padding[0][0]
polygons[:, :, 0] += padding[1][0]
return polygons
def recover_detect_boxes(boxes, window, scale):
boxes[:, 0::2] -= window[0]
boxes[:, 1::2] -= window[1]
boxes /= scale
return boxes
def clip_polygons(polygons, window):
if len(polygons) == 0:
return polygons
y1, x1, y2, x2 = window
polygons[:, :, 1] = np.maximum(y1, np.minimum(y2, polygons[:, :, 1]))
polygons[:, :, 0] = np.maximum(x1, np.minimum(x2, polygons[:, :, 0]))
return polygons
def recover_detect_polygons(polygons, window, scale):
if len(polygons) == 0:
return polygons
clip_polygons(polygons, window)
polygons[:, :, 1] -= window[0]
polygons[:, :, 0] -= window[1]
polygons /= scale
return polygons
| true | true |
1c46e48e2e3f579a1cdbebb866e2f56a6b6f6241 | 201 | py | Python | rpc/client.py | yuriscosta/tads-sistemas-distribuidos | 1bdcd3ff87bb5ecc2a722ef70bb4e7fd7c8540da | [
"MIT"
] | 1 | 2017-10-18T03:04:49.000Z | 2017-10-18T03:04:49.000Z | rpc/client.py | yuriscosta/tads-sistemas-distribuidos | 1bdcd3ff87bb5ecc2a722ef70bb4e7fd7c8540da | [
"MIT"
] | 1 | 2020-06-05T17:51:11.000Z | 2020-06-05T17:51:11.000Z | rpc/client.py | yuriscosta/tads-sistemas-distribuidos | 1bdcd3ff87bb5ecc2a722ef70bb4e7fd7c8540da | [
"MIT"
] | null | null | null | import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.pow(2,3))
print(s.add(2,3))
print(s.mul(5,2))
# Gerando erros
print(s.pow(0,0))
print(s.add(1))
print(s.sub(1, 2))
| 16.75 | 54 | 0.676617 | import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.pow(2,3))
print(s.add(2,3))
print(s.mul(5,2))
print(s.pow(0,0))
print(s.add(1))
print(s.sub(1, 2))
| true | true |
1c46e5e885ba5b8a6ca6466a4c60eccdef77f19e | 9,122 | py | Python | src/rosdep2/platforms/debian.py | gavanderhoorn/rosdep | 641433af01bb217b807af6adda2b9f7a0c55f727 | [
"BSD-3-Clause"
] | null | null | null | src/rosdep2/platforms/debian.py | gavanderhoorn/rosdep | 641433af01bb217b807af6adda2b9f7a0c55f727 | [
"BSD-3-Clause"
] | null | null | null | src/rosdep2/platforms/debian.py | gavanderhoorn/rosdep | 641433af01bb217b807af6adda2b9f7a0c55f727 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# Copyright (c) 2009, Willow Garage, 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 the Willow Garage, 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.
# Author Tully Foote, Ken Conley
from __future__ import print_function
import subprocess
import sys
from rospkg.os_detect import OS_DEBIAN, OS_LINARO, OS_UBUNTU, OS_ELEMENTARY, OsDetect
from .pip import PIP_INSTALLER
from .gem import GEM_INSTALLER
from .source import SOURCE_INSTALLER
from ..installers import PackageManagerInstaller
from ..shell_utils import read_stdout
# apt package manager key
APT_INSTALLER = 'apt'
def register_installers(context):
context.set_installer(APT_INSTALLER, AptInstaller())
def register_platforms(context):
register_debian(context)
register_linaro(context)
register_ubuntu(context)
register_elementary(context)
def register_debian(context):
context.add_os_installer_key(OS_DEBIAN, APT_INSTALLER)
context.add_os_installer_key(OS_DEBIAN, PIP_INSTALLER)
context.add_os_installer_key(OS_DEBIAN, GEM_INSTALLER)
context.add_os_installer_key(OS_DEBIAN, SOURCE_INSTALLER)
context.set_default_os_installer_key(OS_DEBIAN, lambda self: APT_INSTALLER)
context.set_os_version_type(OS_DEBIAN, OsDetect.get_codename)
def register_linaro(context):
# Linaro is an alias for Ubuntu. If linaro is detected and it's not set as
# an override force ubuntu.
(os_name, os_version) = context.get_os_name_and_version()
if os_name == OS_LINARO and not context.os_override:
print('rosdep detected OS: [%s] aliasing it to: [%s]' %
(OS_LINARO, OS_UBUNTU), file=sys.stderr)
context.set_os_override(OS_UBUNTU, context.os_detect.get_codename())
def register_elementary(context):
# Elementary is an alias for Ubuntu. If elementary is detected and it's
# not set as an override force ubuntu.
(os_name, os_version) = context.get_os_name_and_version()
if os_name == OS_ELEMENTARY and not context.os_override:
print('rosdep detected OS: [%s] aliasing it to: [%s]' %
(OS_ELEMENTARY, OS_UBUNTU), file=sys.stderr)
context.set_os_override(OS_UBUNTU, context.os_detect.get_codename())
def register_ubuntu(context):
context.add_os_installer_key(OS_UBUNTU, APT_INSTALLER)
context.add_os_installer_key(OS_UBUNTU, PIP_INSTALLER)
context.add_os_installer_key(OS_UBUNTU, GEM_INSTALLER)
context.add_os_installer_key(OS_UBUNTU, SOURCE_INSTALLER)
context.set_default_os_installer_key(OS_UBUNTU, lambda self: APT_INSTALLER)
context.set_os_version_type(OS_UBUNTU, OsDetect.get_codename)
def _read_apt_cache_showpkg(packages, exec_fn=None):
"""
Output whether these packages are virtual package list providing package.
If one package was not found, it gets returned as non-virtual.
:param exec_fn: see `dpkg_detect`; make sure that exec_fn supports a
second, boolean, parameter.
"""
cmd = ['apt-cache', 'showpkg'] + packages
if exec_fn is None:
exec_fn = read_stdout
std_out = exec_fn(cmd).splitlines()
starts = []
notfound = set()
for p in packages:
last_start = starts[-1] if len(starts) > 0 else 0
try:
starts.append(std_out.index('Package: %s' % p, last_start))
except ValueError:
notfound.add(p)
starts.append(None)
for p in packages:
if p in notfound:
yield p, False, None
continue
start = starts.pop(0)
lines = iter(std_out[start:starts[0]])
header = 'Package: %s' % p
# proceed to Package header
while next(lines) != header:
pass
# proceed to versions section
while next(lines) != 'Versions: ':
pass
# virtual packages don't have versions
if next(lines) != '':
yield p, False, None
continue
# proceed to reserve provides section
while next(lines) != 'Reverse Provides: ':
pass
pr = [line.split(' ', 2)[0] for line in lines]
if pr:
yield p, True, pr
else:
yield p, False, None
def dpkg_detect(pkgs, exec_fn=None):
"""
Given a list of package, return the list of installed packages.
:param pkgs: list of package names, optionally followed by a fixed version (`foo=3.0`)
:param exec_fn: function to execute Popen and read stdout (for testing)
:return: list elements in *pkgs* that were found installed on the system
"""
ret_list = []
# this is mainly a hack to support version locking for eigen.
# we strip version-locking syntax, e.g. libeigen3-dev=3.0.1-*.
# our query does not do the validation on the version itself.
# This is a map `package name -> package name optionally with version`.
version_lock_map = {}
for p in pkgs:
if '=' in p:
version_lock_map[p.split('=')[0]] = p
else:
version_lock_map[p] = p
cmd = ['dpkg-query', '-W', '-f=\'${Package} ${Status}\n\'']
cmd.extend(version_lock_map.keys())
if exec_fn is None:
exec_fn = read_stdout
std_out, std_err = exec_fn(cmd, True)
std_out = std_out.replace('\'', '')
pkg_list = std_out.split('\n')
for pkg in pkg_list:
pkg_row = pkg.split()
if len(pkg_row) == 4 and (pkg_row[3] == 'installed'):
ret_list.append(pkg_row[0])
installed_packages = [version_lock_map[r] for r in ret_list]
# now for the remaining packages check, whether they are installed as
# virtual packages
remaining = _read_apt_cache_showpkg(list(p for p in pkgs if p not in installed_packages))
virtual = [n for (n, v, pr) in remaining if v and len(dpkg_detect(pr)) > 0]
return installed_packages + virtual
def _iterate_packages(packages, reinstall):
for entry in _read_apt_cache_showpkg(packages):
p, is_virtual, providers = entry
if is_virtual:
installed = []
if reinstall:
installed = dpkg_detect(providers)
if len(installed) > 0:
for i in installed:
yield i
continue # don't ouput providers
yield providers
else:
yield p
class AptInstaller(PackageManagerInstaller):
"""
An implementation of the Installer for use on debian style
systems.
"""
def __init__(self):
super(AptInstaller, self).__init__(dpkg_detect)
def get_version_strings(self):
output = subprocess.check_output(['apt-get', '--version'])
version = output.splitlines()[0].split(' ')[1]
return ['apt-get {}'.format(version)]
def _get_install_commands_for_package(self, base_cmd, package_or_list):
def pkg_command(p):
return self.elevate_priv(base_cmd + [p])
if isinstance(package_or_list, list):
return [pkg_command(p) for p in package_or_list]
else:
return pkg_command(package_or_list)
def get_install_command(self, resolved, interactive=True, reinstall=False, quiet=False):
packages = self.get_packages_to_install(resolved, reinstall=reinstall)
if not packages:
return []
if not interactive and quiet:
base_cmd = ['apt-get', 'install', '-y', '-qq']
elif quiet:
base_cmd = ['apt-get', 'install', '-qq']
if not interactive:
base_cmd = ['apt-get', 'install', '-y']
else:
base_cmd = ['apt-get', 'install']
return [self._get_install_commands_for_package(base_cmd, p) for p in _iterate_packages(packages, reinstall)]
| 36.931174 | 116 | 0.676168 |
from __future__ import print_function
import subprocess
import sys
from rospkg.os_detect import OS_DEBIAN, OS_LINARO, OS_UBUNTU, OS_ELEMENTARY, OsDetect
from .pip import PIP_INSTALLER
from .gem import GEM_INSTALLER
from .source import SOURCE_INSTALLER
from ..installers import PackageManagerInstaller
from ..shell_utils import read_stdout
APT_INSTALLER = 'apt'
def register_installers(context):
context.set_installer(APT_INSTALLER, AptInstaller())
def register_platforms(context):
register_debian(context)
register_linaro(context)
register_ubuntu(context)
register_elementary(context)
def register_debian(context):
context.add_os_installer_key(OS_DEBIAN, APT_INSTALLER)
context.add_os_installer_key(OS_DEBIAN, PIP_INSTALLER)
context.add_os_installer_key(OS_DEBIAN, GEM_INSTALLER)
context.add_os_installer_key(OS_DEBIAN, SOURCE_INSTALLER)
context.set_default_os_installer_key(OS_DEBIAN, lambda self: APT_INSTALLER)
context.set_os_version_type(OS_DEBIAN, OsDetect.get_codename)
def register_linaro(context):
# an override force ubuntu.
(os_name, os_version) = context.get_os_name_and_version()
if os_name == OS_LINARO and not context.os_override:
print('rosdep detected OS: [%s] aliasing it to: [%s]' %
(OS_LINARO, OS_UBUNTU), file=sys.stderr)
context.set_os_override(OS_UBUNTU, context.os_detect.get_codename())
def register_elementary(context):
# Elementary is an alias for Ubuntu. If elementary is detected and it's
(os_name, os_version) = context.get_os_name_and_version()
if os_name == OS_ELEMENTARY and not context.os_override:
print('rosdep detected OS: [%s] aliasing it to: [%s]' %
(OS_ELEMENTARY, OS_UBUNTU), file=sys.stderr)
context.set_os_override(OS_UBUNTU, context.os_detect.get_codename())
def register_ubuntu(context):
context.add_os_installer_key(OS_UBUNTU, APT_INSTALLER)
context.add_os_installer_key(OS_UBUNTU, PIP_INSTALLER)
context.add_os_installer_key(OS_UBUNTU, GEM_INSTALLER)
context.add_os_installer_key(OS_UBUNTU, SOURCE_INSTALLER)
context.set_default_os_installer_key(OS_UBUNTU, lambda self: APT_INSTALLER)
context.set_os_version_type(OS_UBUNTU, OsDetect.get_codename)
def _read_apt_cache_showpkg(packages, exec_fn=None):
cmd = ['apt-cache', 'showpkg'] + packages
if exec_fn is None:
exec_fn = read_stdout
std_out = exec_fn(cmd).splitlines()
starts = []
notfound = set()
for p in packages:
last_start = starts[-1] if len(starts) > 0 else 0
try:
starts.append(std_out.index('Package: %s' % p, last_start))
except ValueError:
notfound.add(p)
starts.append(None)
for p in packages:
if p in notfound:
yield p, False, None
continue
start = starts.pop(0)
lines = iter(std_out[start:starts[0]])
header = 'Package: %s' % p
while next(lines) != header:
pass
while next(lines) != 'Versions: ':
pass
if next(lines) != '':
yield p, False, None
continue
# proceed to reserve provides section
while next(lines) != 'Reverse Provides: ':
pass
pr = [line.split(' ', 2)[0] for line in lines]
if pr:
yield p, True, pr
else:
yield p, False, None
def dpkg_detect(pkgs, exec_fn=None):
ret_list = []
# this is mainly a hack to support version locking for eigen.
# we strip version-locking syntax, e.g. libeigen3-dev=3.0.1-*.
# our query does not do the validation on the version itself.
# This is a map `package name -> package name optionally with version`.
version_lock_map = {}
for p in pkgs:
if '=' in p:
version_lock_map[p.split('=')[0]] = p
else:
version_lock_map[p] = p
cmd = ['dpkg-query', '-W', '-f=\'${Package} ${Status}\n\'']
cmd.extend(version_lock_map.keys())
if exec_fn is None:
exec_fn = read_stdout
std_out, std_err = exec_fn(cmd, True)
std_out = std_out.replace('\'', '')
pkg_list = std_out.split('\n')
for pkg in pkg_list:
pkg_row = pkg.split()
if len(pkg_row) == 4 and (pkg_row[3] == 'installed'):
ret_list.append(pkg_row[0])
installed_packages = [version_lock_map[r] for r in ret_list]
remaining = _read_apt_cache_showpkg(list(p for p in pkgs if p not in installed_packages))
virtual = [n for (n, v, pr) in remaining if v and len(dpkg_detect(pr)) > 0]
return installed_packages + virtual
def _iterate_packages(packages, reinstall):
for entry in _read_apt_cache_showpkg(packages):
p, is_virtual, providers = entry
if is_virtual:
installed = []
if reinstall:
installed = dpkg_detect(providers)
if len(installed) > 0:
for i in installed:
yield i
continue
yield providers
else:
yield p
class AptInstaller(PackageManagerInstaller):
def __init__(self):
super(AptInstaller, self).__init__(dpkg_detect)
def get_version_strings(self):
output = subprocess.check_output(['apt-get', '--version'])
version = output.splitlines()[0].split(' ')[1]
return ['apt-get {}'.format(version)]
def _get_install_commands_for_package(self, base_cmd, package_or_list):
def pkg_command(p):
return self.elevate_priv(base_cmd + [p])
if isinstance(package_or_list, list):
return [pkg_command(p) for p in package_or_list]
else:
return pkg_command(package_or_list)
def get_install_command(self, resolved, interactive=True, reinstall=False, quiet=False):
packages = self.get_packages_to_install(resolved, reinstall=reinstall)
if not packages:
return []
if not interactive and quiet:
base_cmd = ['apt-get', 'install', '-y', '-qq']
elif quiet:
base_cmd = ['apt-get', 'install', '-qq']
if not interactive:
base_cmd = ['apt-get', 'install', '-y']
else:
base_cmd = ['apt-get', 'install']
return [self._get_install_commands_for_package(base_cmd, p) for p in _iterate_packages(packages, reinstall)]
| true | true |
1c46e7371d0f642717b0dbe3ec998d628839b8d6 | 6,710 | py | Python | novelle/views/routes.py | sahuashi/novelle | 04295f4060af763a23a299219da73ba46c1ed626 | [
"MIT"
] | null | null | null | novelle/views/routes.py | sahuashi/novelle | 04295f4060af763a23a299219da73ba46c1ed626 | [
"MIT"
] | null | null | null | novelle/views/routes.py | sahuashi/novelle | 04295f4060af763a23a299219da73ba46c1ed626 | [
"MIT"
] | null | null | null | import os
import requests
from flask import Blueprint, render_template, flash, request, redirect, url_for, current_app
from flask_login import login_required, logout_user, login_user, current_user
from sqlalchemy import exc
from novelle.models import db, User, Book
from novelle.forms import Form
router = Blueprint('route', __name__)
# no home page at the moment, redirect from home page to search page
@router.route("/")
def index():
return redirect(url_for('route.search'))
# allow user to search query
@router.route("/search", methods=["POST", "GET"])
def search():
if request.method == "POST":
q = request.form["query"]
return redirect(url_for('route.retrieve', query=q))
else:
return render_template('search.html')
# retrieve book results from Google Books API
@router.route("/search/<query>")
def retrieve(query):
api_key = os.environ.get('BOOKS_API_KEY')
search_query = query
# build url for api request
search_url = f'https://www.googleapis.com/books/v1/volumes?q={search_query}&projection=full&maxResults=15&key={api_key}'
# send request to api
resp = requests.get(search_url)
# save relevant book info from api response
responses = resp.json()['items']
books = parse_books(responses)
return render_template('results.html', books=books, query=query)
def parse_books(res):
# list to store parsed book information
books = []
# retrieve relevant info from json
for book in res:
book_info = {
'id': book['id'],
'title': book['volumeInfo']['title'] if 'title' in book['volumeInfo'] else 'No title available.',
'subtitle': book['volumeInfo']['subtitle'] if 'subtitle' in book['volumeInfo'] else '',
'desc': book['volumeInfo']['description'] if 'description' in book[
'volumeInfo'] else 'No description available.',
'author': book['volumeInfo']['authors'][0] if 'authors' in book['volumeInfo'] else 'No authors available.',
'date': book['volumeInfo']['publishedDate'] if 'publishedDate' in book[
'volumeInfo'] else 'No published date available.',
'publisher': book['volumeInfo']['publisher'] if 'publisher' in book[
'volumeInfo'] else ' No publisher available.',
'thumbnail': book['volumeInfo']['imageLinks']['thumbnail'] if 'imageLinks' in book[
'volumeInfo'] else 'https://islandpress.org/sites/default/files/default_book_cover_2015.jpg',
'pages': book['volumeInfo']['pageCount'] if 'pageCount' in book[
'volumeInfo'] else 'No page count available.',
'rating': f"{book['volumeInfo']['averageRating']}/5 based on {book['volumeInfo']['ratingsCount']} review(s)"
if 'averageRating' in book['volumeInfo'] else 'No rating available.',
'infoLink': book['volumeInfo']['infoLink'] if 'infoLink' in book['volumeInfo'] else ' '
}
# add current book to list of book results
books.append(book_info)
# add current book to database
try:
book = Book(id=book_info.get('id'),
title=book_info.get('title'),
subtitle=book_info.get('subtitle'),
thumbnail=book_info.get('thumbnail'),
googlebooks=book_info.get('infoLink')
)
db.session.add(book)
db.session.flush()
# if current book info already in db, abort
except exc.SQLAlchemyError:
db.session.rollback()
# else, save updated db
else:
db.session.commit()
return books
# allow user to login to view and add to list
@router.route("/login", methods=['GET', 'POST'])
def login():
form = Form()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if user.password == form.password.data:
# valid login, redirect to user's reading list
login_user(user)
flash(f'Welcome back, {current_user.username}!')
return redirect(url_for('route.list'))
# invalid login, return to login page to try again
flash('Invalid username/password. Please try again.')
return redirect(url_for('route.login'))
return render_template('login.html', form=form)
# allow user to create account
@router.route("/register", methods=['GET', 'POST'])
def register():
form = Form()
if form.validate_on_submit():
user = User(username=form.username.data, password=form.password.data)
# add new user to database
try:
db.session.add(user)
db.session.flush()
# if user already exists, abort
except exc.SQLAlchemyError:
db.session.rollback()
flash('Username already taken! Please try again.')
return redirect(url_for('route.register'))
# save changes to database and have user login
else:
db.session.commit()
flash('Account created! Please login to continue.')
return redirect(url_for('route.login'))
return render_template('register.html', form=form)
# protected route: allow user to logout
@router.route("/logout")
@login_required
def logout():
flash(f'You were successfully logged out, {current_user.username}!')
logout_user()
return redirect(url_for('route.index'))
# display user's reading list
@router.route("/mylist")
def list():
if current_user.is_authenticated:
return render_template('list.html', user=current_user)
else:
flash('You must login to see your reading list.')
return redirect(url_for('route.login'))
# add book to user's reading list
@router.route("/save", methods=['POST', 'GET'])
def save():
if current_user.is_authenticated:
if request.method == "POST":
book_id = request.form['bookid']
book = Book.query.filter_by(id=book_id).first()
user = current_user
user.list.append(book)
db.session.commit()
return redirect(url_for('route.list'))
else:
flash('You must login to save to your reading list.')
return redirect(url_for('route.login'))
@router.route("/delete", methods=['POST'])
def delete():
book_id = request.form['bookid']
book = Book.query.filter_by(id=book_id).first()
user = current_user
user.list.remove(book)
db.session.commit()
return redirect(url_for('route.list'))
@router.route('/favicon.ico')
def favicon():
return current_app.send_static_file('favicon.ico')
| 37.909605 | 124 | 0.628167 | import os
import requests
from flask import Blueprint, render_template, flash, request, redirect, url_for, current_app
from flask_login import login_required, logout_user, login_user, current_user
from sqlalchemy import exc
from novelle.models import db, User, Book
from novelle.forms import Form
router = Blueprint('route', __name__)
@router.route("/")
def index():
return redirect(url_for('route.search'))
@router.route("/search", methods=["POST", "GET"])
def search():
if request.method == "POST":
q = request.form["query"]
return redirect(url_for('route.retrieve', query=q))
else:
return render_template('search.html')
@router.route("/search/<query>")
def retrieve(query):
api_key = os.environ.get('BOOKS_API_KEY')
search_query = query
search_url = f'https://www.googleapis.com/books/v1/volumes?q={search_query}&projection=full&maxResults=15&key={api_key}'
resp = requests.get(search_url)
responses = resp.json()['items']
books = parse_books(responses)
return render_template('results.html', books=books, query=query)
def parse_books(res):
books = []
for book in res:
book_info = {
'id': book['id'],
'title': book['volumeInfo']['title'] if 'title' in book['volumeInfo'] else 'No title available.',
'subtitle': book['volumeInfo']['subtitle'] if 'subtitle' in book['volumeInfo'] else '',
'desc': book['volumeInfo']['description'] if 'description' in book[
'volumeInfo'] else 'No description available.',
'author': book['volumeInfo']['authors'][0] if 'authors' in book['volumeInfo'] else 'No authors available.',
'date': book['volumeInfo']['publishedDate'] if 'publishedDate' in book[
'volumeInfo'] else 'No published date available.',
'publisher': book['volumeInfo']['publisher'] if 'publisher' in book[
'volumeInfo'] else ' No publisher available.',
'thumbnail': book['volumeInfo']['imageLinks']['thumbnail'] if 'imageLinks' in book[
'volumeInfo'] else 'https://islandpress.org/sites/default/files/default_book_cover_2015.jpg',
'pages': book['volumeInfo']['pageCount'] if 'pageCount' in book[
'volumeInfo'] else 'No page count available.',
'rating': f"{book['volumeInfo']['averageRating']}/5 based on {book['volumeInfo']['ratingsCount']} review(s)"
if 'averageRating' in book['volumeInfo'] else 'No rating available.',
'infoLink': book['volumeInfo']['infoLink'] if 'infoLink' in book['volumeInfo'] else ' '
}
books.append(book_info)
try:
book = Book(id=book_info.get('id'),
title=book_info.get('title'),
subtitle=book_info.get('subtitle'),
thumbnail=book_info.get('thumbnail'),
googlebooks=book_info.get('infoLink')
)
db.session.add(book)
db.session.flush()
except exc.SQLAlchemyError:
db.session.rollback()
else:
db.session.commit()
return books
@router.route("/login", methods=['GET', 'POST'])
def login():
form = Form()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if user.password == form.password.data:
login_user(user)
flash(f'Welcome back, {current_user.username}!')
return redirect(url_for('route.list'))
# invalid login, return to login page to try again
flash('Invalid username/password. Please try again.')
return redirect(url_for('route.login'))
return render_template('login.html', form=form)
# allow user to create account
@router.route("/register", methods=['GET', 'POST'])
def register():
form = Form()
if form.validate_on_submit():
user = User(username=form.username.data, password=form.password.data)
# add new user to database
try:
db.session.add(user)
db.session.flush()
# if user already exists, abort
except exc.SQLAlchemyError:
db.session.rollback()
flash('Username already taken! Please try again.')
return redirect(url_for('route.register'))
# save changes to database and have user login
else:
db.session.commit()
flash('Account created! Please login to continue.')
return redirect(url_for('route.login'))
return render_template('register.html', form=form)
# protected route: allow user to logout
@router.route("/logout")
@login_required
def logout():
flash(f'You were successfully logged out, {current_user.username}!')
logout_user()
return redirect(url_for('route.index'))
# display user's reading list
@router.route("/mylist")
def list():
if current_user.is_authenticated:
return render_template('list.html', user=current_user)
else:
flash('You must login to see your reading list.')
return redirect(url_for('route.login'))
@router.route("/save", methods=['POST', 'GET'])
def save():
if current_user.is_authenticated:
if request.method == "POST":
book_id = request.form['bookid']
book = Book.query.filter_by(id=book_id).first()
user = current_user
user.list.append(book)
db.session.commit()
return redirect(url_for('route.list'))
else:
flash('You must login to save to your reading list.')
return redirect(url_for('route.login'))
@router.route("/delete", methods=['POST'])
def delete():
book_id = request.form['bookid']
book = Book.query.filter_by(id=book_id).first()
user = current_user
user.list.remove(book)
db.session.commit()
return redirect(url_for('route.list'))
@router.route('/favicon.ico')
def favicon():
return current_app.send_static_file('favicon.ico')
| true | true |
1c46e82782628298655f1652a3e4cd46980848c8 | 5,161 | py | Python | Synaptic-Flow/Utils/metrics.py | santosh-b/Alleviate-Robust-Overfitting | c369ab2eaf51ba02a15f45db77a8c9292c8dbbf8 | [
"MIT"
] | null | null | null | Synaptic-Flow/Utils/metrics.py | santosh-b/Alleviate-Robust-Overfitting | c369ab2eaf51ba02a15f45db77a8c9292c8dbbf8 | [
"MIT"
] | null | null | null | Synaptic-Flow/Utils/metrics.py | santosh-b/Alleviate-Robust-Overfitting | c369ab2eaf51ba02a15f45db77a8c9292c8dbbf8 | [
"MIT"
] | null | null | null | import torch
import torch.nn as nn
import numpy as np
import pandas as pd
from prune import *
from Layers import layers
def summary(model, scores, flops, prunable):
r"""Summary of compression results for a model.
"""
rows = []
for name, module in model.named_modules():
for pname, param in module.named_parameters(recurse=False):
pruned = prunable(module) and id(param) in scores.keys()
if pruned:
sparsity = getattr(module, pname+'_mask').detach().cpu().numpy().mean()
score = scores[id(param)].detach().cpu().numpy()
else:
sparsity = 1.0
score = np.zeros(1)
shape = param.detach().cpu().numpy().shape
flop = flops[name][pname]
score_mean = score.mean()
score_var = score.var()
score_sum = score.sum()
score_abs_mean = np.abs(score).mean()
score_abs_var = np.abs(score).var()
score_abs_sum = np.abs(score).sum()
rows.append([name, pname, sparsity, np.prod(shape), shape, flop,
score_mean, score_var, score_sum,
score_abs_mean, score_abs_var, score_abs_sum,
pruned])
columns = ['module', 'param', 'sparsity', 'size', 'shape', 'flops', 'score mean', 'score variance',
'score sum', 'score abs mean', 'score abs variance', 'score abs sum', 'prunable']
return pd.DataFrame(rows, columns=columns)
def flop(model, input_shape, device):
total = {}
def count_flops(name):
def hook(module, input, output):
flops = {}
if isinstance(module, layers.Linear) or isinstance(module, nn.Linear):
in_features = module.in_features
out_features = module.out_features
flops['weight'] = in_features * out_features
if module.bias is not None:
flops['bias'] = out_features
if isinstance(module, layers.Conv2d) or isinstance(module, nn.Conv2d):
in_channels = module.in_channels
out_channels = module.out_channels
kernel_size = int(np.prod(module.kernel_size))
output_size = output.size(2) * output.size(3)
flops['weight'] = in_channels * out_channels * kernel_size * output_size
if module.bias is not None:
flops['bias'] = out_channels * output_size
if isinstance(module, layers.BatchNorm1d) or isinstance(module, nn.BatchNorm1d):
if module.affine:
flops['weight'] = module.num_features
flops['bias'] = module.num_features
if isinstance(module, layers.BatchNorm2d) or isinstance(module, nn.BatchNorm2d):
output_size = output.size(2) * output.size(3)
if module.affine:
flops['weight'] = module.num_features * output_size
flops['bias'] = module.num_features * output_size
if isinstance(module, layers.Identity1d):
flops['weight'] = module.num_features
if isinstance(module, layers.Identity2d):
output_size = output.size(2) * output.size(3)
flops['weight'] = module.num_features * output_size
total[name] = flops
return hook
for name, module in model.named_modules():
module.register_forward_hook(count_flops(name))
input = torch.ones([1] + list(input_shape)).to(device)
model(input)
return total
# def conservation(model, scores, batchnorm, residual):
# r"""Summary of conservation results for a model.
# """
# rows = []
# bias_flux = 0.0
# mu = 0.0
# for name, module in reversed(list(model.named_modules())):
# if prunable(module, batchnorm, residual):
# weight_flux = 0.0
# for pname, param in module.named_parameters(recurse=False):
# # Get score
# score = scores[id(param)].detach().cpu().numpy()
# # Adjust batchnorm bias score for mean and variance
# if isinstance(module, (layers.Linear, layers.Conv2d)) and pname == "bias":
# bias = param.detach().cpu().numpy()
# score *= (bias - mu) / bias
# mu = 0.0
# if isinstance(module, (layers.BatchNorm1d, layers.BatchNorm2d)) and pname == "bias":
# mu = module.running_mean.detach().cpu().numpy()
# # Add flux
# if pname == "weight":
# weight_flux += score.sum()
# if pname == "bias":
# bias_flux += score.sum()
# layer_flux = weight_flux
# if not isinstance(module, (layers.Identity1d, layers.Identity2d)):
# layer_flux += bias_flux
# rows.append([name, layer_flux])
# columns = ['module', 'score flux']
# return pd.DataFrame(rows, columns=columns)
| 43.369748 | 104 | 0.550281 | import torch
import torch.nn as nn
import numpy as np
import pandas as pd
from prune import *
from Layers import layers
def summary(model, scores, flops, prunable):
rows = []
for name, module in model.named_modules():
for pname, param in module.named_parameters(recurse=False):
pruned = prunable(module) and id(param) in scores.keys()
if pruned:
sparsity = getattr(module, pname+'_mask').detach().cpu().numpy().mean()
score = scores[id(param)].detach().cpu().numpy()
else:
sparsity = 1.0
score = np.zeros(1)
shape = param.detach().cpu().numpy().shape
flop = flops[name][pname]
score_mean = score.mean()
score_var = score.var()
score_sum = score.sum()
score_abs_mean = np.abs(score).mean()
score_abs_var = np.abs(score).var()
score_abs_sum = np.abs(score).sum()
rows.append([name, pname, sparsity, np.prod(shape), shape, flop,
score_mean, score_var, score_sum,
score_abs_mean, score_abs_var, score_abs_sum,
pruned])
columns = ['module', 'param', 'sparsity', 'size', 'shape', 'flops', 'score mean', 'score variance',
'score sum', 'score abs mean', 'score abs variance', 'score abs sum', 'prunable']
return pd.DataFrame(rows, columns=columns)
def flop(model, input_shape, device):
total = {}
def count_flops(name):
def hook(module, input, output):
flops = {}
if isinstance(module, layers.Linear) or isinstance(module, nn.Linear):
in_features = module.in_features
out_features = module.out_features
flops['weight'] = in_features * out_features
if module.bias is not None:
flops['bias'] = out_features
if isinstance(module, layers.Conv2d) or isinstance(module, nn.Conv2d):
in_channels = module.in_channels
out_channels = module.out_channels
kernel_size = int(np.prod(module.kernel_size))
output_size = output.size(2) * output.size(3)
flops['weight'] = in_channels * out_channels * kernel_size * output_size
if module.bias is not None:
flops['bias'] = out_channels * output_size
if isinstance(module, layers.BatchNorm1d) or isinstance(module, nn.BatchNorm1d):
if module.affine:
flops['weight'] = module.num_features
flops['bias'] = module.num_features
if isinstance(module, layers.BatchNorm2d) or isinstance(module, nn.BatchNorm2d):
output_size = output.size(2) * output.size(3)
if module.affine:
flops['weight'] = module.num_features * output_size
flops['bias'] = module.num_features * output_size
if isinstance(module, layers.Identity1d):
flops['weight'] = module.num_features
if isinstance(module, layers.Identity2d):
output_size = output.size(2) * output.size(3)
flops['weight'] = module.num_features * output_size
total[name] = flops
return hook
for name, module in model.named_modules():
module.register_forward_hook(count_flops(name))
input = torch.ones([1] + list(input_shape)).to(device)
model(input)
return total
# """
| true | true |
1c46e8c37c4ba356c3728913dc60e567bdcb344e | 9,642 | py | Python | server/vcr-server/vcr_server/utils/solrqueue.py | brianorwhatever/aries-vcr | 96bb31a2f96406dfa2832dbd7790c46b60981e13 | [
"Apache-2.0"
] | 38 | 2019-01-07T02:49:55.000Z | 2020-01-27T17:26:09.000Z | server/vcr-server/vcr_server/utils/solrqueue.py | brianorwhatever/aries-vcr | 96bb31a2f96406dfa2832dbd7790c46b60981e13 | [
"Apache-2.0"
] | 364 | 2019-01-07T20:22:15.000Z | 2020-03-10T21:59:23.000Z | server/vcr-server/vcr_server/utils/solrqueue.py | brianorwhatever/aries-vcr | 96bb31a2f96406dfa2832dbd7790c46b60981e13 | [
"Apache-2.0"
] | 34 | 2019-01-04T19:16:04.000Z | 2020-02-20T19:24:25.000Z | import logging
import threading
import os
from queue import Empty, Full, Queue
from haystack.utils import get_identifier
from api.v2.search.index import TxnAwareSearchIndex
LOGGER = logging.getLogger(__name__)
# this will kill the vcr-api process
RTI_ABORT_ON_ERRORS = os.getenv("RTI_ABORT_ON_ERRORS", "TRUE").upper()
ABORT_ON_ERRORS = RTI_ABORT_ON_ERRORS == "TRUE"
# this will re-raise errors, which will kill the indexing thread
RTI_RAISE_ERRORS = os.getenv("RTI_RAISE_ERRORS", "FALSE").upper()
RAISE_ERRORS = RTI_RAISE_ERRORS == "TRUE"
# if both of the above are false, indexing errors will be ignored
# number of seconds to wait when solr queue is empty before retry
RTI_WAIT_TIME = os.getenv("RTI_WAIT_TIME", "5")
WAIT_TIME = int(RTI_WAIT_TIME)
# max number of items to trigger an update to the solr index
RTI_MAX_SOLR_BATCH = os.getenv("RTI_MAX_SOLR_BATCH", "25")
MAX_SOLR_BATCH = int(RTI_MAX_SOLR_BATCH)
class SolrQueue:
is_active = False
def __init__(self):
LOGGER.info("Initializing Solr queue ...")
self._queue = Queue()
self._prev_queue = None
self._stop = threading.Event()
self._thread = None
self._trigger = threading.Event()
def isactive(self):
return (self.is_active or not self._queue.empty())
def qsize(self):
return self._queue.qsize()
def add(self, index_cls, using, instances):
ids = [instance.id for instance in instances]
# Log the wallet_id to make it easy to search for the credentials when troubleshooting
# The record ids are not indexed so they are not searchable.
# wallet_ids = [instance.credential_id for instance in instances]
LOGGER.debug("Adding items to Solr queue for indexing; Class: %s, Using: %s", index_cls, using)
try:
self._queue.put((index_cls, using, ids, 0))
except Full:
LOGGER.error("Can't add items to the Solr queue because it is full")
raise
def delete(self, index_cls, using, instances):
ids = [get_identifier(instance) for instance in instances]
# Log the wallet_id to make it easy to search for the credentials when troubleshooting
# The record ids are not indexed so they are not searchable.
# wallet_ids = [instance.credential_id for instance in instances]
LOGGER.debug("Deleteing items from Solr queue/index; Class: %s, Using: %s", index_cls, using)
try:
self._queue.put((index_cls, using, ids, 1))
except Full:
LOGGER.error("Can't delete items from the Solr queue because it is full")
raise
def setup(self, app=None):
LOGGER.info("Setting up Solr queue ...")
if app is not None:
LOGGER.info("Wiring the Solr queue into the app; %s", app)
app["solrqueue"] = self
app.on_startup.append(self.app_start)
app.on_cleanup.append(self.app_stop)
LOGGER.info("Wiring the Solr queue into the TxnAwareSearchIndex.")
self._prev_queue = TxnAwareSearchIndex._backend_queue
TxnAwareSearchIndex._backend_queue = self
async def app_start(self, _app=None):
self.start()
async def app_stop(self, _app=None):
self.stop()
def __enter__(self):
self.setup()
self.start()
return self
def __exit__(self, type, value, tb):
LOGGER.info("Solr queue is exiting ...")
# if handling exception, don't wait for worker thread
self.stop(not type)
LOGGER.info("Restoring previous TxnAwareSearchIndex settings ...")
TxnAwareSearchIndex._backend_queue = self._prev_queue
def start(self):
LOGGER.info("Starting Solr queue ...")
self._thread = threading.Thread(target=self._run)
self._thread.start()
def stop(self, join=True):
LOGGER.info("Stoping Solr queue ...")
if not self._queue.empty():
LOGGER.error("The Solr queue is not empty, there are about %s items that will not be indexed", self._queue.qsize())
self._stop.set()
self._trigger.set()
if join:
self._thread.join()
def trigger(self):
LOGGER.info("Triggering Solr queue ...")
self._trigger.set()
def _run(self):
LOGGER.info("Running Solr queue ...")
while True:
LOGGER.debug("Waiting [%d] ...", WAIT_TIME)
self._trigger.wait(WAIT_TIME)
self._drain()
if self._stop.is_set():
LOGGER.info("Finished running Solr queue ...")
return
def index_type(self, index_cls, delete, using):
"""String representing the index class type."""
if not index_cls:
return None
return ("delete" if delete == 1 else "update") + "::" + str(index_cls) + "::" + str(using)
def _drain(self):
LOGGER.debug("Indexing Solr queue items ...")
global RAISE_ERRORS
global ABORT_ON_ERRORS
last_ids = {}
try:
self.is_active = True
while True:
try:
index_cls, using, ids, delete = self._queue.get_nowait()
LOGGER.debug("Pop items off the Solr queue for indexing; Class: %s, Using: %s, Delete: %s, Instances: %s", index_cls, using, delete, ids)
except Empty:
LOGGER.debug("Solr queue is empty ...")
index_cls = None
delete = 0
using = None
index_cls_type = self.index_type(index_cls, delete, using)
if index_cls:
LOGGER.debug("Updating list of ids for [%s]..." % index_cls_type)
if not index_cls_type in last_ids:
last_ids[index_cls_type] = {
"index_cls": index_cls,
"delete": delete,
"using": using,
"ids": set(),
}
last_ids[index_cls_type]["ids"].update(ids)
for attr, val in last_ids.items():
if (not index_cls) or MAX_SOLR_BATCH <= len(val["ids"]):
LOGGER.debug("Processing %s items for [%s]", len(val["ids"]), attr)
try:
if val["delete"] == 1:
self.remove(val["index_cls"], val["using"], val["ids"])
else:
self.update(val["index_cls"], val["using"], val["ids"])
last_ids[attr]["ids"] = set()
except:
LOGGER.exception("An unexpected exception was encountered while processing items from the Solr queue.", exc_info=True)
LOGGER.info("Requeueing items for later processing ...")
try:
self._queue.put( (val["index_cls"], val["using"], val["ids"], val["delete"]) )
except Full:
LOGGER.error("Can't requeue items to the Solr queue because it is full; %s", val["ids"])
raise
raise
if not index_cls:
LOGGER.debug("Done indexing items from Solr queue ...")
break
except Exception as e:
LOGGER.error("Error processing real-time index queue: %s", str(e))
if ABORT_ON_ERRORS:
# this will kill the vcr-api process
os.abort()
elif RAISE_ERRORS:
# this will re-raise errors, which will kill the indexing thread
raise
# if both of the above are false, indexing errors will be ignored
finally:
self.is_active = False
def update(self, index_cls, using, ids):
LOGGER.debug("Updating the indexes for Solr queue items ...")
index = index_cls()
backend = index.get_backend(using)
if backend is not None:
LOGGER.info("Updating indexes for %d row(s) from Solr queue: %s", len(ids), ids)
rows = index.index_queryset(using).filter(id__in=ids)
# Turn off silently_fail; throw an exception if there is an error so we can requeue the items being indexed.
backend.silently_fail = False
backend.update(index, rows)
# LOGGER.debug("Index update complete.")
else:
LOGGER.error("Failed to get backend. Unable to update the index for %d row(s) from the Solr queue: %s", len(ids), ids)
raise Exception("Failed to get backend. Unable to update the index for Solr queue")
def remove(self, index_cls, using, ids):
LOGGER.debug("Removing the indexes for Solr queue items ...")
index = index_cls()
backend = index.get_backend(using)
if backend is not None:
LOGGER.info("Removing indexes for %d row(s) in Solr queue: %s", len(ids), ids)
# Turn off silently_fail; throw an exception if there is an error so we can requeue the items being indexed.
backend.silently_fail = False
# backend.remove has no support for a list of IDs
backend.conn.delete(id=ids)
else:
LOGGER.error("Failed to get backend. Unable to remove the indexes for %d row(s) from the solr queue: %s", len(ids), ids)
raise Exception("Failed to get backend. Unable to remove the index for Solr queue")
| 42.663717 | 157 | 0.581 | import logging
import threading
import os
from queue import Empty, Full, Queue
from haystack.utils import get_identifier
from api.v2.search.index import TxnAwareSearchIndex
LOGGER = logging.getLogger(__name__)
RTI_ABORT_ON_ERRORS = os.getenv("RTI_ABORT_ON_ERRORS", "TRUE").upper()
ABORT_ON_ERRORS = RTI_ABORT_ON_ERRORS == "TRUE"
RTI_RAISE_ERRORS = os.getenv("RTI_RAISE_ERRORS", "FALSE").upper()
RAISE_ERRORS = RTI_RAISE_ERRORS == "TRUE"
RTI_WAIT_TIME = os.getenv("RTI_WAIT_TIME", "5")
WAIT_TIME = int(RTI_WAIT_TIME)
RTI_MAX_SOLR_BATCH = os.getenv("RTI_MAX_SOLR_BATCH", "25")
MAX_SOLR_BATCH = int(RTI_MAX_SOLR_BATCH)
class SolrQueue:
is_active = False
def __init__(self):
LOGGER.info("Initializing Solr queue ...")
self._queue = Queue()
self._prev_queue = None
self._stop = threading.Event()
self._thread = None
self._trigger = threading.Event()
def isactive(self):
return (self.is_active or not self._queue.empty())
def qsize(self):
return self._queue.qsize()
def add(self, index_cls, using, instances):
ids = [instance.id for instance in instances]
LOGGER.debug("Adding items to Solr queue for indexing; Class: %s, Using: %s", index_cls, using)
try:
self._queue.put((index_cls, using, ids, 0))
except Full:
LOGGER.error("Can't add items to the Solr queue because it is full")
raise
def delete(self, index_cls, using, instances):
ids = [get_identifier(instance) for instance in instances]
# Log the wallet_id to make it easy to search for the credentials when troubleshooting
# The record ids are not indexed so they are not searchable.
# wallet_ids = [instance.credential_id for instance in instances]
LOGGER.debug("Deleteing items from Solr queue/index; Class: %s, Using: %s", index_cls, using)
try:
self._queue.put((index_cls, using, ids, 1))
except Full:
LOGGER.error("Can't delete items from the Solr queue because it is full")
raise
def setup(self, app=None):
LOGGER.info("Setting up Solr queue ...")
if app is not None:
LOGGER.info("Wiring the Solr queue into the app; %s", app)
app["solrqueue"] = self
app.on_startup.append(self.app_start)
app.on_cleanup.append(self.app_stop)
LOGGER.info("Wiring the Solr queue into the TxnAwareSearchIndex.")
self._prev_queue = TxnAwareSearchIndex._backend_queue
TxnAwareSearchIndex._backend_queue = self
async def app_start(self, _app=None):
self.start()
async def app_stop(self, _app=None):
self.stop()
def __enter__(self):
self.setup()
self.start()
return self
def __exit__(self, type, value, tb):
LOGGER.info("Solr queue is exiting ...")
self.stop(not type)
LOGGER.info("Restoring previous TxnAwareSearchIndex settings ...")
TxnAwareSearchIndex._backend_queue = self._prev_queue
def start(self):
LOGGER.info("Starting Solr queue ...")
self._thread = threading.Thread(target=self._run)
self._thread.start()
def stop(self, join=True):
LOGGER.info("Stoping Solr queue ...")
if not self._queue.empty():
LOGGER.error("The Solr queue is not empty, there are about %s items that will not be indexed", self._queue.qsize())
self._stop.set()
self._trigger.set()
if join:
self._thread.join()
def trigger(self):
LOGGER.info("Triggering Solr queue ...")
self._trigger.set()
def _run(self):
LOGGER.info("Running Solr queue ...")
while True:
LOGGER.debug("Waiting [%d] ...", WAIT_TIME)
self._trigger.wait(WAIT_TIME)
self._drain()
if self._stop.is_set():
LOGGER.info("Finished running Solr queue ...")
return
def index_type(self, index_cls, delete, using):
if not index_cls:
return None
return ("delete" if delete == 1 else "update") + "::" + str(index_cls) + "::" + str(using)
def _drain(self):
LOGGER.debug("Indexing Solr queue items ...")
global RAISE_ERRORS
global ABORT_ON_ERRORS
last_ids = {}
try:
self.is_active = True
while True:
try:
index_cls, using, ids, delete = self._queue.get_nowait()
LOGGER.debug("Pop items off the Solr queue for indexing; Class: %s, Using: %s, Delete: %s, Instances: %s", index_cls, using, delete, ids)
except Empty:
LOGGER.debug("Solr queue is empty ...")
index_cls = None
delete = 0
using = None
index_cls_type = self.index_type(index_cls, delete, using)
if index_cls:
LOGGER.debug("Updating list of ids for [%s]..." % index_cls_type)
if not index_cls_type in last_ids:
last_ids[index_cls_type] = {
"index_cls": index_cls,
"delete": delete,
"using": using,
"ids": set(),
}
last_ids[index_cls_type]["ids"].update(ids)
for attr, val in last_ids.items():
if (not index_cls) or MAX_SOLR_BATCH <= len(val["ids"]):
LOGGER.debug("Processing %s items for [%s]", len(val["ids"]), attr)
try:
if val["delete"] == 1:
self.remove(val["index_cls"], val["using"], val["ids"])
else:
self.update(val["index_cls"], val["using"], val["ids"])
last_ids[attr]["ids"] = set()
except:
LOGGER.exception("An unexpected exception was encountered while processing items from the Solr queue.", exc_info=True)
LOGGER.info("Requeueing items for later processing ...")
try:
self._queue.put( (val["index_cls"], val["using"], val["ids"], val["delete"]) )
except Full:
LOGGER.error("Can't requeue items to the Solr queue because it is full; %s", val["ids"])
raise
raise
if not index_cls:
LOGGER.debug("Done indexing items from Solr queue ...")
break
except Exception as e:
LOGGER.error("Error processing real-time index queue: %s", str(e))
if ABORT_ON_ERRORS:
os.abort()
elif RAISE_ERRORS:
raise
finally:
self.is_active = False
def update(self, index_cls, using, ids):
LOGGER.debug("Updating the indexes for Solr queue items ...")
index = index_cls()
backend = index.get_backend(using)
if backend is not None:
LOGGER.info("Updating indexes for %d row(s) from Solr queue: %s", len(ids), ids)
rows = index.index_queryset(using).filter(id__in=ids)
backend.silently_fail = False
backend.update(index, rows)
else:
LOGGER.error("Failed to get backend. Unable to update the index for %d row(s) from the Solr queue: %s", len(ids), ids)
raise Exception("Failed to get backend. Unable to update the index for Solr queue")
def remove(self, index_cls, using, ids):
LOGGER.debug("Removing the indexes for Solr queue items ...")
index = index_cls()
backend = index.get_backend(using)
if backend is not None:
LOGGER.info("Removing indexes for %d row(s) in Solr queue: %s", len(ids), ids)
backend.silently_fail = False
backend.conn.delete(id=ids)
else:
LOGGER.error("Failed to get backend. Unable to remove the indexes for %d row(s) from the solr queue: %s", len(ids), ids)
raise Exception("Failed to get backend. Unable to remove the index for Solr queue")
| true | true |
1c46e8ebc705732b535b16f3a42154c4df52a3d9 | 82 | py | Python | tests/conftest.py | mishc9/flake_rba | eda1e80436f401871dba61a4c769204c2cbcfc65 | [
"MIT"
] | null | null | null | tests/conftest.py | mishc9/flake_rba | eda1e80436f401871dba61a4c769204c2cbcfc65 | [
"MIT"
] | null | null | null | tests/conftest.py | mishc9/flake_rba | eda1e80436f401871dba61a4c769204c2cbcfc65 | [
"MIT"
] | null | null | null | import pytest
@pytest.fixture
def fixture_template():
return "Hello World!"
| 11.714286 | 25 | 0.731707 | import pytest
@pytest.fixture
def fixture_template():
return "Hello World!"
| true | true |
1c46ea4290b2b9e013c4b3a29287456e61b6ca89 | 1,429 | py | Python | tests/plugins/inventory/test_nsot.py | omershtivi/nornir | 0bbded1dcf38245c75aadf74706ea8547b2a0e73 | [
"Apache-2.0"
] | 1 | 2019-04-10T08:14:59.000Z | 2019-04-10T08:14:59.000Z | tests/plugins/inventory/test_nsot.py | omershtivi/nornir | 0bbded1dcf38245c75aadf74706ea8547b2a0e73 | [
"Apache-2.0"
] | null | null | null | tests/plugins/inventory/test_nsot.py | omershtivi/nornir | 0bbded1dcf38245c75aadf74706ea8547b2a0e73 | [
"Apache-2.0"
] | null | null | null | import json
import os
from nornir.plugins.inventory import nsot
# We need import below to load fixtures
import pytest # noqa
BASE_PATH = os.path.join(os.path.dirname(__file__), "nsot")
def get_inv(requests_mock, case, **kwargs):
for i in ["interfaces", "sites", "devices"]:
with open("{}/{}/{}.json".format(BASE_PATH, case, i), "r") as f:
requests_mock.get(
"http://localhost:8990/api/{}".format(i),
json=json.load(f),
headers={"Content-type": "application/json"},
)
return nsot.NSOTInventory(**kwargs)
def transform_function(host):
attrs = ["user", "password"]
for a in attrs:
if a in host.data:
host["nornir_{}".format(a)] = host.data[a]
class Test(object):
def test_inventory(self, requests_mock):
inv = get_inv(requests_mock, "1.3.0", transform_function=transform_function)
assert len(inv.hosts) == 4
assert len(inv.filter(site="site1").hosts) == 2
assert len(inv.filter(os="junos").hosts) == 2
assert len(inv.filter(site="site1", os="junos").hosts) == 1
def test_transform_function(self, requests_mock):
inv = get_inv(requests_mock, "1.3.0", transform_function=transform_function)
for host in inv.hosts.values():
assert host["user"] == host["nornir_user"]
assert host["password"] == host["nornir_password"]
| 31.755556 | 84 | 0.615815 | import json
import os
from nornir.plugins.inventory import nsot
import pytest
BASE_PATH = os.path.join(os.path.dirname(__file__), "nsot")
def get_inv(requests_mock, case, **kwargs):
for i in ["interfaces", "sites", "devices"]:
with open("{}/{}/{}.json".format(BASE_PATH, case, i), "r") as f:
requests_mock.get(
"http://localhost:8990/api/{}".format(i),
json=json.load(f),
headers={"Content-type": "application/json"},
)
return nsot.NSOTInventory(**kwargs)
def transform_function(host):
attrs = ["user", "password"]
for a in attrs:
if a in host.data:
host["nornir_{}".format(a)] = host.data[a]
class Test(object):
def test_inventory(self, requests_mock):
inv = get_inv(requests_mock, "1.3.0", transform_function=transform_function)
assert len(inv.hosts) == 4
assert len(inv.filter(site="site1").hosts) == 2
assert len(inv.filter(os="junos").hosts) == 2
assert len(inv.filter(site="site1", os="junos").hosts) == 1
def test_transform_function(self, requests_mock):
inv = get_inv(requests_mock, "1.3.0", transform_function=transform_function)
for host in inv.hosts.values():
assert host["user"] == host["nornir_user"]
assert host["password"] == host["nornir_password"]
| true | true |
1c46eb9b38a94e1016136f4df0089ae4ec1eaff0 | 1,112 | py | Python | hexi/service/pipeline/inputManager.py | tunstek/hexi | ebb00e4e47ac90d96a26179a5786d768d95c4bd5 | [
"MIT"
] | 14 | 2017-10-07T23:19:09.000Z | 2021-10-08T12:13:59.000Z | hexi/service/pipeline/inputManager.py | tunstek/hexi | ebb00e4e47ac90d96a26179a5786d768d95c4bd5 | [
"MIT"
] | 1 | 2018-07-16T17:03:43.000Z | 2018-07-16T17:03:43.000Z | hexi/service/pipeline/inputManager.py | tunstek/hexi | ebb00e4e47ac90d96a26179a5786d768d95c4bd5 | [
"MIT"
] | 6 | 2018-05-18T14:25:26.000Z | 2021-03-28T12:37:21.000Z | import asyncio
import time
from hexi.service import event
from hexi.service.pipeline.BaseManager import BaseManager
from hexi.util import deque
from hexi.plugin.InputPlugin import InputPlugin
EMPTY_SIGNAL = [0, 0, 0, 0, 0, 0]
class InputManager(BaseManager):
def __init__(self):
super().__init__('input', 'input', InputPlugin)
self.data_log_queue = deque.WebSocketPipingDeque(maxlen=400)
def init(self):
super().init()
self.last_signal = EMPTY_SIGNAL
asyncio.ensure_future(self.fetch_signal_loop_async())
self.data_log_queue.attach_ws_endpoint(self.bp, '/api/input_log')
event.subscribe(self.on_input_raw_signal, ['hexi.pipeline.input.raw_data'])
async def fetch_signal_loop_async(self):
while True:
signal = self.last_signal
self.last_signal = EMPTY_SIGNAL
self.data_log_queue.append([int(time.time()), signal])
# TODO: test whether currently started
asyncio.ensure_future(event.publish('hexi.pipeline.input.data', signal))
await asyncio.sleep(1 / 20)
async def on_input_raw_signal(self, e):
self.last_signal = e['value']
| 30.054054 | 79 | 0.735612 | import asyncio
import time
from hexi.service import event
from hexi.service.pipeline.BaseManager import BaseManager
from hexi.util import deque
from hexi.plugin.InputPlugin import InputPlugin
EMPTY_SIGNAL = [0, 0, 0, 0, 0, 0]
class InputManager(BaseManager):
def __init__(self):
super().__init__('input', 'input', InputPlugin)
self.data_log_queue = deque.WebSocketPipingDeque(maxlen=400)
def init(self):
super().init()
self.last_signal = EMPTY_SIGNAL
asyncio.ensure_future(self.fetch_signal_loop_async())
self.data_log_queue.attach_ws_endpoint(self.bp, '/api/input_log')
event.subscribe(self.on_input_raw_signal, ['hexi.pipeline.input.raw_data'])
async def fetch_signal_loop_async(self):
while True:
signal = self.last_signal
self.last_signal = EMPTY_SIGNAL
self.data_log_queue.append([int(time.time()), signal])
asyncio.ensure_future(event.publish('hexi.pipeline.input.data', signal))
await asyncio.sleep(1 / 20)
async def on_input_raw_signal(self, e):
self.last_signal = e['value']
| true | true |
1c46ec3f4bcd5dfd904476a655c486582328757a | 7,446 | py | Python | tensorflow_io/python/experimental/numpy_dataset_ops.py | lgeiger/io | 90be860451a705e2fbe8cfdec3c30030112b5c69 | [
"Apache-2.0"
] | 558 | 2018-11-09T22:45:27.000Z | 2022-03-24T04:59:36.000Z | tensorflow_io/python/experimental/numpy_dataset_ops.py | lgeiger/io | 90be860451a705e2fbe8cfdec3c30030112b5c69 | [
"Apache-2.0"
] | 1,122 | 2018-12-09T03:30:40.000Z | 2022-03-31T16:22:15.000Z | tensorflow_io/python/experimental/numpy_dataset_ops.py | lgeiger/io | 90be860451a705e2fbe8cfdec3c30030112b5c69 | [
"Apache-2.0"
] | 319 | 2018-12-09T00:18:47.000Z | 2022-03-30T21:49:46.000Z | # Copyright 2018 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.
# ==============================================================================
"""NumpyIODataset"""
import numpy as np
import tensorflow as tf
from tensorflow_io.python.ops import core_ops
class NumpyIODataset(tf.data.Dataset):
"""NumpyIODataset"""
def __init__(self, a, internal=True):
"""NumpyIODataset."""
with tf.name_scope("NumpyIODataset"):
assert internal
entries = a
def p(entry):
address, _ = entry.__array_interface__["data"]
shape = entry.shape
dtype = tf.as_dtype(entry.dtype)
return address, "", "", shape, dtype
flatten = tf.nest.flatten(entries)
assert all([entry.shape[0] == flatten[0].shape[0] for entry in flatten])
params = [p(entry) for entry in flatten]
def f(start, stop):
return tf.nest.pack_sequence_as(
entries,
[
core_ops.io_numpy_read(
address=address,
filename=filename,
array=array,
shape=shape,
start=start,
stop=stop,
dtype=dtype,
)
for address, filename, array, shape, dtype in params
],
)
step = 1024
total = tf.constant(flatten[0].shape[0], tf.int64)
indices_start = tf.data.Dataset.range(0, total, step)
indices_stop = indices_start.skip(1).concatenate(
tf.data.Dataset.from_tensor_slices([total])
)
dataset = tf.data.Dataset.zip((indices_start, indices_stop))
dataset = dataset.map(f)
dataset = dataset.unbatch()
self._dataset = dataset
self._holder = [np.array(entry, copy=False) for entry in flatten]
super().__init__(
self._dataset._variant_tensor
) # pylint: disable=protected-access
def _inputs(self):
return []
@property
def element_spec(self):
return self._dataset.element_spec
class NumpyFileIODataset(tf.data.Dataset):
"""NumpyFileIODataset"""
def __init__(self, filename, spec=None, internal=True):
"""NumpyFileIODataset."""
with tf.name_scope("NumpyFileIODataset"):
assert internal
if tf.executing_eagerly():
arrays, shapes, dtypes = core_ops.io_numpy_info(filename=filename)
arrays = tf.unstack(arrays)
shapes = tf.unstack(shapes)
dtypes = tf.unstack(dtypes)
dtypes = [tf.as_dtype(dtype.numpy()) for dtype in dtypes]
entries = list(zip(shapes, dtypes, arrays))
entries = [
tf.TensorSpec(shape, dtype, array)
for (shape, dtype, array) in entries
]
indices = None
if all([e.numpy().decode().startswith("arr_") for e in arrays]):
try:
indices = [int(e.numpy()[4:]) for e in arrays]
except ValueError:
pass
if indices is not None:
values = list(indices)
values.sort()
if not all([k == v for k, v in enumerate(values)]):
indices = None
# if indices is continuously, then construct a tuple, otherwise a dict.
if indices is not None:
entries = dict(zip(indices, entries))
entries = tuple([entries[index] for index in sorted(indices)])
else:
indices = [index.numpy().decode() for index in tf.unstack(arrays)]
entries = dict(zip(indices, entries))
flatten = tf.nest.flatten(entries)
shapes = [entry.shape for entry in flatten]
assert all([shape[0] == shapes[0][0] for shape in shapes])
else:
assert spec is not None
if isinstance(spec, tuple):
entries = tuple(
[
tf.TensorSpec(
None,
(v if isinstance(v, tf.dtypes.DType) else v.dtype),
"arr_{}".format(i),
)
for i, v in enumerate(spec)
]
)
else:
entries = {
k: tf.TensorSpec(
None, (v if isinstance(v, tf.dtypes.DType) else v.dtype), k
)
for k, v in spec.items()
}
flatten = tf.nest.flatten(entries)
def shape_f(entry):
shape, _ = core_ops.io_numpy_spec(
filename=filename, array=entry.name
)
return shape
shapes = [shape_f(entry) for entry in flatten]
def p(entry, shape):
return 0, filename, entry.name, shape, entry.dtype
params = [p(entry, shape) for entry, shape in zip(flatten, shapes)]
def f(start, stop):
return tf.nest.pack_sequence_as(
entries,
[
core_ops.io_numpy_read(
address=address,
filename=filename,
array=array,
shape=shape,
start=start,
stop=stop,
dtype=dtype,
)
for address, filename, array, shape, dtype in params
],
)
step = 1024
total = tf.cast(shapes[0][0], tf.int64)
indices_start = tf.data.Dataset.range(0, total, step)
indices_stop = indices_start.skip(1).concatenate(
tf.data.Dataset.from_tensor_slices([total])
)
dataset = tf.data.Dataset.zip((indices_start, indices_stop))
dataset = dataset.map(f)
dataset = dataset.unbatch()
self._dataset = dataset
super().__init__(
self._dataset._variant_tensor
) # pylint: disable=protected-access
def _inputs(self):
return []
@property
def element_spec(self):
return self._dataset.element_spec
| 36.861386 | 87 | 0.480526 |
import numpy as np
import tensorflow as tf
from tensorflow_io.python.ops import core_ops
class NumpyIODataset(tf.data.Dataset):
def __init__(self, a, internal=True):
with tf.name_scope("NumpyIODataset"):
assert internal
entries = a
def p(entry):
address, _ = entry.__array_interface__["data"]
shape = entry.shape
dtype = tf.as_dtype(entry.dtype)
return address, "", "", shape, dtype
flatten = tf.nest.flatten(entries)
assert all([entry.shape[0] == flatten[0].shape[0] for entry in flatten])
params = [p(entry) for entry in flatten]
def f(start, stop):
return tf.nest.pack_sequence_as(
entries,
[
core_ops.io_numpy_read(
address=address,
filename=filename,
array=array,
shape=shape,
start=start,
stop=stop,
dtype=dtype,
)
for address, filename, array, shape, dtype in params
],
)
step = 1024
total = tf.constant(flatten[0].shape[0], tf.int64)
indices_start = tf.data.Dataset.range(0, total, step)
indices_stop = indices_start.skip(1).concatenate(
tf.data.Dataset.from_tensor_slices([total])
)
dataset = tf.data.Dataset.zip((indices_start, indices_stop))
dataset = dataset.map(f)
dataset = dataset.unbatch()
self._dataset = dataset
self._holder = [np.array(entry, copy=False) for entry in flatten]
super().__init__(
self._dataset._variant_tensor
)
def _inputs(self):
return []
@property
def element_spec(self):
return self._dataset.element_spec
class NumpyFileIODataset(tf.data.Dataset):
def __init__(self, filename, spec=None, internal=True):
with tf.name_scope("NumpyFileIODataset"):
assert internal
if tf.executing_eagerly():
arrays, shapes, dtypes = core_ops.io_numpy_info(filename=filename)
arrays = tf.unstack(arrays)
shapes = tf.unstack(shapes)
dtypes = tf.unstack(dtypes)
dtypes = [tf.as_dtype(dtype.numpy()) for dtype in dtypes]
entries = list(zip(shapes, dtypes, arrays))
entries = [
tf.TensorSpec(shape, dtype, array)
for (shape, dtype, array) in entries
]
indices = None
if all([e.numpy().decode().startswith("arr_") for e in arrays]):
try:
indices = [int(e.numpy()[4:]) for e in arrays]
except ValueError:
pass
if indices is not None:
values = list(indices)
values.sort()
if not all([k == v for k, v in enumerate(values)]):
indices = None
if indices is not None:
entries = dict(zip(indices, entries))
entries = tuple([entries[index] for index in sorted(indices)])
else:
indices = [index.numpy().decode() for index in tf.unstack(arrays)]
entries = dict(zip(indices, entries))
flatten = tf.nest.flatten(entries)
shapes = [entry.shape for entry in flatten]
assert all([shape[0] == shapes[0][0] for shape in shapes])
else:
assert spec is not None
if isinstance(spec, tuple):
entries = tuple(
[
tf.TensorSpec(
None,
(v if isinstance(v, tf.dtypes.DType) else v.dtype),
"arr_{}".format(i),
)
for i, v in enumerate(spec)
]
)
else:
entries = {
k: tf.TensorSpec(
None, (v if isinstance(v, tf.dtypes.DType) else v.dtype), k
)
for k, v in spec.items()
}
flatten = tf.nest.flatten(entries)
def shape_f(entry):
shape, _ = core_ops.io_numpy_spec(
filename=filename, array=entry.name
)
return shape
shapes = [shape_f(entry) for entry in flatten]
def p(entry, shape):
return 0, filename, entry.name, shape, entry.dtype
params = [p(entry, shape) for entry, shape in zip(flatten, shapes)]
def f(start, stop):
return tf.nest.pack_sequence_as(
entries,
[
core_ops.io_numpy_read(
address=address,
filename=filename,
array=array,
shape=shape,
start=start,
stop=stop,
dtype=dtype,
)
for address, filename, array, shape, dtype in params
],
)
step = 1024
total = tf.cast(shapes[0][0], tf.int64)
indices_start = tf.data.Dataset.range(0, total, step)
indices_stop = indices_start.skip(1).concatenate(
tf.data.Dataset.from_tensor_slices([total])
)
dataset = tf.data.Dataset.zip((indices_start, indices_stop))
dataset = dataset.map(f)
dataset = dataset.unbatch()
self._dataset = dataset
super().__init__(
self._dataset._variant_tensor
)
def _inputs(self):
return []
@property
def element_spec(self):
return self._dataset.element_spec
| true | true |
1c46ec4630ef2346b753d3b1c8de606804d39144 | 5,523 | py | Python | azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/security_rule_py3.py | Christina-Kang/azure-sdk-for-python | bbf982eb06aab04b8151f69f1d230b7f5fb96ebf | [
"MIT"
] | 1 | 2022-03-30T22:39:15.000Z | 2022-03-30T22:39:15.000Z | azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/security_rule_py3.py | Christina-Kang/azure-sdk-for-python | bbf982eb06aab04b8151f69f1d230b7f5fb96ebf | [
"MIT"
] | 54 | 2016-03-25T17:25:01.000Z | 2018-10-22T17:27:54.000Z | azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/security_rule_py3.py | Christina-Kang/azure-sdk-for-python | bbf982eb06aab04b8151f69f1d230b7f5fb96ebf | [
"MIT"
] | 2 | 2017-01-20T18:25:46.000Z | 2017-05-12T21:31:47.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 .sub_resource import SubResource
class SecurityRule(SubResource):
"""Network security rule.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:param description: A description for this rule. Restricted to 140 chars.
:type description: str
:param protocol: Required. Network protocol this rule applies to. Possible
values are 'Tcp', 'Udp', and '*'. Possible values include: 'Tcp', 'Udp',
'*'
:type protocol: str or
~azure.mgmt.network.v2017_03_01.models.SecurityRuleProtocol
:param source_port_range: The source port or range. Integer or range
between 0 and 65535. Asterix '*' can also be used to match all ports.
:type source_port_range: str
:param destination_port_range: The destination port or range. Integer or
range between 0 and 65535. Asterix '*' can also be used to match all
ports.
:type destination_port_range: str
:param source_address_prefix: Required. The CIDR or source IP range.
Asterix '*' can also be used to match all source IPs. Default tags such as
'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If
this is an ingress rule, specifies where network traffic originates from.
:type source_address_prefix: str
:param destination_address_prefix: Required. The destination address
prefix. CIDR or source IP range. Asterix '*' can also be used to match all
source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and
'Internet' can also be used.
:type destination_address_prefix: str
:param access: Required. The network traffic is allowed or denied.
Possible values are: 'Allow' and 'Deny'. Possible values include: 'Allow',
'Deny'
:type access: str or
~azure.mgmt.network.v2017_03_01.models.SecurityRuleAccess
:param priority: The priority of the rule. The value can be between 100
and 4096. The priority number must be unique for each rule in the
collection. The lower the priority number, the higher the priority of the
rule.
:type priority: int
:param direction: Required. The direction of the rule. The direction
specifies if rule will be evaluated on incoming or outcoming traffic.
Possible values are: 'Inbound' and 'Outbound'. Possible values include:
'Inbound', 'Outbound'
:type direction: str or
~azure.mgmt.network.v2017_03_01.models.SecurityRuleDirection
:param provisioning_state: The provisioning state of the public IP
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param name: The name of the resource that is unique within a resource
group. This name can be used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource
is updated.
:type etag: str
"""
_validation = {
'protocol': {'required': True},
'source_address_prefix': {'required': True},
'destination_address_prefix': {'required': True},
'access': {'required': True},
'direction': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'description': {'key': 'properties.description', 'type': 'str'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'source_port_range': {'key': 'properties.sourcePortRange', 'type': 'str'},
'destination_port_range': {'key': 'properties.destinationPortRange', 'type': 'str'},
'source_address_prefix': {'key': 'properties.sourceAddressPrefix', 'type': 'str'},
'destination_address_prefix': {'key': 'properties.destinationAddressPrefix', 'type': 'str'},
'access': {'key': 'properties.access', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'direction': {'key': 'properties.direction', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, *, protocol, source_address_prefix: str, destination_address_prefix: str, access, direction, id: str=None, description: str=None, source_port_range: str=None, destination_port_range: str=None, priority: int=None, provisioning_state: str=None, name: str=None, etag: str=None, **kwargs) -> None:
super(SecurityRule, self).__init__(id=id, **kwargs)
self.description = description
self.protocol = protocol
self.source_port_range = source_port_range
self.destination_port_range = destination_port_range
self.source_address_prefix = source_address_prefix
self.destination_address_prefix = destination_address_prefix
self.access = access
self.priority = priority
self.direction = direction
self.provisioning_state = provisioning_state
self.name = name
self.etag = etag
| 49.756757 | 316 | 0.668296 |
from .sub_resource import SubResource
class SecurityRule(SubResource):
_validation = {
'protocol': {'required': True},
'source_address_prefix': {'required': True},
'destination_address_prefix': {'required': True},
'access': {'required': True},
'direction': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'description': {'key': 'properties.description', 'type': 'str'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'source_port_range': {'key': 'properties.sourcePortRange', 'type': 'str'},
'destination_port_range': {'key': 'properties.destinationPortRange', 'type': 'str'},
'source_address_prefix': {'key': 'properties.sourceAddressPrefix', 'type': 'str'},
'destination_address_prefix': {'key': 'properties.destinationAddressPrefix', 'type': 'str'},
'access': {'key': 'properties.access', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'direction': {'key': 'properties.direction', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, *, protocol, source_address_prefix: str, destination_address_prefix: str, access, direction, id: str=None, description: str=None, source_port_range: str=None, destination_port_range: str=None, priority: int=None, provisioning_state: str=None, name: str=None, etag: str=None, **kwargs) -> None:
super(SecurityRule, self).__init__(id=id, **kwargs)
self.description = description
self.protocol = protocol
self.source_port_range = source_port_range
self.destination_port_range = destination_port_range
self.source_address_prefix = source_address_prefix
self.destination_address_prefix = destination_address_prefix
self.access = access
self.priority = priority
self.direction = direction
self.provisioning_state = provisioning_state
self.name = name
self.etag = etag
| true | true |
1c46ed5b7d03f873e983faa920d777e35b56c1ae | 3,714 | py | Python | test_tflite.py | kzm4269/keras-yolo3 | 06b2b522213cb901f4a7133b87aab04079e41aff | [
"MIT"
] | null | null | null | test_tflite.py | kzm4269/keras-yolo3 | 06b2b522213cb901f4a7133b87aab04079e41aff | [
"MIT"
] | null | null | null | test_tflite.py | kzm4269/keras-yolo3 | 06b2b522213cb901f4a7133b87aab04079e41aff | [
"MIT"
] | 1 | 2019-09-17T01:28:59.000Z | 2019-09-17T01:28:59.000Z | import argparse
import sys
from pathlib import Path
import numpy as np
import tensorflow as tf
import keras
from PIL import Image
import matplotlib.pyplot as plt
from yolo3.model import yolo_eval
from yolo3.utils import letterbox_image
def predict_keras(model_path):
model = keras.models.load_model(model_path, compile=False)
def predict(image):
assert image.ndim == 3, image.shape
assert image.dtype == np.float32, image.dtype
assert image.ptp() <= 1.0, image.ptp()
return model.predict([image[None]])
return predict
def predict_tflite(model_path):
# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path=model_path)
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
def predict(image):
assert image.ndim == 3, image.shape
assert image.dtype == np.float32, image.dtype
assert image.ptp() <= 1.0, image.ptp()
# Test model on random input data.
print('- predict_tflite: interpreter.set_tensor')
interpreter.set_tensor(input_details[0]['index'], image[None])
print('- predict_tflite: interpreter.invoke')
interpreter.invoke()
# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
print('- predict_tflite: interpreter.get_tensor')
return [interpreter.get_tensor(output_ditail['index']) for output_ditail in output_details]
return predict
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('model', help='model path (.h5 or .tflite)')
parser.add_argument('images', nargs='+', help='image paths')
args = parser.parse_args()
anchors = np.reshape(list(map(int, Path('./model_data/yolo_anchors.txt').read_text().strip().split(','))), (-1, 2))
class_names = Path('./model_data/coco_classes.txt').read_text().strip().splitlines()
predict = {
'h5': predict_keras,
'tflite': predict_tflite,
}[args.model.split('.')[-1]](args.model)
for i, image_path in enumerate(map(Path, args.images)):
print('load:', image_path)
pil_image = Image.open(str(image_path))
input_data = letterbox_image(pil_image, size=(416, 416))
input_data = input_data / np.float32(255.)
image = np.asarray(pil_image)
# image = input_data.copy()
print('predict:', image_path)
output_data = predict(input_data)
print('eval:', image_path)
result = yolo_eval(
[keras.backend.constant(d) for d in output_data],
anchors=anchors,
num_classes=len(class_names),
image_shape=(image.shape[0], image.shape[1]),
score_threshold=0.3,
iou_threshold=0.45,
)
boxes, scores, classes = [keras.backend.eval(t) for t in result]
print('boxes =', boxes)
print('save:', image_path)
from matplotlib.backends.backend_agg import FigureCanvasAgg
fig = FigureCanvasAgg(plt.Figure()).figure
ax = fig.add_subplot(1,1,1)
ax.imshow(image)
for i, (top, left, bottom, right) in enumerate(boxes):
assert top <= bottom and left <= right
ax.add_patch(plt.Rectangle(xy=[left, top], width=right - left, height=bottom - top, fill=False, linewidth=3, color='red'))
fig.savefig(f'out_{args.model.split(".")[-1]}_{i:03d}.png')
if __name__ == '__main__':
_main() | 35.371429 | 134 | 0.631125 | import argparse
import sys
from pathlib import Path
import numpy as np
import tensorflow as tf
import keras
from PIL import Image
import matplotlib.pyplot as plt
from yolo3.model import yolo_eval
from yolo3.utils import letterbox_image
def predict_keras(model_path):
model = keras.models.load_model(model_path, compile=False)
def predict(image):
assert image.ndim == 3, image.shape
assert image.dtype == np.float32, image.dtype
assert image.ptp() <= 1.0, image.ptp()
return model.predict([image[None]])
return predict
def predict_tflite(model_path):
interpreter = tf.lite.Interpreter(model_path=model_path)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
def predict(image):
assert image.ndim == 3, image.shape
assert image.dtype == np.float32, image.dtype
assert image.ptp() <= 1.0, image.ptp()
print('- predict_tflite: interpreter.set_tensor')
interpreter.set_tensor(input_details[0]['index'], image[None])
print('- predict_tflite: interpreter.invoke')
interpreter.invoke()
print('- predict_tflite: interpreter.get_tensor')
return [interpreter.get_tensor(output_ditail['index']) for output_ditail in output_details]
return predict
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('model', help='model path (.h5 or .tflite)')
parser.add_argument('images', nargs='+', help='image paths')
args = parser.parse_args()
anchors = np.reshape(list(map(int, Path('./model_data/yolo_anchors.txt').read_text().strip().split(','))), (-1, 2))
class_names = Path('./model_data/coco_classes.txt').read_text().strip().splitlines()
predict = {
'h5': predict_keras,
'tflite': predict_tflite,
}[args.model.split('.')[-1]](args.model)
for i, image_path in enumerate(map(Path, args.images)):
print('load:', image_path)
pil_image = Image.open(str(image_path))
input_data = letterbox_image(pil_image, size=(416, 416))
input_data = input_data / np.float32(255.)
image = np.asarray(pil_image)
print('predict:', image_path)
output_data = predict(input_data)
print('eval:', image_path)
result = yolo_eval(
[keras.backend.constant(d) for d in output_data],
anchors=anchors,
num_classes=len(class_names),
image_shape=(image.shape[0], image.shape[1]),
score_threshold=0.3,
iou_threshold=0.45,
)
boxes, scores, classes = [keras.backend.eval(t) for t in result]
print('boxes =', boxes)
print('save:', image_path)
from matplotlib.backends.backend_agg import FigureCanvasAgg
fig = FigureCanvasAgg(plt.Figure()).figure
ax = fig.add_subplot(1,1,1)
ax.imshow(image)
for i, (top, left, bottom, right) in enumerate(boxes):
assert top <= bottom and left <= right
ax.add_patch(plt.Rectangle(xy=[left, top], width=right - left, height=bottom - top, fill=False, linewidth=3, color='red'))
fig.savefig(f'out_{args.model.split(".")[-1]}_{i:03d}.png')
if __name__ == '__main__':
_main() | true | true |
1c46edebef8140280b53e681b1f63cdbf8683804 | 15,791 | py | Python | tests/support/unit.py | byteskeptical/salt | 637fe0b04f38b2274191b005d73b3c6707d7f400 | [
"Apache-2.0"
] | 5 | 2018-05-01T20:51:14.000Z | 2021-11-09T05:43:00.000Z | tests/support/unit.py | byteskeptical/salt | 637fe0b04f38b2274191b005d73b3c6707d7f400 | [
"Apache-2.0"
] | 12 | 2015-04-15T22:17:42.000Z | 2016-03-22T08:46:27.000Z | tests/support/unit.py | byteskeptical/salt | 637fe0b04f38b2274191b005d73b3c6707d7f400 | [
"Apache-2.0"
] | 7 | 2017-09-29T18:49:53.000Z | 2021-11-09T05:42:49.000Z | # -*- coding: utf-8 -*-
'''
:codeauthor: Pedro Algarvio (pedro@algarvio.me)
============================
Unittest Compatibility Layer
============================
Compatibility layer to use :mod:`unittest <python2:unittest>` under Python
2.7 or `unittest2`_ under Python 2.6 without having to worry about which is
in use.
.. attention::
Please refer to Python's :mod:`unittest <python2:unittest>`
documentation as the ultimate source of information, this is just a
compatibility layer.
.. _`unittest2`: https://pypi.python.org/pypi/unittest2
'''
# pylint: disable=unused-import,blacklisted-module,deprecated-method
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import logging
from unittest import (
TestLoader as _TestLoader,
TextTestRunner as _TextTestRunner,
TestCase as _TestCase,
expectedFailure,
TestSuite as _TestSuite,
skip,
skipIf,
TestResult,
TextTestResult as _TextTestResult
)
from unittest.case import _id, SkipTest
from salt.ext import six
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
# Set SHOW_PROC to True to show
# process details when running in verbose mode
# i.e. [CPU:15.1%|MEM:48.3%|Z:0]
SHOW_PROC = 'NO_SHOW_PROC' not in os.environ
LOREM_IPSUM = '''\
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget urna a arcu lacinia sagittis.
Sed scelerisque, lacus eget malesuada vestibulum, justo diam facilisis tortor, in sodales dolor
nibh eu urna. Aliquam iaculis massa risus, sed elementum risus accumsan id. Suspendisse mattis,
metus sed lacinia dictum, leo orci dapibus sapien, at porttitor sapien nulla ac velit.
Duis ac cursus leo, non varius metus. Sed laoreet felis magna, vel tempor diam malesuada nec.
Quisque cursus odio tortor. In consequat augue nisl, eget lacinia odio vestibulum eget.
Donec venenatis elementum arcu at rhoncus. Nunc pharetra erat in lacinia convallis. Ut condimentum
eu mauris sit amet convallis. Morbi vulputate vel odio non laoreet. Nullam in suscipit tellus.
Sed quis posuere urna.'''
class TestSuite(_TestSuite):
def _handleClassSetUp(self, test, result):
previousClass = getattr(result, '_previousTestClass', None)
currentClass = test.__class__
if currentClass == previousClass or getattr(currentClass, 'setUpClass', None) is None:
return super(TestSuite, self)._handleClassSetUp(test, result)
# Store a reference to all class attributes before running the setUpClass method
initial_class_attributes = dir(test.__class__)
ret = super(TestSuite, self)._handleClassSetUp(test, result)
# Store the difference in in a variable in order to check later if they were deleted
test.__class__._prerun_class_attributes = [
attr for attr in dir(test.__class__) if attr not in initial_class_attributes]
return ret
def _tearDownPreviousClass(self, test, result):
# Run any tearDownClass code defined
super(TestSuite, self)._tearDownPreviousClass(test, result)
previousClass = getattr(result, '_previousTestClass', None)
currentClass = test.__class__
if currentClass == previousClass:
return
# See if the previous class attributes have been cleaned
if previousClass and getattr(previousClass, 'tearDownClass', None):
prerun_class_attributes = getattr(previousClass, '_prerun_class_attributes', None)
if prerun_class_attributes is not None:
previousClass._prerun_class_attributes = None
del previousClass._prerun_class_attributes
for attr in prerun_class_attributes:
if hasattr(previousClass, attr):
attr_value = getattr(previousClass, attr, None)
if attr_value is None:
continue
if isinstance(attr_value, (bool,) + six.string_types + six.integer_types):
setattr(previousClass, attr, None)
continue
log.warning('Deleting extra class attribute after test run: %s.%s(%s). '
'Please consider using \'del self.%s\' on the test class '
'\'tearDownClass()\' method', previousClass.__name__, attr,
str(getattr(previousClass, attr))[:100], attr)
delattr(previousClass, attr)
class TestLoader(_TestLoader):
# We're just subclassing to make sure tha tour TestSuite class is the one used
suiteClass = TestSuite
class TestCase(_TestCase):
# pylint: disable=expected-an-indented-block-comment,too-many-leading-hastag-for-block-comment
## Commented out because it may be causing tests to hang
## at the end of the run
#
# _cwd = os.getcwd()
# _chdir_counter = 0
# @classmethod
# def tearDownClass(cls):
# '''
# Overriden method for tearing down all classes in salttesting
#
# This hard-resets the environment between test classes
# '''
# # Compare where we are now compared to where we were when we began this family of tests
# if not cls._cwd == os.getcwd() and cls._chdir_counter > 0:
# os.chdir(cls._cwd)
# print('\nWARNING: A misbehaving test has modified the working directory!\nThe test suite has reset the working directory '
# 'on tearDown() to {0}\n'.format(cls._cwd))
# cls._chdir_counter += 1
# pylint: enable=expected-an-indented-block-comment,too-many-leading-hastag-for-block-comment
def run(self, result=None):
self._prerun_instance_attributes = dir(self)
self.maxDiff = None
outcome = super(TestCase, self).run(result=result)
for attr in dir(self):
if attr == '_prerun_instance_attributes':
continue
if attr in getattr(self.__class__, '_prerun_class_attributes', ()):
continue
if attr not in self._prerun_instance_attributes:
attr_value = getattr(self, attr, None)
if attr_value is None:
continue
if isinstance(attr_value, (bool,) + six.string_types + six.integer_types):
setattr(self, attr, None)
continue
log.warning('Deleting extra class attribute after test run: %s.%s(%s). '
'Please consider using \'del self.%s\' on the test case '
'\'tearDown()\' method', self.__class__.__name__, attr,
getattr(self, attr), attr)
delattr(self, attr)
self._prerun_instance_attributes = None
del self._prerun_instance_attributes
return outcome
def shortDescription(self):
desc = _TestCase.shortDescription(self)
if HAS_PSUTIL and SHOW_PROC:
show_zombie_processes = 'SHOW_PROC_ZOMBIES' in os.environ
proc_info = '[CPU:{0}%|MEM:{1}%'.format(psutil.cpu_percent(),
psutil.virtual_memory().percent)
if show_zombie_processes:
found_zombies = 0
try:
for proc in psutil.process_iter():
if proc.status == psutil.STATUS_ZOMBIE:
found_zombies += 1
except Exception:
pass
proc_info += '|Z:{0}'.format(found_zombies)
proc_info += '] {short_desc}'.format(short_desc=desc if desc else '')
return proc_info
else:
return _TestCase.shortDescription(self)
def assertEquals(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assertEquals', 'assertEqual')
)
# return _TestCase.assertEquals(self, *args, **kwargs)
def assertNotEquals(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assertNotEquals', 'assertNotEqual')
)
# return _TestCase.assertNotEquals(self, *args, **kwargs)
def assert_(self, *args, **kwargs):
# The unittest2 library uses this deprecated method, we can't raise
# the exception.
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assert_', 'assertTrue')
)
# return _TestCase.assert_(self, *args, **kwargs)
def assertAlmostEquals(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assertAlmostEquals', 'assertAlmostEqual')
)
# return _TestCase.assertAlmostEquals(self, *args, **kwargs)
def assertNotAlmostEquals(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assertNotAlmostEquals', 'assertNotAlmostEqual')
)
# return _TestCase.assertNotAlmostEquals(self, *args, **kwargs)
def repack_state_returns(self, state_ret):
'''
Accepts a state return dict and returns it back with the top level key
names rewritten such that the ID declaration is the key instead of the
State's unique tag. For example: 'foo' instead of
'file_|-foo_|-/etc/foo.conf|-managed'
This makes it easier to work with state returns when crafting asserts
after running states.
'''
assert isinstance(state_ret, dict), state_ret
return {x.split('_|-')[1]: y for x, y in six.iteritems(state_ret)}
def failUnlessEqual(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failUnlessEqual', 'assertEqual')
)
# return _TestCase.failUnlessEqual(self, *args, **kwargs)
def failIfEqual(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failIfEqual', 'assertNotEqual')
)
# return _TestCase.failIfEqual(self, *args, **kwargs)
def failUnless(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failUnless', 'assertTrue')
)
# return _TestCase.failUnless(self, *args, **kwargs)
def failIf(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failIf', 'assertFalse')
)
# return _TestCase.failIf(self, *args, **kwargs)
def failUnlessRaises(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failUnlessRaises', 'assertRaises')
)
# return _TestCase.failUnlessRaises(self, *args, **kwargs)
def failUnlessAlmostEqual(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failUnlessAlmostEqual', 'assertAlmostEqual')
)
# return _TestCase.failUnlessAlmostEqual(self, *args, **kwargs)
def failIfAlmostEqual(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failIfAlmostEqual', 'assertNotAlmostEqual')
)
# return _TestCase.failIfAlmostEqual(self, *args, **kwargs)
@staticmethod
def assert_called_once(mock):
'''
mock.assert_called_once only exists in PY3 in 3.6 and newer
'''
try:
mock.assert_called_once()
except AttributeError:
log.warning('assert_called_once invoked, but not available')
if six.PY2:
def assertRegexpMatches(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function will be deprecated in python 3. Please start '
'using {1}() instead.'.format(
'assertRegexpMatches',
'assertRegex'
)
)
def assertRegex(self, text, regex, msg=None):
# In python 2, alias to the future python 3 function
return _TestCase.assertRegexpMatches(self, text, regex, msg=msg)
def assertNotRegexpMatches(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function will be deprecated in python 3. Please start '
'using {1}() instead.'.format(
'assertNotRegexpMatches',
'assertNotRegex'
)
)
def assertNotRegex(self, text, regex, msg=None):
# In python 2, alias to the future python 3 function
return _TestCase.assertNotRegexpMatches(self, text, regex, msg=msg)
def assertRaisesRegexp(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function will be deprecated in python 3. Please start '
'using {1}() instead.'.format(
'assertRaisesRegexp',
'assertRaisesRegex'
)
)
def assertRaisesRegex(self, exception, regexp, *args, **kwds):
# In python 2, alias to the future python 3 function
return _TestCase.assertRaisesRegexp(self, exception, regexp, *args, **kwds)
else:
def assertRegexpMatches(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format(
'assertRegexpMatches',
'assertRegex'
)
)
def assertNotRegexpMatches(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format(
'assertNotRegexpMatches',
'assertNotRegex'
)
)
def assertRaisesRegexp(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format(
'assertRaisesRegexp',
'assertRaisesRegex'
)
)
class TextTestResult(_TextTestResult):
'''
Custom TestResult class whith logs the start and the end of a test
'''
def startTest(self, test):
log.debug('>>>>> START >>>>> %s', test.id())
return super(TextTestResult, self).startTest(test)
def stopTest(self, test):
log.debug('<<<<< END <<<<<<< %s', test.id())
return super(TextTestResult, self).stopTest(test)
class TextTestRunner(_TextTestRunner):
'''
Custom Text tests runner to log the start and the end of a test case
'''
resultclass = TextTestResult
__all__ = [
'TestLoader',
'TextTestRunner',
'TestCase',
'expectedFailure',
'TestSuite',
'skipIf',
'TestResult'
]
| 40.283163 | 135 | 0.604142 |
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import logging
from unittest import (
TestLoader as _TestLoader,
TextTestRunner as _TextTestRunner,
TestCase as _TestCase,
expectedFailure,
TestSuite as _TestSuite,
skip,
skipIf,
TestResult,
TextTestResult as _TextTestResult
)
from unittest.case import _id, SkipTest
from salt.ext import six
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
SHOW_PROC = 'NO_SHOW_PROC' not in os.environ
LOREM_IPSUM = '''\
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget urna a arcu lacinia sagittis.
Sed scelerisque, lacus eget malesuada vestibulum, justo diam facilisis tortor, in sodales dolor
nibh eu urna. Aliquam iaculis massa risus, sed elementum risus accumsan id. Suspendisse mattis,
metus sed lacinia dictum, leo orci dapibus sapien, at porttitor sapien nulla ac velit.
Duis ac cursus leo, non varius metus. Sed laoreet felis magna, vel tempor diam malesuada nec.
Quisque cursus odio tortor. In consequat augue nisl, eget lacinia odio vestibulum eget.
Donec venenatis elementum arcu at rhoncus. Nunc pharetra erat in lacinia convallis. Ut condimentum
eu mauris sit amet convallis. Morbi vulputate vel odio non laoreet. Nullam in suscipit tellus.
Sed quis posuere urna.'''
class TestSuite(_TestSuite):
def _handleClassSetUp(self, test, result):
previousClass = getattr(result, '_previousTestClass', None)
currentClass = test.__class__
if currentClass == previousClass or getattr(currentClass, 'setUpClass', None) is None:
return super(TestSuite, self)._handleClassSetUp(test, result)
initial_class_attributes = dir(test.__class__)
ret = super(TestSuite, self)._handleClassSetUp(test, result)
test.__class__._prerun_class_attributes = [
attr for attr in dir(test.__class__) if attr not in initial_class_attributes]
return ret
def _tearDownPreviousClass(self, test, result):
super(TestSuite, self)._tearDownPreviousClass(test, result)
previousClass = getattr(result, '_previousTestClass', None)
currentClass = test.__class__
if currentClass == previousClass:
return
if previousClass and getattr(previousClass, 'tearDownClass', None):
prerun_class_attributes = getattr(previousClass, '_prerun_class_attributes', None)
if prerun_class_attributes is not None:
previousClass._prerun_class_attributes = None
del previousClass._prerun_class_attributes
for attr in prerun_class_attributes:
if hasattr(previousClass, attr):
attr_value = getattr(previousClass, attr, None)
if attr_value is None:
continue
if isinstance(attr_value, (bool,) + six.string_types + six.integer_types):
setattr(previousClass, attr, None)
continue
log.warning('Deleting extra class attribute after test run: %s.%s(%s). '
'Please consider using \'del self.%s\' on the test class '
'\'tearDownClass()\' method', previousClass.__name__, attr,
str(getattr(previousClass, attr))[:100], attr)
delattr(previousClass, attr)
class TestLoader(_TestLoader):
suiteClass = TestSuite
class TestCase(_TestCase):
# pylint: disable=expected-an-indented-block-comment,too-many-leading-hastag-for-block-comment
## Commented out because it may be causing tests to hang
## at the end of the run
#
# _cwd = os.getcwd()
# _chdir_counter = 0
# @classmethod
# def tearDownClass(cls):
# '''
# Overriden method for tearing down all classes in salttesting
#
# This hard-resets the environment between test classes
# '''
# # Compare where we are now compared to where we were when we began this family of tests
# if not cls._cwd == os.getcwd() and cls._chdir_counter > 0:
# os.chdir(cls._cwd)
# print('\nWARNING: A misbehaving test has modified the working directory!\nThe test suite has reset the working directory '
# 'on tearDown() to {0}\n'.format(cls._cwd))
# cls._chdir_counter += 1
# pylint: enable=expected-an-indented-block-comment,too-many-leading-hastag-for-block-comment
def run(self, result=None):
self._prerun_instance_attributes = dir(self)
self.maxDiff = None
outcome = super(TestCase, self).run(result=result)
for attr in dir(self):
if attr == '_prerun_instance_attributes':
continue
if attr in getattr(self.__class__, '_prerun_class_attributes', ()):
continue
if attr not in self._prerun_instance_attributes:
attr_value = getattr(self, attr, None)
if attr_value is None:
continue
if isinstance(attr_value, (bool,) + six.string_types + six.integer_types):
setattr(self, attr, None)
continue
log.warning('Deleting extra class attribute after test run: %s.%s(%s). '
'Please consider using \'del self.%s\' on the test case '
'\'tearDown()\' method', self.__class__.__name__, attr,
getattr(self, attr), attr)
delattr(self, attr)
self._prerun_instance_attributes = None
del self._prerun_instance_attributes
return outcome
def shortDescription(self):
desc = _TestCase.shortDescription(self)
if HAS_PSUTIL and SHOW_PROC:
show_zombie_processes = 'SHOW_PROC_ZOMBIES' in os.environ
proc_info = '[CPU:{0}%|MEM:{1}%'.format(psutil.cpu_percent(),
psutil.virtual_memory().percent)
if show_zombie_processes:
found_zombies = 0
try:
for proc in psutil.process_iter():
if proc.status == psutil.STATUS_ZOMBIE:
found_zombies += 1
except Exception:
pass
proc_info += '|Z:{0}'.format(found_zombies)
proc_info += '] {short_desc}'.format(short_desc=desc if desc else '')
return proc_info
else:
return _TestCase.shortDescription(self)
def assertEquals(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assertEquals', 'assertEqual')
)
# return _TestCase.assertEquals(self, *args, **kwargs)
def assertNotEquals(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assertNotEquals', 'assertNotEqual')
)
# return _TestCase.assertNotEquals(self, *args, **kwargs)
def assert_(self, *args, **kwargs):
# The unittest2 library uses this deprecated method, we can't raise
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assert_', 'assertTrue')
)
def assertAlmostEquals(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assertAlmostEquals', 'assertAlmostEqual')
)
def assertNotAlmostEquals(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('assertNotAlmostEquals', 'assertNotAlmostEqual')
)
def repack_state_returns(self, state_ret):
assert isinstance(state_ret, dict), state_ret
return {x.split('_|-')[1]: y for x, y in six.iteritems(state_ret)}
def failUnlessEqual(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failUnlessEqual', 'assertEqual')
)
def failIfEqual(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failIfEqual', 'assertNotEqual')
)
def failUnless(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failUnless', 'assertTrue')
)
def failIf(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failIf', 'assertFalse')
)
def failUnlessRaises(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failUnlessRaises', 'assertRaises')
)
def failUnlessAlmostEqual(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failUnlessAlmostEqual', 'assertAlmostEqual')
)
def failIfAlmostEqual(self, *args, **kwargs):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format('failIfAlmostEqual', 'assertNotAlmostEqual')
)
@staticmethod
def assert_called_once(mock):
try:
mock.assert_called_once()
except AttributeError:
log.warning('assert_called_once invoked, but not available')
if six.PY2:
def assertRegexpMatches(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function will be deprecated in python 3. Please start '
'using {1}() instead.'.format(
'assertRegexpMatches',
'assertRegex'
)
)
def assertRegex(self, text, regex, msg=None):
return _TestCase.assertRegexpMatches(self, text, regex, msg=msg)
def assertNotRegexpMatches(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function will be deprecated in python 3. Please start '
'using {1}() instead.'.format(
'assertNotRegexpMatches',
'assertNotRegex'
)
)
def assertNotRegex(self, text, regex, msg=None):
return _TestCase.assertNotRegexpMatches(self, text, regex, msg=msg)
def assertRaisesRegexp(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function will be deprecated in python 3. Please start '
'using {1}() instead.'.format(
'assertRaisesRegexp',
'assertRaisesRegex'
)
)
def assertRaisesRegex(self, exception, regexp, *args, **kwds):
return _TestCase.assertRaisesRegexp(self, exception, regexp, *args, **kwds)
else:
def assertRegexpMatches(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format(
'assertRegexpMatches',
'assertRegex'
)
)
def assertNotRegexpMatches(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format(
'assertNotRegexpMatches',
'assertNotRegex'
)
)
def assertRaisesRegexp(self, *args, **kwds):
raise DeprecationWarning(
'The {0}() function is deprecated. Please start using {1}() '
'instead.'.format(
'assertRaisesRegexp',
'assertRaisesRegex'
)
)
class TextTestResult(_TextTestResult):
def startTest(self, test):
log.debug('>>>>> START >>>>> %s', test.id())
return super(TextTestResult, self).startTest(test)
def stopTest(self, test):
log.debug('<<<<< END <<<<<<< %s', test.id())
return super(TextTestResult, self).stopTest(test)
class TextTestRunner(_TextTestRunner):
resultclass = TextTestResult
__all__ = [
'TestLoader',
'TextTestRunner',
'TestCase',
'expectedFailure',
'TestSuite',
'skipIf',
'TestResult'
]
| true | true |
1c46efa6f932098b01ac8f6ff7f969b913d9d383 | 1,307 | py | Python | demo.py | foamliu/Image-Matching | 3213a8a574fa7bcc476d3de1c7370c268bf817a7 | [
"MIT"
] | 12 | 2019-04-12T06:56:59.000Z | 2020-05-03T00:47:33.000Z | demo.py | foamliu/Image-Matching | 3213a8a574fa7bcc476d3de1c7370c268bf817a7 | [
"MIT"
] | 1 | 2019-05-15T02:05:46.000Z | 2019-05-17T17:57:34.000Z | demo.py | foamliu/Image-Matching | 3213a8a574fa7bcc476d3de1c7370c268bf817a7 | [
"MIT"
] | 2 | 2019-05-28T07:03:45.000Z | 2020-03-20T09:49:15.000Z | import math
import cv2 as cv
import numpy as np
import torch
from PIL import Image
from torchvision import transforms
from models import ResNetMatchModel
def get_image(file):
img = cv.imread(file)
img = img[..., ::-1] # RGB
img = Image.fromarray(img, 'RGB') # RGB
img = transformer(img)
img = img.to(device)
return img
def get_feature(model, file):
img = get_image(file)
imgs = img.unsqueeze(dim=0)
with torch.no_grad():
output = model(imgs)
feature = output[0].cpu().numpy()
return feature / np.linalg.norm(feature)
if __name__ == "__main__":
device = torch.device('cpu')
threshold = 21.07971786746929
filename = 'image_matching.pt'
model = ResNetMatchModel()
model.load_state_dict(torch.load(filename))
model = model.to(device)
model.eval()
transformer = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
x0 = get_feature(model, '0.jpg')
x1 = get_feature(model, '6.jpg')
cosine = np.dot(x0, x1)
cosine = np.clip(cosine, -1, 1)
theta = math.acos(cosine)
theta = theta * 180 / math.pi
print(theta)
print(theta <= threshold)
| 22.929825 | 74 | 0.635042 | import math
import cv2 as cv
import numpy as np
import torch
from PIL import Image
from torchvision import transforms
from models import ResNetMatchModel
def get_image(file):
img = cv.imread(file)
img = img[..., ::-1]
img = Image.fromarray(img, 'RGB')
img = transformer(img)
img = img.to(device)
return img
def get_feature(model, file):
img = get_image(file)
imgs = img.unsqueeze(dim=0)
with torch.no_grad():
output = model(imgs)
feature = output[0].cpu().numpy()
return feature / np.linalg.norm(feature)
if __name__ == "__main__":
device = torch.device('cpu')
threshold = 21.07971786746929
filename = 'image_matching.pt'
model = ResNetMatchModel()
model.load_state_dict(torch.load(filename))
model = model.to(device)
model.eval()
transformer = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
x0 = get_feature(model, '0.jpg')
x1 = get_feature(model, '6.jpg')
cosine = np.dot(x0, x1)
cosine = np.clip(cosine, -1, 1)
theta = math.acos(cosine)
theta = theta * 180 / math.pi
print(theta)
print(theta <= threshold)
| true | true |
1c46efb1d180176edecbf36aaf6099e81619e829 | 4,855 | py | Python | torchflare/metrics/fbeta_meter.py | glenn-jocher/torchflare | 3c55b5a0761f2e85dd6da95767c6ec03f0f5baad | [
"Apache-2.0"
] | 1 | 2021-06-12T12:39:04.000Z | 2021-06-12T12:39:04.000Z | torchflare/metrics/fbeta_meter.py | weidao-Shi/torchflare | 3c55b5a0761f2e85dd6da95767c6ec03f0f5baad | [
"Apache-2.0"
] | null | null | null | torchflare/metrics/fbeta_meter.py | weidao-Shi/torchflare | 3c55b5a0761f2e85dd6da95767c6ec03f0f5baad | [
"Apache-2.0"
] | null | null | null | """Implements FBeta and F1-score."""
import torch
from torchflare.metrics.meters import MetricMeter, _BaseInputHandler
class FBeta(_BaseInputHandler, MetricMeter):
"""Computes Fbeta Score.
Supports binary,multiclass and multilabel cases.
"""
def __init__(
self,
beta: float,
num_classes: int,
threshold: float = 0.5,
average: str = "macro",
multilabel: bool = False,
):
"""Constructor method for Fbeta score.
Args:
num_classes : The number of num_classes(For binary case , use out_features : 1)
threshold: The value of threshold for masking. Input is raw logits.
average : One of "micro" or "macro"
beta : weight of precision in harmonic mean.
multilabel: Whether problem is multilabel or not.
Note:
In case of binary classification, set num_classes = 1
"""
super(FBeta, self).__init__(
num_classes=num_classes,
multilabel=multilabel,
threshold=threshold,
average=average,
)
self.beta = beta
self.eps = 1e-20
self._outputs = None
self._targets = None
self.reset()
def handle(self) -> str:
"""Method to get the class name.
Returns:
The class name
"""
return self.__class__.__name__.lower()
def accumulate(self, outputs: torch.Tensor, targets: torch.Tensor):
"""Method to accumulate the outputs and targets.
Args:
outputs : raw logits from the network.
targets : Ground truth targets
"""
outputs, targets = self.detach_tensor(outputs), self.detach_tensor(targets)
self._outputs.append(outputs)
self._targets.append(targets)
def reset(self):
"""Resets the accumulation lists."""
self._outputs = []
self._targets = []
@property
def value(self) -> torch.Tensor:
"""Computes the FBeta Score.
Returns:
The computed Fbeta score.
"""
outputs = torch.cat(self._outputs)
targets = torch.cat(self._targets)
tp, fp, tn, fn = self.compute_stats(outputs=outputs, targets=targets)
precision = tp / (tp + fp + self.eps)
recall = tp / (tp + fn + self.eps)
numerator = (1 + self.beta ** 2) * precision * recall
denominator = self.beta ** 2 * precision + recall
fbeta = self.reduce(numerator=numerator, denominator=denominator)
return fbeta
class F1Score(_BaseInputHandler, MetricMeter):
"""Computes F1 Score.
Supports binary,multiclass and multilabel cases.
"""
def __init__(
self,
num_classes: int,
threshold: float = 0.5,
multilabel: bool = False,
average: str = "macro",
):
"""Constructor method for F1-score.
Args:
num_classes : The number of num_classes(For binary case , use out_features : 1)
threshold: The value of threshold for masking. Input is raw logits.
average : One of "micro" or "macro".
multilabel: Whether the problem is multilabel or not.
"""
super(F1Score, self).__init__(
num_classes=num_classes,
multilabel=multilabel,
threshold=threshold,
average=average,
)
self.eps = 1e-20
self._outputs = None
self._targets = None
self.reset()
def handle(self) -> str:
"""Method to get the class name.
Returns:
The class name
"""
return self.__class__.__name__.lower()
@property
def value(self) -> torch.Tensor:
"""Value of FBeta Score.
Returns:
The computed F1-score
"""
outputs = torch.cat(self._outputs)
targets = torch.cat(self._targets)
tp, fp, tn, fn = self.compute_stats(outputs=outputs, targets=targets)
precision = tp / (tp + fp + self.eps)
recall = tp / (tp + fn + self.eps)
numerator = 2 * precision * recall
denominator = precision + recall
f1 = self.reduce(numerator=numerator, denominator=denominator)
return f1
def accumulate(self, outputs: torch.Tensor, targets: torch.Tensor):
"""Method to accumulate the outputs and targets.
Args:
outputs : raw logits from the network.
targets : Ground truth targets
"""
outputs, targets = self.detach_tensor(outputs), self.detach_tensor(targets)
self._outputs.append(outputs)
self._targets.append(targets)
def reset(self):
"""Resets the accumulation lists."""
self._outputs = []
self._targets = []
__all__ = ["FBeta", "F1Score"]
| 27.429379 | 91 | 0.581462 | import torch
from torchflare.metrics.meters import MetricMeter, _BaseInputHandler
class FBeta(_BaseInputHandler, MetricMeter):
def __init__(
self,
beta: float,
num_classes: int,
threshold: float = 0.5,
average: str = "macro",
multilabel: bool = False,
):
super(FBeta, self).__init__(
num_classes=num_classes,
multilabel=multilabel,
threshold=threshold,
average=average,
)
self.beta = beta
self.eps = 1e-20
self._outputs = None
self._targets = None
self.reset()
def handle(self) -> str:
return self.__class__.__name__.lower()
def accumulate(self, outputs: torch.Tensor, targets: torch.Tensor):
outputs, targets = self.detach_tensor(outputs), self.detach_tensor(targets)
self._outputs.append(outputs)
self._targets.append(targets)
def reset(self):
self._outputs = []
self._targets = []
@property
def value(self) -> torch.Tensor:
outputs = torch.cat(self._outputs)
targets = torch.cat(self._targets)
tp, fp, tn, fn = self.compute_stats(outputs=outputs, targets=targets)
precision = tp / (tp + fp + self.eps)
recall = tp / (tp + fn + self.eps)
numerator = (1 + self.beta ** 2) * precision * recall
denominator = self.beta ** 2 * precision + recall
fbeta = self.reduce(numerator=numerator, denominator=denominator)
return fbeta
class F1Score(_BaseInputHandler, MetricMeter):
def __init__(
self,
num_classes: int,
threshold: float = 0.5,
multilabel: bool = False,
average: str = "macro",
):
super(F1Score, self).__init__(
num_classes=num_classes,
multilabel=multilabel,
threshold=threshold,
average=average,
)
self.eps = 1e-20
self._outputs = None
self._targets = None
self.reset()
def handle(self) -> str:
return self.__class__.__name__.lower()
@property
def value(self) -> torch.Tensor:
outputs = torch.cat(self._outputs)
targets = torch.cat(self._targets)
tp, fp, tn, fn = self.compute_stats(outputs=outputs, targets=targets)
precision = tp / (tp + fp + self.eps)
recall = tp / (tp + fn + self.eps)
numerator = 2 * precision * recall
denominator = precision + recall
f1 = self.reduce(numerator=numerator, denominator=denominator)
return f1
def accumulate(self, outputs: torch.Tensor, targets: torch.Tensor):
outputs, targets = self.detach_tensor(outputs), self.detach_tensor(targets)
self._outputs.append(outputs)
self._targets.append(targets)
def reset(self):
self._outputs = []
self._targets = []
__all__ = ["FBeta", "F1Score"]
| true | true |
1c46f06b69ffba498e3069692b46574d299220a8 | 5,492 | py | Python | tests/data/embeddings_test.py | richarajpal/deep_qa | d918335a1bed71b9cfccf1d5743321cee9c61952 | [
"Apache-2.0"
] | 459 | 2017-02-08T13:40:17.000Z | 2021-12-12T12:57:48.000Z | tests/data/embeddings_test.py | richarajpal/deep_qa | d918335a1bed71b9cfccf1d5743321cee9c61952 | [
"Apache-2.0"
] | 176 | 2017-01-26T01:19:41.000Z | 2018-04-22T19:16:01.000Z | tests/data/embeddings_test.py | richarajpal/deep_qa | d918335a1bed71b9cfccf1d5743321cee9c61952 | [
"Apache-2.0"
] | 154 | 2017-01-26T01:00:30.000Z | 2021-02-05T10:44:42.000Z | # pylint: disable=no-self-use,invalid-name
import gzip
import numpy
import pytest
from deep_qa.common.checks import ConfigurationError
from deep_qa.data.data_indexer import DataIndexer
from deep_qa.data.embeddings import PretrainedEmbeddings
from deep_qa.models.text_classification import ClassificationModel
from deep_qa.testing.test_case import DeepQaTestCase
class TestPretrainedEmbeddings(DeepQaTestCase):
# pylint: disable=protected-access
def test_get_embedding_layer_uses_correct_embedding_dim(self):
data_indexer = DataIndexer()
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word1 1.0 2.3 -1.0\n".encode('utf-8'))
embeddings_file.write("word2 0.1 0.4 -4.0\n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
assert embedding_layer.output_dim == 3
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word1 1.0 2.3 -1.0 3.1\n".encode('utf-8'))
embeddings_file.write("word2 0.1 0.4 -4.0 -1.2\n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
assert embedding_layer.output_dim == 4
def test_get_embedding_layer_crashes_when_embedding_dim_is_one(self):
data_indexer = DataIndexer()
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("dimensionality 3\n".encode('utf-8'))
embeddings_file.write("word1 1.0 2.3 -1.0\n".encode('utf-8'))
embeddings_file.write("word2 0.1 0.4 -4.0\n".encode('utf-8'))
with pytest.raises(Exception):
PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
def test_get_embedding_layer_skips_inconsistent_lines(self):
data_indexer = DataIndexer()
data_indexer.add_word_to_index("word1")
data_indexer.add_word_to_index("word2")
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word1 1.0 2.3 -1.0\n".encode('utf-8'))
embeddings_file.write("word2 0.1 0.4 \n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
print(embedding_layer.weights)
word_vector = embedding_layer._initial_weights[0][data_indexer.get_word_index("word2")]
assert not numpy.allclose(word_vector[:2], numpy.asarray([0.1, 0.4]))
def test_get_embedding_layer_actually_initializes_word_vectors_correctly(self):
data_indexer = DataIndexer()
data_indexer.add_word_to_index("word")
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word 1.0 2.3 -1.0\n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
word_vector = embedding_layer._initial_weights[0][data_indexer.get_word_index("word")]
assert numpy.allclose(word_vector, numpy.asarray([1.0, 2.3, -1.0]))
def test_get_embedding_layer_initializes_unseen_words_randomly_not_zero(self):
data_indexer = DataIndexer()
data_indexer.add_word_to_index("word2")
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word 1.0 2.3 -1.0\n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
word_vector = embedding_layer._initial_weights[0][data_indexer.get_word_index("word2")]
assert not numpy.allclose(word_vector, numpy.asarray([0.0, 0.0, 0.0]))
def test_embedding_will_not_project_random_embeddings(self):
self.write_pretrained_vector_files()
self.write_true_false_model_files()
with pytest.raises(ConfigurationError):
args = {
"embeddings": {
"words": {
"dimension": 5,
"project": True,
"fine_tune": True,
"dropout": 0.2
}
}
}
model = self.get_model(ClassificationModel, args)
model.train()
def test_projection_dim_not_equal_to_pretrained_dim_with_no_projection_flag_raises_error(self):
self.write_pretrained_vector_files()
self.write_true_false_model_files()
with pytest.raises(ConfigurationError):
args = {
"embeddings": {
"words": {
"dimension": 13,
"pretrained_file": self.PRETRAINED_VECTORS_GZIP,
"project": False,
"fine_tune": False,
"dropout": 0.2
}
}
}
model = self.get_model(ClassificationModel, args)
model.train()
| 51.327103 | 101 | 0.64512 |
import gzip
import numpy
import pytest
from deep_qa.common.checks import ConfigurationError
from deep_qa.data.data_indexer import DataIndexer
from deep_qa.data.embeddings import PretrainedEmbeddings
from deep_qa.models.text_classification import ClassificationModel
from deep_qa.testing.test_case import DeepQaTestCase
class TestPretrainedEmbeddings(DeepQaTestCase):
def test_get_embedding_layer_uses_correct_embedding_dim(self):
data_indexer = DataIndexer()
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word1 1.0 2.3 -1.0\n".encode('utf-8'))
embeddings_file.write("word2 0.1 0.4 -4.0\n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
assert embedding_layer.output_dim == 3
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word1 1.0 2.3 -1.0 3.1\n".encode('utf-8'))
embeddings_file.write("word2 0.1 0.4 -4.0 -1.2\n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
assert embedding_layer.output_dim == 4
def test_get_embedding_layer_crashes_when_embedding_dim_is_one(self):
data_indexer = DataIndexer()
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("dimensionality 3\n".encode('utf-8'))
embeddings_file.write("word1 1.0 2.3 -1.0\n".encode('utf-8'))
embeddings_file.write("word2 0.1 0.4 -4.0\n".encode('utf-8'))
with pytest.raises(Exception):
PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
def test_get_embedding_layer_skips_inconsistent_lines(self):
data_indexer = DataIndexer()
data_indexer.add_word_to_index("word1")
data_indexer.add_word_to_index("word2")
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word1 1.0 2.3 -1.0\n".encode('utf-8'))
embeddings_file.write("word2 0.1 0.4 \n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
print(embedding_layer.weights)
word_vector = embedding_layer._initial_weights[0][data_indexer.get_word_index("word2")]
assert not numpy.allclose(word_vector[:2], numpy.asarray([0.1, 0.4]))
def test_get_embedding_layer_actually_initializes_word_vectors_correctly(self):
data_indexer = DataIndexer()
data_indexer.add_word_to_index("word")
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word 1.0 2.3 -1.0\n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
word_vector = embedding_layer._initial_weights[0][data_indexer.get_word_index("word")]
assert numpy.allclose(word_vector, numpy.asarray([1.0, 2.3, -1.0]))
def test_get_embedding_layer_initializes_unseen_words_randomly_not_zero(self):
data_indexer = DataIndexer()
data_indexer.add_word_to_index("word2")
embeddings_filename = self.TEST_DIR + "embeddings.gz"
with gzip.open(embeddings_filename, 'wb') as embeddings_file:
embeddings_file.write("word 1.0 2.3 -1.0\n".encode('utf-8'))
embedding_layer = PretrainedEmbeddings.get_embedding_layer(embeddings_filename, data_indexer)
word_vector = embedding_layer._initial_weights[0][data_indexer.get_word_index("word2")]
assert not numpy.allclose(word_vector, numpy.asarray([0.0, 0.0, 0.0]))
def test_embedding_will_not_project_random_embeddings(self):
self.write_pretrained_vector_files()
self.write_true_false_model_files()
with pytest.raises(ConfigurationError):
args = {
"embeddings": {
"words": {
"dimension": 5,
"project": True,
"fine_tune": True,
"dropout": 0.2
}
}
}
model = self.get_model(ClassificationModel, args)
model.train()
def test_projection_dim_not_equal_to_pretrained_dim_with_no_projection_flag_raises_error(self):
self.write_pretrained_vector_files()
self.write_true_false_model_files()
with pytest.raises(ConfigurationError):
args = {
"embeddings": {
"words": {
"dimension": 13,
"pretrained_file": self.PRETRAINED_VECTORS_GZIP,
"project": False,
"fine_tune": False,
"dropout": 0.2
}
}
}
model = self.get_model(ClassificationModel, args)
model.train()
| true | true |
1c46f19ef96c73dc748b7707cea8dbf4595a8711 | 2,871 | py | Python | worker/view.py | photonle/bot | 3689d3bfb177bb4b2efe207311283e63118fa427 | [
"MIT"
] | 1 | 2020-03-18T14:50:59.000Z | 2020-03-18T14:50:59.000Z | worker/view.py | photonle/bot | 3689d3bfb177bb4b2efe207311283e63118fa427 | [
"MIT"
] | 3 | 2020-03-17T14:07:43.000Z | 2021-02-14T13:28:22.000Z | worker/view.py | photonle/bot | 3689d3bfb177bb4b2efe207311283e63118fa427 | [
"MIT"
] | 1 | 2020-05-17T15:19:31.000Z | 2020-05-17T15:19:31.000Z | from shutil import copy
import sqlite3
import sys
sys.stdout = open("report.txt", "w", encoding="utf8")
copy('photon.db', 'photon.read.db')
conn = sqlite3.connect('photon.read.db')
curs = conn.cursor()
curs.execute("SELECT * FROM (SELECT path, COUNT(*) as count FROM files GROUP BY path) WHERE count > 1 ORDER BY count ASC, path ASC")
for reply in curs:
print("\nLua Path '{}' has been seen in {} addons.".format(*reply))
inner = conn.cursor()
inner.execute("SELECT path, owner, name, author, sname FROM files INNER JOIN addons ON files.owner = addons.wsid INNER JOIN authors ON addons.author = authors.sid WHERE path = ? ORDER BY wsid ASC", (reply[0],))
for addon in inner:
print("\tSeen in: '{2}' ({1}) by '{4}' ({3}).".format(*addon))
curs.execute("SELECT * FROM (SELECT cname, COUNT(*) as count FROM cars GROUP BY cname) WHERE count > 1 ORDER BY count ASC, cname ASC")
for reply in curs:
print("\nVehicle ID '{}' has been seen in {} addons.".format(*reply))
inner = conn.cursor()
inner.execute("SELECT cname, owner, name, author, sname FROM cars INNER JOIN addons ON cars.owner = addons.wsid INNER JOIN authors ON addons.author = authors.sid WHERE cname = ? ORDER BY wsid ASC", (reply[0],))
for addon in inner:
print("\tSeen in: '{2}' ({1}) by '{4}' ({3}).".format(*addon))
curs.execute("SELECT * FROM (SELECT cname, COUNT(*) as count FROM components GROUP BY cname) WHERE count > 1 ORDER BY count ASC, cname ASC")
for reply in curs:
print("\nComponent '{}' has been seen in {} addons.".format(*reply))
inner = conn.cursor()
inner.execute("SELECT cname, owner, name, author, sname FROM components INNER JOIN addons ON components.owner = addons.wsid INNER JOIN authors ON addons.author = authors.sid WHERE cname = ? ORDER BY wsid ASC", (reply[0],))
for addon in inner:
print("\tSeen in: '{2}' ({1}) by '{4}' ({3}).".format(*addon))
# curs.execute("SELECT * FROM files INNER JOIN addons ON files.owner = addons.wsid WHERE owner IN (SELECT wsid FROM addons WHERE author = 76561198166686412)")
# for reply in curs:
# inner = conn.cursor()
# inner.execute("SELECT path, owner, name, author, sname FROM files INNER JOIN addons ON files.owner = addons.wsid INNER JOIN authors ON addons.author = authors.sid WHERE path = ? ORDER BY wsid ASC", (reply[0],))
# # res = inner.fetchone()
# # if res is not None:
# # print("Lua Path '{0}'.".format(*reply))
# # print("\tSeen in: '{2}' ({1}) by '{4}' ({3}).".format(*res))
# for reply in curs:
# print("\nLua Path '{}' has been seen in {} addons.".format(*reply))
# inner = conn.cursor()
# inner.execute("SELECT path, owner, name, author, sname FROM files INNER JOIN addons ON files.owner = addons.wsid INNER JOIN authors ON addons.author = authors.sid WHERE path = ? ORDER BY wsid ASC", (reply[0],))
# for addon in inner:
# print("\tSeen in: '{2}' ({1}) by '{4}' ({3}).".format(*addon))
| 58.591837 | 223 | 0.676071 | from shutil import copy
import sqlite3
import sys
sys.stdout = open("report.txt", "w", encoding="utf8")
copy('photon.db', 'photon.read.db')
conn = sqlite3.connect('photon.read.db')
curs = conn.cursor()
curs.execute("SELECT * FROM (SELECT path, COUNT(*) as count FROM files GROUP BY path) WHERE count > 1 ORDER BY count ASC, path ASC")
for reply in curs:
print("\nLua Path '{}' has been seen in {} addons.".format(*reply))
inner = conn.cursor()
inner.execute("SELECT path, owner, name, author, sname FROM files INNER JOIN addons ON files.owner = addons.wsid INNER JOIN authors ON addons.author = authors.sid WHERE path = ? ORDER BY wsid ASC", (reply[0],))
for addon in inner:
print("\tSeen in: '{2}' ({1}) by '{4}' ({3}).".format(*addon))
curs.execute("SELECT * FROM (SELECT cname, COUNT(*) as count FROM cars GROUP BY cname) WHERE count > 1 ORDER BY count ASC, cname ASC")
for reply in curs:
print("\nVehicle ID '{}' has been seen in {} addons.".format(*reply))
inner = conn.cursor()
inner.execute("SELECT cname, owner, name, author, sname FROM cars INNER JOIN addons ON cars.owner = addons.wsid INNER JOIN authors ON addons.author = authors.sid WHERE cname = ? ORDER BY wsid ASC", (reply[0],))
for addon in inner:
print("\tSeen in: '{2}' ({1}) by '{4}' ({3}).".format(*addon))
curs.execute("SELECT * FROM (SELECT cname, COUNT(*) as count FROM components GROUP BY cname) WHERE count > 1 ORDER BY count ASC, cname ASC")
for reply in curs:
print("\nComponent '{}' has been seen in {} addons.".format(*reply))
inner = conn.cursor()
inner.execute("SELECT cname, owner, name, author, sname FROM components INNER JOIN addons ON components.owner = addons.wsid INNER JOIN authors ON addons.author = authors.sid WHERE cname = ? ORDER BY wsid ASC", (reply[0],))
for addon in inner:
print("\tSeen in: '{2}' ({1}) by '{4}' ({3}).".format(*addon))
| true | true |
1c46f2088730032fec400cd35792bfc6b4aa4935 | 3,714 | py | Python | Lesson 04/walkthrough.py | NoelKocheril/Python101 | b0e923e1ec3e936babbd57a310ec72b13e07ac57 | [
"WTFPL"
] | null | null | null | Lesson 04/walkthrough.py | NoelKocheril/Python101 | b0e923e1ec3e936babbd57a310ec72b13e07ac57 | [
"WTFPL"
] | null | null | null | Lesson 04/walkthrough.py | NoelKocheril/Python101 | b0e923e1ec3e936babbd57a310ec72b13e07ac57 | [
"WTFPL"
] | null | null | null | # Defines a function
# def my_func():
# print("Hello, World!")
# Calls a function
# my_func()
# Repeats a function
# for j in range(10):
# my_func()
# myName = "Noel Kocheril"
# def hello(fname):
# print(f"Hello {fname}")
# hello() # Missing an argument
# hello("Noel")
# hello("Vit")
# hello("Shawn")
# Takes two arguments, and adds them together
# def sum(x, y):
# print(x + y)
# def difference(x, y):
# print(x - y)
# def difference2(x, y, z):
# print(x - y)
# difference(5, 10)
# difference(y=5, x=10)
# difference2(10, 5)
# x = 5
# print("Hello", "Noel", x)
# def printLastChild(*children):
# print(children[-1])
# printLastChild("Noel", "Steve", "Bob")
# Not allowed to have multiple arbitrary arguments
# def printNames(*fname, *lnames):
# print(f"{fname} {lnames}")
# def printLastName(**person):
# print("Hello, Mr. " + person["lname"])
# printLastName(fname="Noel", age=25, lname="Kocheril")
# def greet(name, message="Good Morning!"):
# print(f"Hello, {name}, {message}")
# greet("Noel")
# greet("Vit", "How are you?")
# Not allowed: Non-Default Argument after default argument
# def greet(message="Good Morning!", name):
# print(f"Hello, {name}, {message}")
# def my_func(food):
# for x in food:
# print(x)
# fruits = ["apple", "banana", "orange"]
# my_func(fruits)
# def square(x):
# return x * x
# print(square(10))
# def my_func():
# return 4
# print("This will never run.....")
# def percentageToLetterGrade(percentage):
# if percentage >= 80:
# return "A"
# elif percentage >= 70:
# return "B"
# elif percentage >= 60:
# return "C"
# elif percentage >= 50:
# return "D"
# return "F"
# print(percentageToLetterGrade(50))
# def sumOfNumbers(n):
# if n >= 0:
# result = n + sumOfNumbers(n - 1)
# print(result)
# else:
# result = 0
# return result
# sumOfNumbers(5)
# """
# sumOfNumbers(5)
# -> result = 5 + sumOfNumbers(4)
# -> result = 5 + 4 + sumOfNumbers(3) -> 0
# """
# def TowersOfHanoi()
# Fibonacci Sequence - n = n-1 + n-2
# x_n = x_n-1 + x_n-2
# count = 0
# def FibonacciSequence(n):
# if n == 0:
# result = 0
# elif n == 1:
# result = 1
# else:
# result = FibonacciSequence(n - 1) + FibonacciSequence(n - 2)
# global count
# count += 1
# print(result)
# return result
# FibonacciSequence(10)
# print(count)
# for i in range(100):
# print(f"{i}: {FibonacciSequence(i)}")
# def fib(n):
# if n
# sum = 0
# for i in range(1, 10):
# sum += 2 ** i
# print(sum)
"""
fib(n) -> fib(n-1) + fib(fib-2)
1 - fib
2 - 2 fib
3 - 4 fib
nth - 2^n - 17,179,869,184
"""
# Power Function - Using Recursion
# power(base, expo)
# x^n
# def power(base, expo):
# if expo > 0:
# result = power(base, expo - 1) * (base)
# print(result)
# return result
# elif expo == 0:
# return 1
# power(3, 3)
"""
power(3,3)
result = 27
"""
"""
STEP 1
N^6
->
(N^5 * N)
STEP 2
N^5 * N
->
(N^4 * N) * N
(N^3 * N) * N * N
(N^2 * N) * N * N * N
(N^1 * N) * N * N * N * N
(N^0 * N) * N * N * N * N * N
1 * N * N * N * N * N * N
"""
# always comes back to sequences
# Factorial - n! = n * (n - 1)!
def factorial(x):
if x > 0:
result = x * factorial(x - 1)
print(result)
return result
elif x == 0:
return 1
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
for i in range(5):
fact(i)
"""""
n!
4! = 4*3*2*1
4!
3! = 3*2*1
4!
4 * 3!
4 * 3 * 2!
4 * 3 * 2 * 1!
4 * 3 * 2 * 1 * 0!
4 * 3 * 2 * 1 * 1
"""
| 13.407942 | 70 | 0.522348 |
# sumOfNumbers(5)
# -> result = 5 + sumOfNumbers(4)
# -> result = 5 + 4 + sumOfNumbers(3) -> 0
# """
def factorial(x):
if x > 0:
result = x * factorial(x - 1)
print(result)
return result
elif x == 0:
return 1
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
for i in range(5):
fact(i)
| true | true |
1c46f24731b57cf200f9345b0298f65fdfe81f08 | 1,237 | py | Python | ecom/urls.py | dongmokevin/ecomv1 | abb3dc5a5476c379c029b8299e820c1979d5eb14 | [
"MIT"
] | null | null | null | ecom/urls.py | dongmokevin/ecomv1 | abb3dc5a5476c379c029b8299e820c1979d5eb14 | [
"MIT"
] | null | null | null | ecom/urls.py | dongmokevin/ecomv1 | abb3dc5a5476c379c029b8299e820c1979d5eb14 | [
"MIT"
] | null | null | null | """ecom URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
path('basket/', include('basket.urls', namespace='basket')),
path('payment/', include('payment.urls', namespace='payment')),
path('orders/', include('orders.urls', namespace='orders')),
path('account/', include('account.urls', namespace='account')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| 35.342857 | 80 | 0.704931 | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
path('basket/', include('basket.urls', namespace='basket')),
path('payment/', include('payment.urls', namespace='payment')),
path('orders/', include('orders.urls', namespace='orders')),
path('account/', include('account.urls', namespace='account')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| true | true |
1c46f4a9f5384283addc48510e60b1443d6e5e60 | 898 | py | Python | python/hsml/utils/tensor.py | robzor92/models-api | d83ebd775acab4fad94cd4c6a38107635e4b4880 | [
"Apache-2.0"
] | null | null | null | python/hsml/utils/tensor.py | robzor92/models-api | d83ebd775acab4fad94cd4c6a38107635e4b4880 | [
"Apache-2.0"
] | null | null | null | python/hsml/utils/tensor.py | robzor92/models-api | d83ebd775acab4fad94cd4c6a38107635e4b4880 | [
"Apache-2.0"
] | null | null | null | #
# Copyright 2021 Logical Clocks AB
#
# 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.
#
class Tensor:
"""Metadata object representing a model signature for a model."""
def __init__(self, data_type: None, shape: None):
self.data_type = data_type
self.shape = shape
def to_dict(self):
return {"shape": self.shape, "dataType": self.data_type}
| 32.071429 | 76 | 0.7049 |
class Tensor:
def __init__(self, data_type: None, shape: None):
self.data_type = data_type
self.shape = shape
def to_dict(self):
return {"shape": self.shape, "dataType": self.data_type}
| true | true |
1c46f50f3cb0a12eb3ccbd5ce2ef644903c88627 | 12,415 | py | Python | homeassistant/components/alarmdecoder/config_flow.py | DavidDeSloovere/core | 909a20b36d4df6724c955c2ae28cb82fe6d50c2e | [
"Apache-2.0"
] | 4 | 2020-08-10T20:02:24.000Z | 2022-01-31T02:14:22.000Z | homeassistant/components/alarmdecoder/config_flow.py | jagadeeshvenkatesh/core | 1bd982668449815fee2105478569f8e4b5670add | [
"Apache-2.0"
] | 78 | 2020-07-23T07:13:08.000Z | 2022-03-31T06:02:04.000Z | homeassistant/components/alarmdecoder/config_flow.py | jagadeeshvenkatesh/core | 1bd982668449815fee2105478569f8e4b5670add | [
"Apache-2.0"
] | 3 | 2022-01-17T20:10:54.000Z | 2022-01-17T20:17:22.000Z | """Config flow for AlarmDecoder."""
import logging
from adext import AdExt
from alarmdecoder.devices import SerialDevice, SocketDevice
from alarmdecoder.util import NoDeviceError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.binary_sensor import DEVICE_CLASSES
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL
from homeassistant.core import callback
from .const import (
CONF_ALT_NIGHT_MODE,
CONF_AUTO_BYPASS,
CONF_CODE_ARM_REQUIRED,
CONF_DEVICE_BAUD,
CONF_DEVICE_PATH,
CONF_RELAY_ADDR,
CONF_RELAY_CHAN,
CONF_ZONE_LOOP,
CONF_ZONE_NAME,
CONF_ZONE_NUMBER,
CONF_ZONE_RFID,
CONF_ZONE_TYPE,
DEFAULT_ARM_OPTIONS,
DEFAULT_DEVICE_BAUD,
DEFAULT_DEVICE_HOST,
DEFAULT_DEVICE_PATH,
DEFAULT_DEVICE_PORT,
DEFAULT_ZONE_OPTIONS,
DEFAULT_ZONE_TYPE,
DOMAIN,
OPTIONS_ARM,
OPTIONS_ZONES,
PROTOCOL_SERIAL,
PROTOCOL_SOCKET,
)
EDIT_KEY = "edit_selection"
EDIT_ZONES = "Zones"
EDIT_SETTINGS = "Arming Settings"
_LOGGER = logging.getLogger(__name__)
class AlarmDecoderFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a AlarmDecoder config flow."""
VERSION = 1
def __init__(self):
"""Initialize AlarmDecoder ConfigFlow."""
self.protocol = None
@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow for AlarmDecoder."""
return AlarmDecoderOptionsFlowHandler(config_entry)
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
if user_input is not None:
self.protocol = user_input[CONF_PROTOCOL]
return await self.async_step_protocol()
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_PROTOCOL): vol.In(
[PROTOCOL_SOCKET, PROTOCOL_SERIAL]
),
}
),
)
async def async_step_protocol(self, user_input=None):
"""Handle AlarmDecoder protocol setup."""
errors = {}
if user_input is not None:
if _device_already_added(
self._async_current_entries(), user_input, self.protocol
):
return self.async_abort(reason="already_configured")
connection = {}
baud = None
if self.protocol == PROTOCOL_SOCKET:
host = connection[CONF_HOST] = user_input[CONF_HOST]
port = connection[CONF_PORT] = user_input[CONF_PORT]
title = f"{host}:{port}"
device = SocketDevice(interface=(host, port))
if self.protocol == PROTOCOL_SERIAL:
path = connection[CONF_DEVICE_PATH] = user_input[CONF_DEVICE_PATH]
baud = connection[CONF_DEVICE_BAUD] = user_input[CONF_DEVICE_BAUD]
title = path
device = SerialDevice(interface=path)
controller = AdExt(device)
def test_connection():
controller.open(baud)
controller.close()
try:
await self.hass.async_add_executor_job(test_connection)
return self.async_create_entry(
title=title, data={CONF_PROTOCOL: self.protocol, **connection}
)
except NoDeviceError:
errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception during AlarmDecoder setup")
errors["base"] = "unknown"
if self.protocol == PROTOCOL_SOCKET:
schema = vol.Schema(
{
vol.Required(CONF_HOST, default=DEFAULT_DEVICE_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_DEVICE_PORT): int,
}
)
if self.protocol == PROTOCOL_SERIAL:
schema = vol.Schema(
{
vol.Required(CONF_DEVICE_PATH, default=DEFAULT_DEVICE_PATH): str,
vol.Required(CONF_DEVICE_BAUD, default=DEFAULT_DEVICE_BAUD): int,
}
)
return self.async_show_form(
step_id="protocol",
data_schema=schema,
errors=errors,
)
class AlarmDecoderOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle AlarmDecoder options."""
def __init__(self, config_entry: config_entries.ConfigEntry):
"""Initialize AlarmDecoder options flow."""
self.arm_options = config_entry.options.get(OPTIONS_ARM, DEFAULT_ARM_OPTIONS)
self.zone_options = config_entry.options.get(
OPTIONS_ZONES, DEFAULT_ZONE_OPTIONS
)
self.selected_zone = None
async def async_step_init(self, user_input=None):
"""Manage the options."""
if user_input is not None:
if user_input[EDIT_KEY] == EDIT_SETTINGS:
return await self.async_step_arm_settings()
if user_input[EDIT_KEY] == EDIT_ZONES:
return await self.async_step_zone_select()
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(EDIT_KEY, default=EDIT_SETTINGS): vol.In(
[EDIT_SETTINGS, EDIT_ZONES]
)
},
),
)
async def async_step_arm_settings(self, user_input=None):
"""Arming options form."""
if user_input is not None:
return self.async_create_entry(
title="",
data={OPTIONS_ARM: user_input, OPTIONS_ZONES: self.zone_options},
)
return self.async_show_form(
step_id="arm_settings",
data_schema=vol.Schema(
{
vol.Optional(
CONF_ALT_NIGHT_MODE,
default=self.arm_options[CONF_ALT_NIGHT_MODE],
): bool,
vol.Optional(
CONF_AUTO_BYPASS, default=self.arm_options[CONF_AUTO_BYPASS]
): bool,
vol.Optional(
CONF_CODE_ARM_REQUIRED,
default=self.arm_options[CONF_CODE_ARM_REQUIRED],
): bool,
},
),
)
async def async_step_zone_select(self, user_input=None):
"""Zone selection form."""
errors = _validate_zone_input(user_input)
if user_input is not None and not errors:
self.selected_zone = str(
int(user_input[CONF_ZONE_NUMBER])
) # remove leading zeros
return await self.async_step_zone_details()
return self.async_show_form(
step_id="zone_select",
data_schema=vol.Schema({vol.Required(CONF_ZONE_NUMBER): str}),
errors=errors,
)
async def async_step_zone_details(self, user_input=None):
"""Zone details form."""
errors = _validate_zone_input(user_input)
if user_input is not None and not errors:
zone_options = self.zone_options.copy()
zone_id = self.selected_zone
zone_options[zone_id] = _fix_input_types(user_input)
# Delete zone entry if zone_name is omitted
if CONF_ZONE_NAME not in zone_options[zone_id]:
zone_options.pop(zone_id)
return self.async_create_entry(
title="",
data={OPTIONS_ARM: self.arm_options, OPTIONS_ZONES: zone_options},
)
existing_zone_settings = self.zone_options.get(self.selected_zone, {})
return self.async_show_form(
step_id="zone_details",
description_placeholders={CONF_ZONE_NUMBER: self.selected_zone},
data_schema=vol.Schema(
{
vol.Optional(
CONF_ZONE_NAME,
description={
"suggested_value": existing_zone_settings.get(
CONF_ZONE_NAME
)
},
): str,
vol.Optional(
CONF_ZONE_TYPE,
default=existing_zone_settings.get(
CONF_ZONE_TYPE, DEFAULT_ZONE_TYPE
),
): vol.In(DEVICE_CLASSES),
vol.Optional(
CONF_ZONE_RFID,
description={
"suggested_value": existing_zone_settings.get(
CONF_ZONE_RFID
)
},
): str,
vol.Optional(
CONF_ZONE_LOOP,
description={
"suggested_value": existing_zone_settings.get(
CONF_ZONE_LOOP
)
},
): str,
vol.Optional(
CONF_RELAY_ADDR,
description={
"suggested_value": existing_zone_settings.get(
CONF_RELAY_ADDR
)
},
): str,
vol.Optional(
CONF_RELAY_CHAN,
description={
"suggested_value": existing_zone_settings.get(
CONF_RELAY_CHAN
)
},
): str,
}
),
errors=errors,
)
def _validate_zone_input(zone_input):
if not zone_input:
return {}
errors = {}
# CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive
if (CONF_RELAY_ADDR in zone_input and CONF_RELAY_CHAN not in zone_input) or (
CONF_RELAY_ADDR not in zone_input and CONF_RELAY_CHAN in zone_input
):
errors["base"] = "relay_inclusive"
# The following keys must be int
for key in [CONF_ZONE_NUMBER, CONF_ZONE_LOOP, CONF_RELAY_ADDR, CONF_RELAY_CHAN]:
if key in zone_input:
try:
int(zone_input[key])
except ValueError:
errors[key] = "int"
# CONF_ZONE_LOOP depends on CONF_ZONE_RFID
if CONF_ZONE_LOOP in zone_input and CONF_ZONE_RFID not in zone_input:
errors[CONF_ZONE_LOOP] = "loop_rfid"
# CONF_ZONE_LOOP must be 1-4
if (
CONF_ZONE_LOOP in zone_input
and zone_input[CONF_ZONE_LOOP].isdigit()
and int(zone_input[CONF_ZONE_LOOP]) not in list(range(1, 5))
):
errors[CONF_ZONE_LOOP] = "loop_range"
return errors
def _fix_input_types(zone_input):
"""Convert necessary keys to int.
Since ConfigFlow inputs of type int cannot default to an empty string, we collect the values below as
strings and then convert them to ints.
"""
for key in [CONF_ZONE_LOOP, CONF_RELAY_ADDR, CONF_RELAY_CHAN]:
if key in zone_input:
zone_input[key] = int(zone_input[key])
return zone_input
def _device_already_added(current_entries, user_input, protocol):
"""Determine if entry has already been added to HA."""
user_host = user_input.get(CONF_HOST)
user_port = user_input.get(CONF_PORT)
user_path = user_input.get(CONF_DEVICE_PATH)
user_baud = user_input.get(CONF_DEVICE_BAUD)
for entry in current_entries:
entry_host = entry.data.get(CONF_HOST)
entry_port = entry.data.get(CONF_PORT)
entry_path = entry.data.get(CONF_DEVICE_PATH)
entry_baud = entry.data.get(CONF_DEVICE_BAUD)
if (
protocol == PROTOCOL_SOCKET
and user_host == entry_host
and user_port == entry_port
):
return True
if (
protocol == PROTOCOL_SERIAL
and user_baud == entry_baud
and user_path == entry_path
):
return True
return False
| 33.920765 | 105 | 0.560129 | import logging
from adext import AdExt
from alarmdecoder.devices import SerialDevice, SocketDevice
from alarmdecoder.util import NoDeviceError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.binary_sensor import DEVICE_CLASSES
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL
from homeassistant.core import callback
from .const import (
CONF_ALT_NIGHT_MODE,
CONF_AUTO_BYPASS,
CONF_CODE_ARM_REQUIRED,
CONF_DEVICE_BAUD,
CONF_DEVICE_PATH,
CONF_RELAY_ADDR,
CONF_RELAY_CHAN,
CONF_ZONE_LOOP,
CONF_ZONE_NAME,
CONF_ZONE_NUMBER,
CONF_ZONE_RFID,
CONF_ZONE_TYPE,
DEFAULT_ARM_OPTIONS,
DEFAULT_DEVICE_BAUD,
DEFAULT_DEVICE_HOST,
DEFAULT_DEVICE_PATH,
DEFAULT_DEVICE_PORT,
DEFAULT_ZONE_OPTIONS,
DEFAULT_ZONE_TYPE,
DOMAIN,
OPTIONS_ARM,
OPTIONS_ZONES,
PROTOCOL_SERIAL,
PROTOCOL_SOCKET,
)
EDIT_KEY = "edit_selection"
EDIT_ZONES = "Zones"
EDIT_SETTINGS = "Arming Settings"
_LOGGER = logging.getLogger(__name__)
class AlarmDecoderFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
def __init__(self):
self.protocol = None
@staticmethod
@callback
def async_get_options_flow(config_entry):
return AlarmDecoderOptionsFlowHandler(config_entry)
async def async_step_user(self, user_input=None):
if user_input is not None:
self.protocol = user_input[CONF_PROTOCOL]
return await self.async_step_protocol()
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_PROTOCOL): vol.In(
[PROTOCOL_SOCKET, PROTOCOL_SERIAL]
),
}
),
)
async def async_step_protocol(self, user_input=None):
errors = {}
if user_input is not None:
if _device_already_added(
self._async_current_entries(), user_input, self.protocol
):
return self.async_abort(reason="already_configured")
connection = {}
baud = None
if self.protocol == PROTOCOL_SOCKET:
host = connection[CONF_HOST] = user_input[CONF_HOST]
port = connection[CONF_PORT] = user_input[CONF_PORT]
title = f"{host}:{port}"
device = SocketDevice(interface=(host, port))
if self.protocol == PROTOCOL_SERIAL:
path = connection[CONF_DEVICE_PATH] = user_input[CONF_DEVICE_PATH]
baud = connection[CONF_DEVICE_BAUD] = user_input[CONF_DEVICE_BAUD]
title = path
device = SerialDevice(interface=path)
controller = AdExt(device)
def test_connection():
controller.open(baud)
controller.close()
try:
await self.hass.async_add_executor_job(test_connection)
return self.async_create_entry(
title=title, data={CONF_PROTOCOL: self.protocol, **connection}
)
except NoDeviceError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception during AlarmDecoder setup")
errors["base"] = "unknown"
if self.protocol == PROTOCOL_SOCKET:
schema = vol.Schema(
{
vol.Required(CONF_HOST, default=DEFAULT_DEVICE_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_DEVICE_PORT): int,
}
)
if self.protocol == PROTOCOL_SERIAL:
schema = vol.Schema(
{
vol.Required(CONF_DEVICE_PATH, default=DEFAULT_DEVICE_PATH): str,
vol.Required(CONF_DEVICE_BAUD, default=DEFAULT_DEVICE_BAUD): int,
}
)
return self.async_show_form(
step_id="protocol",
data_schema=schema,
errors=errors,
)
class AlarmDecoderOptionsFlowHandler(config_entries.OptionsFlow):
def __init__(self, config_entry: config_entries.ConfigEntry):
self.arm_options = config_entry.options.get(OPTIONS_ARM, DEFAULT_ARM_OPTIONS)
self.zone_options = config_entry.options.get(
OPTIONS_ZONES, DEFAULT_ZONE_OPTIONS
)
self.selected_zone = None
async def async_step_init(self, user_input=None):
if user_input is not None:
if user_input[EDIT_KEY] == EDIT_SETTINGS:
return await self.async_step_arm_settings()
if user_input[EDIT_KEY] == EDIT_ZONES:
return await self.async_step_zone_select()
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(EDIT_KEY, default=EDIT_SETTINGS): vol.In(
[EDIT_SETTINGS, EDIT_ZONES]
)
},
),
)
async def async_step_arm_settings(self, user_input=None):
if user_input is not None:
return self.async_create_entry(
title="",
data={OPTIONS_ARM: user_input, OPTIONS_ZONES: self.zone_options},
)
return self.async_show_form(
step_id="arm_settings",
data_schema=vol.Schema(
{
vol.Optional(
CONF_ALT_NIGHT_MODE,
default=self.arm_options[CONF_ALT_NIGHT_MODE],
): bool,
vol.Optional(
CONF_AUTO_BYPASS, default=self.arm_options[CONF_AUTO_BYPASS]
): bool,
vol.Optional(
CONF_CODE_ARM_REQUIRED,
default=self.arm_options[CONF_CODE_ARM_REQUIRED],
): bool,
},
),
)
async def async_step_zone_select(self, user_input=None):
errors = _validate_zone_input(user_input)
if user_input is not None and not errors:
self.selected_zone = str(
int(user_input[CONF_ZONE_NUMBER])
)
return await self.async_step_zone_details()
return self.async_show_form(
step_id="zone_select",
data_schema=vol.Schema({vol.Required(CONF_ZONE_NUMBER): str}),
errors=errors,
)
async def async_step_zone_details(self, user_input=None):
errors = _validate_zone_input(user_input)
if user_input is not None and not errors:
zone_options = self.zone_options.copy()
zone_id = self.selected_zone
zone_options[zone_id] = _fix_input_types(user_input)
if CONF_ZONE_NAME not in zone_options[zone_id]:
zone_options.pop(zone_id)
return self.async_create_entry(
title="",
data={OPTIONS_ARM: self.arm_options, OPTIONS_ZONES: zone_options},
)
existing_zone_settings = self.zone_options.get(self.selected_zone, {})
return self.async_show_form(
step_id="zone_details",
description_placeholders={CONF_ZONE_NUMBER: self.selected_zone},
data_schema=vol.Schema(
{
vol.Optional(
CONF_ZONE_NAME,
description={
"suggested_value": existing_zone_settings.get(
CONF_ZONE_NAME
)
},
): str,
vol.Optional(
CONF_ZONE_TYPE,
default=existing_zone_settings.get(
CONF_ZONE_TYPE, DEFAULT_ZONE_TYPE
),
): vol.In(DEVICE_CLASSES),
vol.Optional(
CONF_ZONE_RFID,
description={
"suggested_value": existing_zone_settings.get(
CONF_ZONE_RFID
)
},
): str,
vol.Optional(
CONF_ZONE_LOOP,
description={
"suggested_value": existing_zone_settings.get(
CONF_ZONE_LOOP
)
},
): str,
vol.Optional(
CONF_RELAY_ADDR,
description={
"suggested_value": existing_zone_settings.get(
CONF_RELAY_ADDR
)
},
): str,
vol.Optional(
CONF_RELAY_CHAN,
description={
"suggested_value": existing_zone_settings.get(
CONF_RELAY_CHAN
)
},
): str,
}
),
errors=errors,
)
def _validate_zone_input(zone_input):
if not zone_input:
return {}
errors = {}
if (CONF_RELAY_ADDR in zone_input and CONF_RELAY_CHAN not in zone_input) or (
CONF_RELAY_ADDR not in zone_input and CONF_RELAY_CHAN in zone_input
):
errors["base"] = "relay_inclusive"
for key in [CONF_ZONE_NUMBER, CONF_ZONE_LOOP, CONF_RELAY_ADDR, CONF_RELAY_CHAN]:
if key in zone_input:
try:
int(zone_input[key])
except ValueError:
errors[key] = "int"
if CONF_ZONE_LOOP in zone_input and CONF_ZONE_RFID not in zone_input:
errors[CONF_ZONE_LOOP] = "loop_rfid"
if (
CONF_ZONE_LOOP in zone_input
and zone_input[CONF_ZONE_LOOP].isdigit()
and int(zone_input[CONF_ZONE_LOOP]) not in list(range(1, 5))
):
errors[CONF_ZONE_LOOP] = "loop_range"
return errors
def _fix_input_types(zone_input):
for key in [CONF_ZONE_LOOP, CONF_RELAY_ADDR, CONF_RELAY_CHAN]:
if key in zone_input:
zone_input[key] = int(zone_input[key])
return zone_input
def _device_already_added(current_entries, user_input, protocol):
user_host = user_input.get(CONF_HOST)
user_port = user_input.get(CONF_PORT)
user_path = user_input.get(CONF_DEVICE_PATH)
user_baud = user_input.get(CONF_DEVICE_BAUD)
for entry in current_entries:
entry_host = entry.data.get(CONF_HOST)
entry_port = entry.data.get(CONF_PORT)
entry_path = entry.data.get(CONF_DEVICE_PATH)
entry_baud = entry.data.get(CONF_DEVICE_BAUD)
if (
protocol == PROTOCOL_SOCKET
and user_host == entry_host
and user_port == entry_port
):
return True
if (
protocol == PROTOCOL_SERIAL
and user_baud == entry_baud
and user_path == entry_path
):
return True
return False
| true | true |
1c46f51d76f2d9918be20948b378e49153ec1648 | 7,109 | py | Python | svgpathtools/svg_io_sax.py | Vrroom/svgpathtools | b9621c9c340337cd044ae21c83e2917cd010dc8f | [
"MIT"
] | 2 | 2018-05-08T05:31:15.000Z | 2022-01-27T11:51:04.000Z | svgpathtools/svg_io_sax.py | taoari/svgpathtools | 9b1b8e78e10b99d6ca3d4b28e5b6b0d1596b8dc2 | [
"MIT"
] | null | null | null | svgpathtools/svg_io_sax.py | taoari/svgpathtools | 9b1b8e78e10b99d6ca3d4b28e5b6b0d1596b8dc2 | [
"MIT"
] | 3 | 2018-01-15T18:08:06.000Z | 2018-10-11T09:19:49.000Z | """(Experimental) replacement for import/export functionality SAX
"""
# External dependencies
from __future__ import division, absolute_import, print_function
import os
from xml.etree.ElementTree import iterparse, Element, ElementTree, SubElement
# Internal dependencies
from .parser import parse_path
from .parser import parse_transform
from .svg_to_paths import (path2pathd, ellipse2pathd, line2pathd,
polyline2pathd, polygon2pathd, rect2pathd)
from .misctools import open_in_browser
from .path import *
# To maintain forward/backward compatibility
try:
str = basestring
except NameError:
pass
NAME_SVG = "svg"
ATTR_VERSION = "version"
VALUE_SVG_VERSION = "1.1"
ATTR_XMLNS = "xmlns"
VALUE_XMLNS = "http://www.w3.org/2000/svg"
ATTR_XMLNS_LINK = "xmlns:xlink"
VALUE_XLINK = "http://www.w3.org/1999/xlink"
ATTR_XMLNS_EV = "xmlns:ev"
VALUE_XMLNS_EV = "http://www.w3.org/2001/xml-events"
ATTR_WIDTH = "width"
ATTR_HEIGHT = "height"
ATTR_VIEWBOX = "viewBox"
NAME_PATH = "path"
ATTR_DATA = "d"
ATTR_FILL = "fill"
ATTR_STROKE = "stroke"
ATTR_STROKE_WIDTH = "stroke-width"
ATTR_TRANSFORM = "transform"
VALUE_NONE = "none"
class SaxDocument:
def __init__(self, filename):
"""A container for a SAX SVG light tree objects document.
This class provides functions for extracting SVG data into Path objects.
Args:
filename (str): The filename of the SVG file
"""
self.root_values = {}
self.tree = []
# remember location of original svg file
if filename is not None and os.path.dirname(filename) == '':
self.original_filename = os.path.join(os.getcwd(), filename)
else:
self.original_filename = filename
if filename is not None:
self.sax_parse(filename)
def sax_parse(self, filename):
self.root_values = {}
self.tree = []
stack = []
values = {}
matrix = None
for event, elem in iterparse(filename, events=('start', 'end')):
if event == 'start':
stack.append((values, matrix))
if matrix is not None:
matrix = matrix.copy() # copy of matrix
current_values = values
values = {}
values.update(current_values) # copy of dictionary
attrs = elem.attrib
values.update(attrs)
name = elem.tag[28:]
if "style" in attrs:
for equate in attrs["style"].split(";"):
equal_item = equate.split(":")
values[equal_item[0]] = equal_item[1]
if "transform" in attrs:
transform_matrix = parse_transform(attrs["transform"])
if matrix is None:
matrix = np.identity(3)
matrix = transform_matrix.dot(matrix)
if "svg" == name:
current_values = values
values = {}
values.update(current_values)
self.root_values = current_values
continue
elif "g" == name:
continue
elif 'path' == name:
values['d'] = path2pathd(values)
elif 'circle' == name:
values["d"] = ellipse2pathd(values)
elif 'ellipse' == name:
values["d"] = ellipse2pathd(values)
elif 'line' == name:
values["d"] = line2pathd(values)
elif 'polyline' == name:
values["d"] = polyline2pathd(values['points'])
elif 'polygon' == name:
values["d"] = polygon2pathd(values['points'])
elif 'rect' == name:
values["d"] = rect2pathd(values)
else:
continue
values["matrix"] = matrix
values["name"] = name
self.tree.append(values)
else:
v = stack.pop()
values = v[0]
matrix = v[1]
def flatten_all_paths(self):
flat = []
for values in self.tree:
pathd = values['d']
matrix = values['matrix']
parsed_path = parse_path(pathd)
if matrix is not None:
transform(parsed_path, matrix)
flat.append(parsed_path)
return flat
def get_pathd_and_matrix(self):
flat = []
for values in self.tree:
pathd = values['d']
matrix = values['matrix']
flat.append((pathd, matrix))
return flat
def generate_dom(self):
root = Element(NAME_SVG)
root.set(ATTR_VERSION, VALUE_SVG_VERSION)
root.set(ATTR_XMLNS, VALUE_XMLNS)
root.set(ATTR_XMLNS_LINK, VALUE_XLINK)
root.set(ATTR_XMLNS_EV, VALUE_XMLNS_EV)
width = self.root_values.get(ATTR_WIDTH, None)
height = self.root_values.get(ATTR_HEIGHT, None)
if width is not None:
root.set(ATTR_WIDTH, width)
if height is not None:
root.set(ATTR_HEIGHT, height)
viewbox = self.root_values.get(ATTR_VIEWBOX, None)
if viewbox is not None:
root.set(ATTR_VIEWBOX, viewbox)
identity = np.identity(3)
for values in self.tree:
pathd = values.get('d', '')
matrix = values.get('matrix', None)
# path_value = parse_path(pathd)
path = SubElement(root, NAME_PATH)
if matrix is not None and not np.all(np.equal(matrix, identity)):
matrix_string = "matrix("
matrix_string += " "
matrix_string += str(matrix[0][0])
matrix_string += " "
matrix_string += str(matrix[1][0])
matrix_string += " "
matrix_string += str(matrix[0][1])
matrix_string += " "
matrix_string += str(matrix[1][1])
matrix_string += " "
matrix_string += str(matrix[0][2])
matrix_string += " "
matrix_string += str(matrix[1][2])
matrix_string += ")"
path.set(ATTR_TRANSFORM, matrix_string)
if ATTR_DATA in values:
path.set(ATTR_DATA, values[ATTR_DATA])
if ATTR_FILL in values:
path.set(ATTR_FILL, values[ATTR_FILL])
if ATTR_STROKE in values:
path.set(ATTR_STROKE, values[ATTR_STROKE])
return ElementTree(root)
def save(self, filename):
with open(filename, 'wb') as output_svg:
dom_tree = self.generate_dom()
dom_tree.write(output_svg)
def display(self, filename=None):
"""Displays/opens the doc using the OS's default application."""
if filename is None:
filename = 'display_temp.svg'
self.save(filename)
open_in_browser(filename)
| 35.723618 | 80 | 0.544943 |
from __future__ import division, absolute_import, print_function
import os
from xml.etree.ElementTree import iterparse, Element, ElementTree, SubElement
from .parser import parse_path
from .parser import parse_transform
from .svg_to_paths import (path2pathd, ellipse2pathd, line2pathd,
polyline2pathd, polygon2pathd, rect2pathd)
from .misctools import open_in_browser
from .path import *
try:
str = basestring
except NameError:
pass
NAME_SVG = "svg"
ATTR_VERSION = "version"
VALUE_SVG_VERSION = "1.1"
ATTR_XMLNS = "xmlns"
VALUE_XMLNS = "http://www.w3.org/2000/svg"
ATTR_XMLNS_LINK = "xmlns:xlink"
VALUE_XLINK = "http://www.w3.org/1999/xlink"
ATTR_XMLNS_EV = "xmlns:ev"
VALUE_XMLNS_EV = "http://www.w3.org/2001/xml-events"
ATTR_WIDTH = "width"
ATTR_HEIGHT = "height"
ATTR_VIEWBOX = "viewBox"
NAME_PATH = "path"
ATTR_DATA = "d"
ATTR_FILL = "fill"
ATTR_STROKE = "stroke"
ATTR_STROKE_WIDTH = "stroke-width"
ATTR_TRANSFORM = "transform"
VALUE_NONE = "none"
class SaxDocument:
def __init__(self, filename):
self.root_values = {}
self.tree = []
if filename is not None and os.path.dirname(filename) == '':
self.original_filename = os.path.join(os.getcwd(), filename)
else:
self.original_filename = filename
if filename is not None:
self.sax_parse(filename)
def sax_parse(self, filename):
self.root_values = {}
self.tree = []
stack = []
values = {}
matrix = None
for event, elem in iterparse(filename, events=('start', 'end')):
if event == 'start':
stack.append((values, matrix))
if matrix is not None:
matrix = matrix.copy()
current_values = values
values = {}
values.update(current_values)
attrs = elem.attrib
values.update(attrs)
name = elem.tag[28:]
if "style" in attrs:
for equate in attrs["style"].split(";"):
equal_item = equate.split(":")
values[equal_item[0]] = equal_item[1]
if "transform" in attrs:
transform_matrix = parse_transform(attrs["transform"])
if matrix is None:
matrix = np.identity(3)
matrix = transform_matrix.dot(matrix)
if "svg" == name:
current_values = values
values = {}
values.update(current_values)
self.root_values = current_values
continue
elif "g" == name:
continue
elif 'path' == name:
values['d'] = path2pathd(values)
elif 'circle' == name:
values["d"] = ellipse2pathd(values)
elif 'ellipse' == name:
values["d"] = ellipse2pathd(values)
elif 'line' == name:
values["d"] = line2pathd(values)
elif 'polyline' == name:
values["d"] = polyline2pathd(values['points'])
elif 'polygon' == name:
values["d"] = polygon2pathd(values['points'])
elif 'rect' == name:
values["d"] = rect2pathd(values)
else:
continue
values["matrix"] = matrix
values["name"] = name
self.tree.append(values)
else:
v = stack.pop()
values = v[0]
matrix = v[1]
def flatten_all_paths(self):
flat = []
for values in self.tree:
pathd = values['d']
matrix = values['matrix']
parsed_path = parse_path(pathd)
if matrix is not None:
transform(parsed_path, matrix)
flat.append(parsed_path)
return flat
def get_pathd_and_matrix(self):
flat = []
for values in self.tree:
pathd = values['d']
matrix = values['matrix']
flat.append((pathd, matrix))
return flat
def generate_dom(self):
root = Element(NAME_SVG)
root.set(ATTR_VERSION, VALUE_SVG_VERSION)
root.set(ATTR_XMLNS, VALUE_XMLNS)
root.set(ATTR_XMLNS_LINK, VALUE_XLINK)
root.set(ATTR_XMLNS_EV, VALUE_XMLNS_EV)
width = self.root_values.get(ATTR_WIDTH, None)
height = self.root_values.get(ATTR_HEIGHT, None)
if width is not None:
root.set(ATTR_WIDTH, width)
if height is not None:
root.set(ATTR_HEIGHT, height)
viewbox = self.root_values.get(ATTR_VIEWBOX, None)
if viewbox is not None:
root.set(ATTR_VIEWBOX, viewbox)
identity = np.identity(3)
for values in self.tree:
pathd = values.get('d', '')
matrix = values.get('matrix', None)
path = SubElement(root, NAME_PATH)
if matrix is not None and not np.all(np.equal(matrix, identity)):
matrix_string = "matrix("
matrix_string += " "
matrix_string += str(matrix[0][0])
matrix_string += " "
matrix_string += str(matrix[1][0])
matrix_string += " "
matrix_string += str(matrix[0][1])
matrix_string += " "
matrix_string += str(matrix[1][1])
matrix_string += " "
matrix_string += str(matrix[0][2])
matrix_string += " "
matrix_string += str(matrix[1][2])
matrix_string += ")"
path.set(ATTR_TRANSFORM, matrix_string)
if ATTR_DATA in values:
path.set(ATTR_DATA, values[ATTR_DATA])
if ATTR_FILL in values:
path.set(ATTR_FILL, values[ATTR_FILL])
if ATTR_STROKE in values:
path.set(ATTR_STROKE, values[ATTR_STROKE])
return ElementTree(root)
def save(self, filename):
with open(filename, 'wb') as output_svg:
dom_tree = self.generate_dom()
dom_tree.write(output_svg)
def display(self, filename=None):
if filename is None:
filename = 'display_temp.svg'
self.save(filename)
open_in_browser(filename)
| true | true |
1c46f578bdd65913273fe1b4661b4a5a024c948b | 301 | py | Python | 3. Python Advanced (September 2021)/3.2 Python OOP (October 2021)/01. First Steps In OOP/04_car.py | kzborisov/SoftUni | ccb2b8850adc79bfb2652a45124c3ff11183412e | [
"MIT"
] | 1 | 2021-02-07T07:51:12.000Z | 2021-02-07T07:51:12.000Z | 3. Python Advanced (September 2021)/3.2 Python OOP (October 2021)/01. First Steps In OOP/04_car.py | kzborisov/softuni | 9c5b45c74fa7d9748e9b3ea65a5ae4e15c142751 | [
"MIT"
] | null | null | null | 3. Python Advanced (September 2021)/3.2 Python OOP (October 2021)/01. First Steps In OOP/04_car.py | kzborisov/softuni | 9c5b45c74fa7d9748e9b3ea65a5ae4e15c142751 | [
"MIT"
] | null | null | null | class Car:
def __init__(self, name, model, engine):
self.name = name
self.model = model
self.engine = engine
def get_info(self):
return f"This is {self.name} {self.model} with engine {self.engine}"
car = Car("Kia", "Rio", "1.3L B3 I4")
print(car.get_info())
| 23.153846 | 76 | 0.598007 | class Car:
def __init__(self, name, model, engine):
self.name = name
self.model = model
self.engine = engine
def get_info(self):
return f"This is {self.name} {self.model} with engine {self.engine}"
car = Car("Kia", "Rio", "1.3L B3 I4")
print(car.get_info())
| true | true |
1c46f59fb85d988d23d303ed82be39df0f9802c3 | 1,990 | py | Python | contact_form/tests/views.py | nunataksoftware/django-contact-form-updated | ad3da22a6c12c78e59fe05bf4e4f9f5a1e654e03 | [
"BSD-3-Clause"
] | null | null | null | contact_form/tests/views.py | nunataksoftware/django-contact-form-updated | ad3da22a6c12c78e59fe05bf4e4f9f5a1e654e03 | [
"BSD-3-Clause"
] | null | null | null | contact_form/tests/views.py | nunataksoftware/django-contact-form-updated | ad3da22a6c12c78e59fe05bf4e4f9f5a1e654e03 | [
"BSD-3-Clause"
] | null | null | null | from django.conf import settings
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TestCase
class ViewTests(TestCase):
urls = 'contact_form.urls'
def test_get(self):
"""
HTTP GET on the form view just shows the form.
"""
contact_url = reverse('contact_form')
response = self.client.get(contact_url)
self.assertEqual(200, response.status_code)
self.assertTemplateUsed(response,
'contact_form/contact_form.html')
def test_send(self):
"""
Valid data through the view results in a successful send.
"""
contact_url = reverse('contact_form')
data = {'name': 'Test',
'email': 'test@example.com',
'body': 'Test message'}
response = self.client.post(contact_url,
data=data)
self.assertRedirects(response,
reverse('contact_form_sent'))
self.assertEqual(1, len(mail.outbox))
message = mail.outbox[0]
self.assertEqual([data['email']],
message.recipients())
self.assertTrue(data['body'] in message.body)
self.assertEqual(settings.DEFAULT_FROM_EMAIL,
message.from_email)
def test_invalid(self):
"""
Invalid data doesn't work.
"""
contact_url = reverse('contact_form')
data = {'name': 'Test',
'body': 'Test message'}
response = self.client.post(contact_url,
data=data)
self.assertEqual(200, response.status_code)
self.assertFormError(response,
'form',
'email',
'This field is required.')
self.assertEqual(0, len(mail.outbox))
| 29.701493 | 65 | 0.522613 | from django.conf import settings
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TestCase
class ViewTests(TestCase):
urls = 'contact_form.urls'
def test_get(self):
contact_url = reverse('contact_form')
response = self.client.get(contact_url)
self.assertEqual(200, response.status_code)
self.assertTemplateUsed(response,
'contact_form/contact_form.html')
def test_send(self):
contact_url = reverse('contact_form')
data = {'name': 'Test',
'email': 'test@example.com',
'body': 'Test message'}
response = self.client.post(contact_url,
data=data)
self.assertRedirects(response,
reverse('contact_form_sent'))
self.assertEqual(1, len(mail.outbox))
message = mail.outbox[0]
self.assertEqual([data['email']],
message.recipients())
self.assertTrue(data['body'] in message.body)
self.assertEqual(settings.DEFAULT_FROM_EMAIL,
message.from_email)
def test_invalid(self):
contact_url = reverse('contact_form')
data = {'name': 'Test',
'body': 'Test message'}
response = self.client.post(contact_url,
data=data)
self.assertEqual(200, response.status_code)
self.assertFormError(response,
'form',
'email',
'This field is required.')
self.assertEqual(0, len(mail.outbox))
| true | true |
1c46f61d2a6ed620777848b6db1e240c81c79142 | 16,339 | py | Python | cadnano/util.py | mctrinh/cadnano2.5 | d8254f24eef5fd77b4fb2b1a9642a8eea2e3c736 | [
"BSD-3-Clause"
] | 1 | 2022-03-27T14:37:32.000Z | 2022-03-27T14:37:32.000Z | cadnano/util.py | mctrinh/cadnano2.5 | d8254f24eef5fd77b4fb2b1a9642a8eea2e3c736 | [
"BSD-3-Clause"
] | null | null | null | cadnano/util.py | mctrinh/cadnano2.5 | d8254f24eef5fd77b4fb2b1a9642a8eea2e3c736 | [
"BSD-3-Clause"
] | 1 | 2021-01-22T02:29:38.000Z | 2021-01-22T02:29:38.000Z | """
util.py
"""
import argparse
import inspect
import logging
import logging.handlers
import os
import platform
import string
import sys
from os import path
from traceback import extract_stack
logger = logging.getLogger(__name__)
IS_PY_3 = int(sys.version_info[0] > 2)
def clamp(x, min_x, max_x):
if x < min_x:
return min_x
elif x > max_x:
return max_x
else:
return x
def overlap(x, y, a, b):
"""Finds the overlap of (x, y) and (a, b).
Assumes an overlap exists, i.e. y >= a and b >= x.
"""
c = clamp(x, a, b)
d = clamp(y, a, b)
return c, d
# end def
try:
from termcolor import colored
except ImportError:
print("pip3 install termcolor")
def colored(s, color=None, **kwargs):
return s
def trace(n):
"""Returns a stack trace n frames deep"""
s = extract_stack()
frames = []
for f in s[-n-1:-1]:
# f is a stack frame like
# ('/path/script.py', 42, 'funcname', 'current = line - of / code')
frames.append((colored(path.basename(f[0]) + ':%i' % f[1], 'blue') + '(' + colored(f[2], 'green') + ')'))
sep = colored(" > ", 'yellow')
return sep.join(frames)
if IS_PY_3:
complement = str.maketrans('ACGTacgt', 'TGCATGCA')
else:
complement = string.maketrans('ACGTacgt', 'TGCATGCA')
def rcomp(seqStr):
"""Returns the reverse complement of the sequence in seqStr."""
return seqStr.translate(complement)[::-1]
def comp(seqStr):
"""Returns the complement of the sequence in seqStr."""
return seqStr.translate(complement)
if IS_PY_3:
whitetoQ = str.maketrans(' |', '??')
else:
whitetoQ = string.maketrans(' |', '??')
def markwhite(seqStr):
return seqStr.translate(whitetoQ)
def nowhite(seqStr):
"""Gets rid of non-letters in a string."""
return ''.join([c for c in seqStr if c in string.letters])
def nearest(a, l): return min(l, key=lambda x: abs(x - a))
def isWindows():
"""Returns True if platform is detected as Windows, otherwise False"""
if platform.system() == 'Windows':
return True
else:
return False
def isMac():
"""Returns True if platform is detected as Darwin, otherwise False"""
try:
return platform.system() == 'Darwin'
except Exception:
return path.exists('/System/Library/CoreServices/Finder.app')
def isLinux():
"""Returns True if platform is detected as Linux, otherwise False"""
if platform.system() == 'Linux':
return True
else:
return False
def methodName():
"""Returns string containing name of the calling method."""
return inspect.stack()[1][3]
def execCommandList(model_object, commands, desc=None, use_undostack=True):
"""
This is a wrapper for performing QUndoCommands, meant to ensure
uniform handling of the undoStack and macro descriptions.
When using the undoStack, commands are pushed onto self.undoStack()
as part of a macro with description desc. Otherwise, command redo
methods are called directly.
"""
if use_undostack:
us = model_object.undoStack()
us.beginMacro(desc)
for c in commands:
us.push(c)
us.endMacro()
else:
for c in commands:
c.redo()
# end def
def doCmd(model_object, command, use_undostack):
"""Helper for pushing onto the undostack
"""
if use_undostack:
model_object.undoStack().push(command)
else:
command.redo()
# end def
def finalizeCommands(model_object, commands, desc=None):
"""Used to enable interaction with the model but not push
commands to the undostack. In practice:
1. Call a bunch of commands and don't push them to the undostack AKA:
cmd.redo()
2. call finalizeCommands() to push the cummulative change to the stack
This assumes that the UndoCommands provided this function respresent
a transition from the initial state to the final state
Note:
UndoCommands need to implement specialUndo (e.g. just call normal undo.)
"""
# 1. undo the command to get back to the initial _state
for c in commands:
c.specialUndo()
# c.undo()
# 2. push all the "undoable" commands to the undostac
model_object.undoStack().beginMacro(desc)
for c in commands:
model_object.undoStack().push(c)
model_object.undoStack().endMacro()
# end def
def this_path():
return os.path.abspath(os.path.dirname(__file__))
# maps plugin path (extension stripped) -> plugin module
loadedPlugins = {}
def unloadedPlugins():
"""Returns a list of plugin paths that have yet to
be loaded but are in the top level of one of the
search directories specified in pluginDirs"""
internalPlugins = os.path.join(this_path(), 'plugins')
pluginDirs = [internalPlugins]
results = []
for pluginDir in pluginDirs:
if not os.path.isdir(pluginDir):
continue
for dirent in os.listdir(pluginDir):
f = os.path.join(pluginDir, dirent)
isfile = os.path.isfile(f)
hasValidSuffix = dirent.endswith(('.py', '.so'))
if isfile and hasValidSuffix:
results.append(f)
if os.path.isdir(f) and\
os.path.isfile(os.path.join(f, '__init__.py')):
results.append(f)
return list(filter(lambda x: x not in loadedPlugins, results))
def loadPlugin(f):
pass
# path, fname = os.path.split(f)
# name, ext = os.path.splitext(fname)
# pluginKey = os.path.join(path, name)
# try:
# mod = loadedPlugins[pluginKey]
# return mod
# except KeyError:
# pass
# file, filename, data = imp.find_module(name, [path])
# mod = imp.load_module(name, file, filename, data)
# loadedPlugins[pluginKey] = mod
# return mod
def loadAllPlugins():
loadedAPlugin = False
for p in unloadedPlugins():
loadPlugin(p)
loadedAPlugin = True
return loadedAPlugin
def beginSuperMacro(model_object, desc=None):
"""
SuperMacros can be used to nest multiple command lists.
Normally execCommandList macros all the commands in a list.
In some cases, multiple command lists need to be executed separately
because of dependency issues. (e.g. in part.autoStaple, strands
must be completely 1. created and 2. split before 3. xover installation.)
"""
model_object.undoStack().beginMacro(desc)
# end def
def endSuperMacro(model_object):
"""Ends a SuperMacro. Should be called after beginSuperMacro."""
model_object.undoStack().endMacro()
# end def
def findChild(self):
"""When called when self is a QGraphicsItem, iterates through self's
childItems(), placing a red rectangle (a sibling of self) around
each item in sequence (press return to move between items). Since
the index of each child item is displayed as it is highlighted,
one can use findChild() to quickly get a reference to one of self's
children. At each step, one can type a command letter before
hitting return. The command will apply to the current child.
Command Letter: Action:
<return> Advance to next child
s<return> Show current child
S<return> Show current child, hide siblings
h<return> Hide current child
r<return> return current child
"""
from PyQt5.QtWidgets import QGraphicsRectItem
from PyQt5.QtGui import QPen
from PyQt5.QtCore import Qt
children = self.childItems()
parent = self.parentItem()
childVisibility = [(child, child.isVisible()) for child in children]
for n in range(len(children)):
child = children[n]
print("Highlighting %s.childItems()[%i] = %s" % (self, n, child))
childBR = child.mapToItem(parent, child.boundingRect())
childBR = childBR.boundingRect() # xform gives us a QPolygonF
debugHighlighter = QGraphicsRectItem(childBR, parent)
debugHighlighter.setPen(QPen(Qt.red))
debugHighlighter.setZValue(9001)
while True:
# wait for return to be pressed while spinning the event loop.
# also process single-character commands.
command = raw_input()
if command == 's': # Show current child
child.show()
elif command == 'h': # Hde current child
child.hide()
elif command == 'S': # Show only current child
for c in children:
c.hide()
child.show()
elif command == 'r': # Return current child
for child, wasVisible in childVisibility:
child.setVisible(wasVisible)
return child
else:
break
debugHighlighter.scene().removeItem(debugHighlighter)
for child, wasVisible in childVisibility:
child.setVisible(wasVisible)
# end def
def parse_args(argv=None, gui=None):
"""Uses argparse to process commandline arguments.
Returns:
NameSpace object. This can easily be converted to a regular dict through:
argns.__dict__
This also presents a nice command line help to the user, exposed with --help flag:
python main.py --help
If gui is set to "qt", then the parser will use parse_known_args. Unlike
parse_args(), parse_known_args() will not cause abort by show the help
message and exit, if it finds any unrecognized command-line arguments.
Alternatively, you can initialize your app via:
app = QApplication(sys.argv)
parse_args(app.arguments())
QApplication.arguments() returns a list of arguments with all Qt arguments
stripped away. Qt command line args include:
-style=<style> -stylesheet=<stylesheet> -widgetcount -reverse -qmljsdebugger -session=<session>
"""
parser = argparse.ArgumentParser(description="cadnano 2.5")
parser.add_argument("--testing", "-t", action="store_true", help="Enable testing mode/environment.")
parser.add_argument("--profile", "-p", action="store_true", help="Profile app execution.")
parser.add_argument("--print-stats", "-P", action="store_true", help="Print profiling statistics.")
parser.add_argument("--interactive", "-i", action="store_true", help="Enable interactive (console) mode.")
parser.add_argument('--loglevel',
help="Specify logging level. Can be either DEBUG, INFO, WARNING, ERROR or any integer.")
parser.add_argument("--debug-modules", nargs='*', metavar="MODULE-STR",
help="Debug modules whose names start with any of the given strings. For instance, to "
"debug the cadnano file decoder, use --debug-modules cadnano.fileio.decode ."
"To debug all gui modules, use --debug-modules cadnano.gui .")
parser.add_argument("--file", "-f", metavar="designfile.json", help="cadnano design to load upon start up.")
if gui and (gui is True or gui.lower() == "qt"):
# Command line args might include Qt-specific switches and parameters.
argns, unused = parser.parse_known_args(argv)
else:
argns, unused = parser.parse_args(argv), None
return argns, unused
def init_logging(args=None, logdir=None):
"""Set up standard logging system based on parameters in args, e.g. loglevel and testing.
"""
if args is None:
args = {}
if logdir is None:
appname = "cadnano"
try:
import appdirs
logdir = appdirs.user_log_dir(appname)
except ImportError:
if os.environ.get('APPDATA'):
logdir = os.path.join(os.environ['APPDATA'], appname, "Logs")
elif sys.platform == 'darwin':
logdir = os.path.join(os.path.expanduser("~"), "Library", "Logs", appname)
else:
logdir = os.path.join(os.path.expanduser("~"), "."+appname, "logs")
if not os.path.exists(logdir):
os.makedirs(logdir)
logfilepath = os.path.join(logdir, appname+".log")
# We want different output formatting for file vs console logging output.
# File logs should be simple and easy to regex; console logs should be short and nice on the eyes
logfilefmt = "%(asctime)s %(levelname)-6s - %(name)s:%(lineno)s - %(funcName)s() - %(message)s"
logdatefmt = "%Y%m%d-%H:%M:%S"
loguserfmt = "%(asctime)s %(levelname)-5s %(module)30s:%(lineno)-4s%(funcName)16s() %(message)s"
logtimefmt = "%H:%M:%S" # Nice for output to user in console and testing.
# See https://docs.python.org/3/library/logging.html#logrecord-attributes for full list of attributes
# Loglevel (for console messages)
if args.get('loglevel'):
try:
loglevel = int(args['loglevel'])
except (TypeError, ValueError):
loglevel = getattr(logging, args['loglevel'].upper())
else:
loglevel = logging.DEBUG if args.get('testing') else logging.WARNING
if args.get('basic_logging', False):
logging.basicConfig(level=loglevel,
format=loguserfmt,
datefmt=logtimefmt,
filename=logfilepath)
logger.debug("Logging system initialized with loglevel %s", loglevel)
else:
# Set up custom logger:
logging.root.setLevel(logging.DEBUG)
# Add a rotating file handler:
logfilehandler = logging.handlers.RotatingFileHandler(logfilepath, maxBytes=2*2**20, backupCount=2)
logfileformatter = logging.Formatter(fmt=logfilefmt, datefmt=logdatefmt)
logfilehandler.setFormatter(logfileformatter)
logging.root.addHandler(logfilehandler)
print("Logging to file:", logfilepath)
# Add a custom StreamHandler for outputting to the console (default level is 0 = ANY)
logstreamhandler = logging.StreamHandler() # default stream is sys.stderr
logging.root.addHandler(logstreamhandler)
logstreamformatter = logging.Formatter(loguserfmt, logtimefmt)
logstreamhandler.setFormatter(logstreamformatter)
# Set filter for debugging:
if args.get('debug_modules'):
def module_debug_filter(record):
"""
All Filters attached to a logger or handler are asked.
The record is discarted if any of the attached Filters return False.
"""
return any(record.name.startswith(modstr) for modstr in args['debug_modules']) \
or record.levelno >= loglevel
logstreamhandler.addFilter(module_debug_filter)
# Default level is 0, which is appropriate when using module_debug_filter
else:
# only set a min level if we are not using module_debug_filter. (Level is an additional filter.)
logstreamhandler.setLevel(loglevel)
logger.info("Logging system initialized...")
def read_fasta(fp):
name, seq = None, []
for line in fp:
line = line.rstrip()
if line.startswith(">"):
if name:
yield (name, ''.join(seq))
name, seq = line, []
else:
seq.append(line)
if name:
yield (name, ''.join(seq))
def qtdb_trace():
"""Make PDB usable by calling pyqtRemoveInputHook.
Otherwise, PDB is useless as the message
> QCoreApplication::exec: The event loop is already running
is spammed to the console.
When done, call qtdb_resume from the PDB prompt to return things back to
normal.
Note that PDB will drop you into the current frame (this function) and
hitting 'n' is required to return to the frame you wanted PDB originally.
This could probably be optimized at some point to manipulate the frame PDB
starts in.
"""
if False:
logger.info('No debug')
return
else:
import pdb
from PyQt5.QtCore import pyqtRemoveInputHook
pyqtRemoveInputHook()
pdb.set_trace()
def qtdb_resume():
"""Resume normal PyQt operations after calling qtdb_trace.
Note that this function assumes that pyqtRemoveInputHook has been called
"""
from PyQt5.QtCore import pyqtRestoreInputHook
pyqtRestoreInputHook()
| 34.253669 | 113 | 0.63988 | import argparse
import inspect
import logging
import logging.handlers
import os
import platform
import string
import sys
from os import path
from traceback import extract_stack
logger = logging.getLogger(__name__)
IS_PY_3 = int(sys.version_info[0] > 2)
def clamp(x, min_x, max_x):
if x < min_x:
return min_x
elif x > max_x:
return max_x
else:
return x
def overlap(x, y, a, b):
c = clamp(x, a, b)
d = clamp(y, a, b)
return c, d
try:
from termcolor import colored
except ImportError:
print("pip3 install termcolor")
def colored(s, color=None, **kwargs):
return s
def trace(n):
s = extract_stack()
frames = []
for f in s[-n-1:-1]:
frames.append((colored(path.basename(f[0]) + ':%i' % f[1], 'blue') + '(' + colored(f[2], 'green') + ')'))
sep = colored(" > ", 'yellow')
return sep.join(frames)
if IS_PY_3:
complement = str.maketrans('ACGTacgt', 'TGCATGCA')
else:
complement = string.maketrans('ACGTacgt', 'TGCATGCA')
def rcomp(seqStr):
return seqStr.translate(complement)[::-1]
def comp(seqStr):
return seqStr.translate(complement)
if IS_PY_3:
whitetoQ = str.maketrans(' |', '??')
else:
whitetoQ = string.maketrans(' |', '??')
def markwhite(seqStr):
return seqStr.translate(whitetoQ)
def nowhite(seqStr):
return ''.join([c for c in seqStr if c in string.letters])
def nearest(a, l): return min(l, key=lambda x: abs(x - a))
def isWindows():
if platform.system() == 'Windows':
return True
else:
return False
def isMac():
try:
return platform.system() == 'Darwin'
except Exception:
return path.exists('/System/Library/CoreServices/Finder.app')
def isLinux():
if platform.system() == 'Linux':
return True
else:
return False
def methodName():
return inspect.stack()[1][3]
def execCommandList(model_object, commands, desc=None, use_undostack=True):
if use_undostack:
us = model_object.undoStack()
us.beginMacro(desc)
for c in commands:
us.push(c)
us.endMacro()
else:
for c in commands:
c.redo()
def doCmd(model_object, command, use_undostack):
if use_undostack:
model_object.undoStack().push(command)
else:
command.redo()
def finalizeCommands(model_object, commands, desc=None):
for c in commands:
c.specialUndo()
model_object.undoStack().beginMacro(desc)
for c in commands:
model_object.undoStack().push(c)
model_object.undoStack().endMacro()
def this_path():
return os.path.abspath(os.path.dirname(__file__))
loadedPlugins = {}
def unloadedPlugins():
internalPlugins = os.path.join(this_path(), 'plugins')
pluginDirs = [internalPlugins]
results = []
for pluginDir in pluginDirs:
if not os.path.isdir(pluginDir):
continue
for dirent in os.listdir(pluginDir):
f = os.path.join(pluginDir, dirent)
isfile = os.path.isfile(f)
hasValidSuffix = dirent.endswith(('.py', '.so'))
if isfile and hasValidSuffix:
results.append(f)
if os.path.isdir(f) and\
os.path.isfile(os.path.join(f, '__init__.py')):
results.append(f)
return list(filter(lambda x: x not in loadedPlugins, results))
def loadPlugin(f):
pass
def loadAllPlugins():
loadedAPlugin = False
for p in unloadedPlugins():
loadPlugin(p)
loadedAPlugin = True
return loadedAPlugin
def beginSuperMacro(model_object, desc=None):
model_object.undoStack().beginMacro(desc)
def endSuperMacro(model_object):
model_object.undoStack().endMacro()
def findChild(self):
from PyQt5.QtWidgets import QGraphicsRectItem
from PyQt5.QtGui import QPen
from PyQt5.QtCore import Qt
children = self.childItems()
parent = self.parentItem()
childVisibility = [(child, child.isVisible()) for child in children]
for n in range(len(children)):
child = children[n]
print("Highlighting %s.childItems()[%i] = %s" % (self, n, child))
childBR = child.mapToItem(parent, child.boundingRect())
childBR = childBR.boundingRect()
debugHighlighter = QGraphicsRectItem(childBR, parent)
debugHighlighter.setPen(QPen(Qt.red))
debugHighlighter.setZValue(9001)
while True:
command = raw_input()
if command == 's':
child.show()
elif command == 'h':
child.hide()
elif command == 'S':
for c in children:
c.hide()
child.show()
elif command == 'r':
for child, wasVisible in childVisibility:
child.setVisible(wasVisible)
return child
else:
break
debugHighlighter.scene().removeItem(debugHighlighter)
for child, wasVisible in childVisibility:
child.setVisible(wasVisible)
def parse_args(argv=None, gui=None):
parser = argparse.ArgumentParser(description="cadnano 2.5")
parser.add_argument("--testing", "-t", action="store_true", help="Enable testing mode/environment.")
parser.add_argument("--profile", "-p", action="store_true", help="Profile app execution.")
parser.add_argument("--print-stats", "-P", action="store_true", help="Print profiling statistics.")
parser.add_argument("--interactive", "-i", action="store_true", help="Enable interactive (console) mode.")
parser.add_argument('--loglevel',
help="Specify logging level. Can be either DEBUG, INFO, WARNING, ERROR or any integer.")
parser.add_argument("--debug-modules", nargs='*', metavar="MODULE-STR",
help="Debug modules whose names start with any of the given strings. For instance, to "
"debug the cadnano file decoder, use --debug-modules cadnano.fileio.decode ."
"To debug all gui modules, use --debug-modules cadnano.gui .")
parser.add_argument("--file", "-f", metavar="designfile.json", help="cadnano design to load upon start up.")
if gui and (gui is True or gui.lower() == "qt"):
argns, unused = parser.parse_known_args(argv)
else:
argns, unused = parser.parse_args(argv), None
return argns, unused
def init_logging(args=None, logdir=None):
if args is None:
args = {}
if logdir is None:
appname = "cadnano"
try:
import appdirs
logdir = appdirs.user_log_dir(appname)
except ImportError:
if os.environ.get('APPDATA'):
logdir = os.path.join(os.environ['APPDATA'], appname, "Logs")
elif sys.platform == 'darwin':
logdir = os.path.join(os.path.expanduser("~"), "Library", "Logs", appname)
else:
logdir = os.path.join(os.path.expanduser("~"), "."+appname, "logs")
if not os.path.exists(logdir):
os.makedirs(logdir)
logfilepath = os.path.join(logdir, appname+".log")
logfilefmt = "%(asctime)s %(levelname)-6s - %(name)s:%(lineno)s - %(funcName)s() - %(message)s"
logdatefmt = "%Y%m%d-%H:%M:%S"
loguserfmt = "%(asctime)s %(levelname)-5s %(module)30s:%(lineno)-4s%(funcName)16s() %(message)s"
logtimefmt = "%H:%M:%S"
loglevel = int(args['loglevel'])
except (TypeError, ValueError):
loglevel = getattr(logging, args['loglevel'].upper())
else:
loglevel = logging.DEBUG if args.get('testing') else logging.WARNING
if args.get('basic_logging', False):
logging.basicConfig(level=loglevel,
format=loguserfmt,
datefmt=logtimefmt,
filename=logfilepath)
logger.debug("Logging system initialized with loglevel %s", loglevel)
else:
logging.root.setLevel(logging.DEBUG)
logfilehandler = logging.handlers.RotatingFileHandler(logfilepath, maxBytes=2*2**20, backupCount=2)
logfileformatter = logging.Formatter(fmt=logfilefmt, datefmt=logdatefmt)
logfilehandler.setFormatter(logfileformatter)
logging.root.addHandler(logfilehandler)
print("Logging to file:", logfilepath)
logstreamhandler = logging.StreamHandler()
logging.root.addHandler(logstreamhandler)
logstreamformatter = logging.Formatter(loguserfmt, logtimefmt)
logstreamhandler.setFormatter(logstreamformatter)
if args.get('debug_modules'):
def module_debug_filter(record):
"""
All Filters attached to a logger or handler are asked.
The record is discarted if any of the attached Filters return False.
"""
return any(record.name.startswith(modstr) for modstr in args['debug_modules']) \
or record.levelno >= loglevel
logstreamhandler.addFilter(module_debug_filter)
else:
logstreamhandler.setLevel(loglevel)
logger.info("Logging system initialized...")
def read_fasta(fp):
name, seq = None, []
for line in fp:
line = line.rstrip()
if line.startswith(">"):
if name:
yield (name, ''.join(seq))
name, seq = line, []
else:
seq.append(line)
if name:
yield (name, ''.join(seq))
def qtdb_trace():
if False:
logger.info('No debug')
return
else:
import pdb
from PyQt5.QtCore import pyqtRemoveInputHook
pyqtRemoveInputHook()
pdb.set_trace()
def qtdb_resume():
from PyQt5.QtCore import pyqtRestoreInputHook
pyqtRestoreInputHook()
| true | true |
1c46fa3e618557a23f27ae9321e98729cbf11428 | 37 | py | Python | src/trex/error.py | cnk113/TREX | add83d8108f3602c5bbe7b37f60ff19f89b2236d | [
"MIT"
] | null | null | null | src/trex/error.py | cnk113/TREX | add83d8108f3602c5bbe7b37f60ff19f89b2236d | [
"MIT"
] | 1 | 2022-03-18T01:56:53.000Z | 2022-03-24T19:35:58.000Z | src/trex/error.py | cnk113/TREX | add83d8108f3602c5bbe7b37f60ff19f89b2236d | [
"MIT"
] | 1 | 2022-03-23T03:07:42.000Z | 2022-03-23T03:07:42.000Z | class TrexError(Exception):
pass
| 12.333333 | 27 | 0.72973 | class TrexError(Exception):
pass
| true | true |
1c46fc394f4f2e4a1722f7dab063575db81ae159 | 2,360 | py | Python | rematchrSite/rematchrApp/migrations/0003_auto_20150319_1243.py | ctames/rematchr | 4a22c3e4b1c22b64008e4996bdde9d4657c5294b | [
"MIT"
] | null | null | null | rematchrSite/rematchrApp/migrations/0003_auto_20150319_1243.py | ctames/rematchr | 4a22c3e4b1c22b64008e4996bdde9d4657c5294b | [
"MIT"
] | null | null | null | rematchrSite/rematchrApp/migrations/0003_auto_20150319_1243.py | ctames/rematchr | 4a22c3e4b1c22b64008e4996bdde9d4657c5294b | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('rematchrApp', '0002_auto_20150226_1336'),
]
operations = [
migrations.AddField(
model_name='conference',
name='user',
field=models.ForeignKey(null=True, to=settings.AUTH_USER_MODEL, unique=True),
preserve_default=True,
),
migrations.AddField(
model_name='reviewer',
name='doc_texts',
field=models.TextField(default=b'', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='reviewer',
name='doc_urls',
field=models.TextField(default=b'', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='conference',
name='title',
field=models.CharField(max_length=256),
preserve_default=True,
),
migrations.AlterField(
model_name='researcher',
name='doc_texts',
field=models.TextField(default=b'', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='researcher',
name='doc_urls',
field=models.TextField(default=b'', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='researcher',
name='firstname',
field=models.CharField(max_length=256),
preserve_default=True,
),
migrations.AlterField(
model_name='researcher',
name='lastname',
field=models.CharField(max_length=256),
preserve_default=True,
),
migrations.AlterField(
model_name='reviewer',
name='firstname',
field=models.CharField(max_length=256),
preserve_default=True,
),
migrations.AlterField(
model_name='reviewer',
name='lastname',
field=models.CharField(max_length=256),
preserve_default=True,
),
]
| 30.649351 | 89 | 0.563559 |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('rematchrApp', '0002_auto_20150226_1336'),
]
operations = [
migrations.AddField(
model_name='conference',
name='user',
field=models.ForeignKey(null=True, to=settings.AUTH_USER_MODEL, unique=True),
preserve_default=True,
),
migrations.AddField(
model_name='reviewer',
name='doc_texts',
field=models.TextField(default=b'', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='reviewer',
name='doc_urls',
field=models.TextField(default=b'', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='conference',
name='title',
field=models.CharField(max_length=256),
preserve_default=True,
),
migrations.AlterField(
model_name='researcher',
name='doc_texts',
field=models.TextField(default=b'', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='researcher',
name='doc_urls',
field=models.TextField(default=b'', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='researcher',
name='firstname',
field=models.CharField(max_length=256),
preserve_default=True,
),
migrations.AlterField(
model_name='researcher',
name='lastname',
field=models.CharField(max_length=256),
preserve_default=True,
),
migrations.AlterField(
model_name='reviewer',
name='firstname',
field=models.CharField(max_length=256),
preserve_default=True,
),
migrations.AlterField(
model_name='reviewer',
name='lastname',
field=models.CharField(max_length=256),
preserve_default=True,
),
]
| true | true |
1c46fd08a6227a33592d9bcc9675ca8b875b746f | 13,736 | py | Python | src/part2.py | shelonsky/Spark-Project-on-Demographic-Analysis-of-Turkey | 91a6d28e125bdd14b5b44a1ea426c2728b7aa9c3 | [
"MIT"
] | 1 | 2021-12-30T14:19:18.000Z | 2021-12-30T14:19:18.000Z | src/part2.py | shelonsky/Spark-Project-on-Demographic-Analysis-of-Turkey | 91a6d28e125bdd14b5b44a1ea426c2728b7aa9c3 | [
"MIT"
] | null | null | null | src/part2.py | shelonsky/Spark-Project-on-Demographic-Analysis-of-Turkey | 91a6d28e125bdd14b5b44a1ea426c2728b7aa9c3 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# @Time : 2021/5/30 16:06
# @Author : Xiao Lulu
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import pyspark.sql.functions as F
from pyspark.sql import Row
from pyspark.sql.functions import *
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
import re
from pyspark.sql.types import *
from pyspark.sql.window import Window
from pyspark.sql.functions import rank, col
from pyspark.ml import Pipeline
from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler
from pyspark.ml.feature import RFormula
from pyspark.ml.classification import LogisticRegression
from pyspark.ml import Pipeline
# import spark.implicits._
sparkconf = SparkConf().setAppName('Mernis')
sparkconf.set('spark.executor.memory', '10g')
sparkconf.set('spark.driver.memory', '10g')
sparkconf.set("spark.sql.debug.maxToStringFields", "100")
spark = (SparkSession
.builder
.appName("Mernis")
.config(conf=sparkconf)
.getOrCreate())
# sc = SparkContext.getOrCreate()
# 加载数据
file_path = '/root/myfile/mernis/data_dump.sql'
data = spark.sparkContext.textFile(file_path). \
filter((lambda line: re.findall('^\d{6}', line))). \
map(lambda line: line.split('\t')[:-1])
schema = "uid STRING, national_identifier STRING, first STRING, last STRING, mother_first STRING, " \
"father_first STRING, gender STRING, birth_city STRING, date_of_birth STRING," \
"id_registration_city STRING, id_registration_district STRING, address_city STRING," \
"address_district STRING, address_neighborhood STRING,street_address STRING," \
"door_or_entrance_number STRING"
df = spark.createDataFrame(data, schema)
# total_count = df.count() # total_count = 49611709
def format_date(line):
li = line.split('/')
if len(li[2]) == 4 and 0 < len(li[1]) <= 2 and 0 < len(li[1]) <= 2:
return li[2] + '-' + li[1].zfill(2) + '-' + li[0].zfill(2)
else:
return 'null'
format_date_udf = udf(format_date, returnType=StringType())
df.createOrReplaceTempView('citizens')
df_format_date = df.withColumn("date_of_birth", format_date_udf(df["date_of_birth"]))
df_format_date = df_format_date.filter(expr("""date_of_birth != 'null'"""))
df_format_date = df_format_date.withColumn('date_of_birth', to_date('date_of_birth')).\
withColumn('month_of_birth',month('date_of_birth')).\
withColumn('year_of_birth', year('date_of_birth'))
df_format_date.show(3)
###TODO: N6 计算前10大人口城市人口密度,其中城市的面积可Google搜索,面积单位使用平方千米;
def N6():
print('=' * 20, 'problem N6', '=' * 20)
# The top10 city with most citizens
df_n6 = df_format_date. \
select('address_city'). \
groupBy('address_city'). \
agg(count('*').alias('total')). \
orderBy('total', ascending=False). \
limit(10)
sc = SparkContext.getOrCreate()
area = [('ADANA', 14030), ('ISTANBUL', 5343), ('BURSA', 10891), ('IZMIR', 7340), ('AYDIN', 8007),
('ANKARA', 30715), ('ANTALYA', 1417), ('KOCAELI', 3418), ('KONYA', 38257), ('MERSIN', 15737)]
df_area = spark.createDataFrame(area, ['address_city', 'area'])
df_area = df_n6.join(df_area, 'address_city', 'left_outer').orderBy('area')
df_area.show(10)
density_df = df_area.withColumn('desity', round(df_area['total'] / df_area['area'], 2))
density_df.show(10)
N6()
## TODO: N7 根据人口的出身地和居住地,分别统计土耳其跨行政区流动人口和跨城市流动人口占总人口的 比例
def N7():
print('=' * 20, 'problem N7', '=' * 20)
total_num = 49611709
df_n7_district = df_format_date. \
select('id_registration_district', 'address_district'). \
filter(col('id_registration_district') != col('address_district'))
propor_district = df_n7_district.count() / total_num
print('Proportion of cross-district floating population:%.3f' % propor_district)
df_n7_city = df_format_date. \
select('id_registration_city', 'address_city'). \
filter(col('id_registration_city') != col('address_city'))
propor_city = df_n7_city.count() / total_num
print('Proportion of cross-city floating population:%.3f' % propor_city)
N7()
# 将出生日期中的年和月提取出来构成新的列,'year_of_birth'和'month_of_birth',
# 以便于转换成特征。由于总的数据量过大,从中抽取出4900余份样本进行训练和预测。
df_h1 = df_format_date.sample(False, 0.00005, seed=2018)
df_h1.show(10)
df_h1 = df_h1.dropna()
print(df_h1.count())
feature_col = ['first', 'last', 'mother_first', 'father_first', 'gender', 'birth_city',
'month_of_birth', 'year_of_birth', 'id_registration_city', 'id_registration_district',
'address_district', 'address_neighborhood', 'street_address', 'address_city'
]
indexOutputCols = [x + '_Index' for x in feature_col]
oheOutputCols = [x + '_OHE' for x in feature_col]
stringIndexer_features = StringIndexer(inputCols=feature_col, outputCols=indexOutputCols,
handleInvalid="skip")
oheEncoder_features = OneHotEncoder(inputCols=indexOutputCols, outputCols=oheOutputCols)
pipeline = Pipeline(stages=[stringIndexer_features, oheEncoder_features])
model = pipeline.fit(df_h1)
res = model.transform(df_h1)
# Split the dataset into training, validation and test set with prob 0.7,0.2 and 0.1.
(trainingData, validData, testData) = res.randomSplit([0.7, 0.2, 0.1], seed=100)
trainingData.persist()
validData.persist()
testData.persist()
#
# TODO: H1. 某人所在城市的预测模型:给定一个人的所有信息(除了所在城市),预测这个人所在的城市。 分析该模型Top1到 Top
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
# 增加一列labels, 保留address_city的onehot编码
def H1():
print('=' * 20, 'problem H1', '=' * 20)
feature_col = ['first', 'last', 'mother_first', 'father_first', 'gender', 'birth_city',
'month_of_birth', 'year_of_birth', 'id_registration_city', 'id_registration_district',
'address_district', 'address_neighborhood', 'street_address'
]
# All the feature columns
oheOutputCols = [x + '_OHE' for x in feature_col]
# assemble all the feature columns
vecAssembler = VectorAssembler(inputCols=oheOutputCols, outputCol='features')
df_h1 = vecAssembler.transform(trainingData)
lr = LogisticRegression(featuresCol='features', labelCol='address_city_Index',
maxIter=100, regParam=0.3, elasticNetParam=0)
lrPipeline = Pipeline(stages=[vecAssembler, lr])
lrModel = lrPipeline.fit(trainingData)
def evaluate_h1(data, model):
print(model)
vecData = vecAssembler.transform(data)
predictions = model.transform(vecData)
predictions. \
select('national_identifier', 'probability', 'address_city_Index', 'prediction'). \
orderBy('probability', ascending=False). \
show(n=5, truncate=30)
evaluator = MulticlassClassificationEvaluator(labelCol='address_city_Index', predictionCol='prediction')
lrAcc = evaluator.evaluate(predictions)
print('test accuracy = ', lrAcc)
evaluate_h1(validData, lrModel)
# 设置不同超参数
lr.setRegParam(0.001)
lrPipeline = Pipeline(stages=[vecAssembler, lr])
lrModel = lrPipeline.fit(trainingData)
evaluate_h1(validData, lrModel)
lr.setRegParam(0.01)
lrPipeline = Pipeline(stages=[vecAssembler, lr])
lrModel = lrPipeline.fit(trainingData)
evaluate_h1(validData, lrModel)
evaluate_h1(testData, lrModel)
H1()
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
### TODO: H2. Given all the information about one person, predict his/her gender.
def H2():
print('=' * 20, 'problem H2', '=' * 20)
feature_col = ['first', 'last', 'mother_first', 'father_first', 'birth_city', 'year_of_birth', 'month_of_birth',
'id_registration_city', 'id_registration_district', 'address_city',
'address_district', 'address_neighborhood', 'street_address'
]
# All the feature columns
oheOutputCols = [x + '_OHE' for x in feature_col]
vecAssembler = VectorAssembler(inputCols=oheOutputCols, outputCol='features')
lr_h2 = LogisticRegression(featuresCol='features', labelCol='gender_Index',
maxIter=100, regParam=0.01, elasticNetParam=0)
lrPipeline_h2 = Pipeline(stages=[vecAssembler, lr_h2])
lrModel_h2 = lrPipeline_h2.fit(trainingData)
def evaluate_h2(data, model):
predictions = model.transform(data)
predictions. \
select('national_identifier', 'probability', 'gender', 'gender_Index', 'prediction'). \
orderBy('probability', ascending=False). \
show(n=10, truncate=30)
evaluator = MulticlassClassificationEvaluator(labelCol='gender_Index', predictionCol='prediction')
lrAcc = evaluator.evaluate(predictions)
print('test accuracy = ', lrAcc)
evaluate_h2(validData, lrModel_h2)
lrPipeline_h2 = Pipeline(stages=[vecAssembler, lr_h2])
lrModel_h2 = lrPipeline_h2.fit(trainingData)
evaluate_h2(testData, lrModel_h2)
H2()
# H3. 姓名预测模型:假设给定一个人的所有信息(除了姓名),预测这个人最可能的姓氏。分析该 模型Top1到 Top 5的预测准确度;
def H3():
print('=' * 20, 'problem H3', '=' * 20)
feature_col = ['mother_first', 'father_first', 'birth_city', 'gender', 'year_of_birth', 'month_of_birth',
'id_registration_city', 'id_registration_district', 'address_city',
'address_district', 'address_neighborhood', 'street_address'
]
# 所有的特征列列名
oheOutputCols = [x + '_OHE' for x in feature_col]
# assemble all the feature columns
vecAssembler = VectorAssembler(inputCols=oheOutputCols, outputCol='features')
vecTrainDF_h3 = vecAssembler.transform(trainingData)
trainingData.show(3)
lr_h3 = LogisticRegression(featuresCol='features', labelCol='first_Index',
maxIter=100, regParam=0.01, elasticNetParam=0)
# lrPipeline_h3 = Pipeline(stages = [vecAssembler,lr_h3])
lrModel_h3 = lr_h3.fit(vecTrainDF_h3)
def evaluate_h3(data):
print(lrModel_h3)
vecData = vecAssembler.transform(data)
predictions = lrModel_h3.transform(vecData)
predictions.select('national_identifier', 'probability', 'first', 'first_Index', 'prediction').orderBy(
'probability', ascending=False).show(n=10, truncate=30)
evaluator = MulticlassClassificationEvaluator(labelCol='first_Index', predictionCol='prediction')
lrAcc = evaluator.evaluate(predictions)
print('test accuracy = ', lrAcc)
evaluate_h3(validData)
evaluate_h3(testData)
# H3()
# TODO: H4. 人口预测模型:统计每一年出生的人数,预测下一年新增人口数。
from pyspark.sql.types import FloatType
from math import log
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.regression import LinearRegression
from pyspark.ml.feature import VectorAssembler
def H4():
print('='*2,'problem H4','='*20)
df_h4 = df_format_date.withColumn(
'year_of_birth', year('date_of_birth'))
df_population = df_h4.select("year_of_birth").groupBy('year_of_birth').agg(count('*').alias('total'))
df_population = df_population.withColumn('year', df_population['year_of_birth'].cast('int')).drop('year_of_birth')
df_population = df_population.filter(df_population['year'] > 1700)
df_population.orderBy('total').show(10)
def to_index(year):
return year - 1888
to_index_udf = udf(to_index, returnType=IntegerType())
min_year = df_population.select(min('year').alias('year')).collect()[0]
print(min_year)
new_df = df_population.withColumn('index', to_index_udf(df_population['year']))
new_df.show()
(trianing, test) = new_df.randomSplit([0.8, 0.2], seed=2020)
trianing.persist()
test.persist()
### linear regression
vecAssembler = VectorAssembler(inputCols=['index'],outputCol='features')
vecTrainDF = vecAssembler.transform(trianing)
lr_h4 = LinearRegression(featuresCol='features',labelCol='total')
lrModel_h4 = lr_h4.fit(vecTrainDF)
m = lrModel_h4.coefficients[0]
b = lrModel_h4.intercept
print(f"""The formula for the linear regression lines is num = {m:.2f}*index{b:.2f}""")
vecTestDF = vecAssembler.transform(test)
predictions = lrModel_h4.transform(vecTestDF)
predictions.orderBy('prediction', ascending=False).show(5)
regresssionEvaluator = RegressionEvaluator(predictionCol='prediction', labelCol='total', metricName='r2')
r2 = regresssionEvaluator.evaluate(predictions)
print(f"r2 is {r2}")
### LR with Malthus model
def log_num(num):
if num:
return log(num)
else:
return 0
log_num_udf = udf(log_num, returnType=FloatType())
log_df = new_df.withColumn('logTotal', log_num_udf(new_df['total']))
log_df.show()
vecAssembler = VectorAssembler(inputCols=['index'], outputCol='features')
lr_h4_log = LinearRegression(featuresCol='features', labelCol='logTotal')
training_log = trianing.withColumn('logTotal', log_num_udf('total'))
vecTrainDF_log = vecAssembler.transform(training_log)
lrModel_h4_log = lr_h4_log.fit(vecTrainDF_log)
m_log = lrModel_h4_log.coefficients[0]
b_log = lrModel_h4_log.intercept
print(f"""The formula for the linear regression lines is log(total) = {m_log:.3f}*index+{b_log:.3f}""")
# test
test_log = test.withColumn('logTotal', log_num_udf('total'))
vecTestDF_log = vecAssembler.transform(test_log)
predictions_log = lrModel_h4_log.transform(vecTestDF_log)
predictions_log.orderBy('prediction', ascending=False).show(10)
regresssionEvaluator = RegressionEvaluator(predictionCol='prediction', labelCol='logTotal', metricName='r2')
r2_log = regresssionEvaluator.evaluate(predictions_log)
print(f"r2 is {r2_log}")
H4()
| 39.585014 | 118 | 0.692268 |
import pyspark.sql.functions as F
from pyspark.sql import Row
from pyspark.sql.functions import *
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
import re
from pyspark.sql.types import *
from pyspark.sql.window import Window
from pyspark.sql.functions import rank, col
from pyspark.ml import Pipeline
from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler
from pyspark.ml.feature import RFormula
from pyspark.ml.classification import LogisticRegression
from pyspark.ml import Pipeline
sparkconf = SparkConf().setAppName('Mernis')
sparkconf.set('spark.executor.memory', '10g')
sparkconf.set('spark.driver.memory', '10g')
sparkconf.set("spark.sql.debug.maxToStringFields", "100")
spark = (SparkSession
.builder
.appName("Mernis")
.config(conf=sparkconf)
.getOrCreate())
file_path = '/root/myfile/mernis/data_dump.sql'
data = spark.sparkContext.textFile(file_path). \
filter((lambda line: re.findall('^\d{6}', line))). \
map(lambda line: line.split('\t')[:-1])
schema = "uid STRING, national_identifier STRING, first STRING, last STRING, mother_first STRING, " \
"father_first STRING, gender STRING, birth_city STRING, date_of_birth STRING," \
"id_registration_city STRING, id_registration_district STRING, address_city STRING," \
"address_district STRING, address_neighborhood STRING,street_address STRING," \
"door_or_entrance_number STRING"
df = spark.createDataFrame(data, schema)
li = line.split('/')
if len(li[2]) == 4 and 0 < len(li[1]) <= 2 and 0 < len(li[1]) <= 2:
return li[2] + '-' + li[1].zfill(2) + '-' + li[0].zfill(2)
else:
return 'null'
format_date_udf = udf(format_date, returnType=StringType())
df.createOrReplaceTempView('citizens')
df_format_date = df.withColumn("date_of_birth", format_date_udf(df["date_of_birth"]))
df_format_date = df_format_date.filter(expr("""date_of_birth != 'null'"""))
df_format_date = df_format_date.withColumn('date_of_birth', to_date('date_of_birth')).\
withColumn('month_of_birth',month('date_of_birth')).\
withColumn('year_of_birth', year('date_of_birth'))
df_format_date.show(3)
address_city'). \
groupBy('address_city'). \
agg(count('*').alias('total')). \
orderBy('total', ascending=False). \
limit(10)
sc = SparkContext.getOrCreate()
area = [('ADANA', 14030), ('ISTANBUL', 5343), ('BURSA', 10891), ('IZMIR', 7340), ('AYDIN', 8007),
('ANKARA', 30715), ('ANTALYA', 1417), ('KOCAELI', 3418), ('KONYA', 38257), ('MERSIN', 15737)]
df_area = spark.createDataFrame(area, ['address_city', 'area'])
df_area = df_n6.join(df_area, 'address_city', 'left_outer').orderBy('area')
df_area.show(10)
density_df = df_area.withColumn('desity', round(df_area['total'] / df_area['area'], 2))
density_df.show(10)
N6()
total_num = 49611709
df_n7_district = df_format_date. \
select('id_registration_district', 'address_district'). \
filter(col('id_registration_district') != col('address_district'))
propor_district = df_n7_district.count() / total_num
print('Proportion of cross-district floating population:%.3f' % propor_district)
df_n7_city = df_format_date. \
select('id_registration_city', 'address_city'). \
filter(col('id_registration_city') != col('address_city'))
propor_city = df_n7_city.count() / total_num
print('Proportion of cross-city floating population:%.3f' % propor_city)
N7()
df_h1 = df_format_date.sample(False, 0.00005, seed=2018)
df_h1.show(10)
df_h1 = df_h1.dropna()
print(df_h1.count())
feature_col = ['first', 'last', 'mother_first', 'father_first', 'gender', 'birth_city',
'month_of_birth', 'year_of_birth', 'id_registration_city', 'id_registration_district',
'address_district', 'address_neighborhood', 'street_address', 'address_city'
]
indexOutputCols = [x + '_Index' for x in feature_col]
oheOutputCols = [x + '_OHE' for x in feature_col]
stringIndexer_features = StringIndexer(inputCols=feature_col, outputCols=indexOutputCols,
handleInvalid="skip")
oheEncoder_features = OneHotEncoder(inputCols=indexOutputCols, outputCols=oheOutputCols)
pipeline = Pipeline(stages=[stringIndexer_features, oheEncoder_features])
model = pipeline.fit(df_h1)
res = model.transform(df_h1)
(trainingData, validData, testData) = res.randomSplit([0.7, 0.2, 0.1], seed=100)
trainingData.persist()
validData.persist()
testData.persist()
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
def H1():
print('=' * 20, 'problem H1', '=' * 20)
feature_col = ['first', 'last', 'mother_first', 'father_first', 'gender', 'birth_city',
'month_of_birth', 'year_of_birth', 'id_registration_city', 'id_registration_district',
'address_district', 'address_neighborhood', 'street_address'
]
oheOutputCols = [x + '_OHE' for x in feature_col]
vecAssembler = VectorAssembler(inputCols=oheOutputCols, outputCol='features')
df_h1 = vecAssembler.transform(trainingData)
lr = LogisticRegression(featuresCol='features', labelCol='address_city_Index',
maxIter=100, regParam=0.3, elasticNetParam=0)
lrPipeline = Pipeline(stages=[vecAssembler, lr])
lrModel = lrPipeline.fit(trainingData)
def evaluate_h1(data, model):
print(model)
vecData = vecAssembler.transform(data)
predictions = model.transform(vecData)
predictions. \
select('national_identifier', 'probability', 'address_city_Index', 'prediction'). \
orderBy('probability', ascending=False). \
show(n=5, truncate=30)
evaluator = MulticlassClassificationEvaluator(labelCol='address_city_Index', predictionCol='prediction')
lrAcc = evaluator.evaluate(predictions)
print('test accuracy = ', lrAcc)
evaluate_h1(validData, lrModel)
lr.setRegParam(0.001)
lrPipeline = Pipeline(stages=[vecAssembler, lr])
lrModel = lrPipeline.fit(trainingData)
evaluate_h1(validData, lrModel)
lr.setRegParam(0.01)
lrPipeline = Pipeline(stages=[vecAssembler, lr])
lrModel = lrPipeline.fit(trainingData)
evaluate_h1(validData, lrModel)
evaluate_h1(testData, lrModel)
H1()
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
h_of_birth',
'id_registration_city', 'id_registration_district', 'address_city',
'address_district', 'address_neighborhood', 'street_address'
]
oheOutputCols = [x + '_OHE' for x in feature_col]
vecAssembler = VectorAssembler(inputCols=oheOutputCols, outputCol='features')
lr_h2 = LogisticRegression(featuresCol='features', labelCol='gender_Index',
maxIter=100, regParam=0.01, elasticNetParam=0)
lrPipeline_h2 = Pipeline(stages=[vecAssembler, lr_h2])
lrModel_h2 = lrPipeline_h2.fit(trainingData)
def evaluate_h2(data, model):
predictions = model.transform(data)
predictions. \
select('national_identifier', 'probability', 'gender', 'gender_Index', 'prediction'). \
orderBy('probability', ascending=False). \
show(n=10, truncate=30)
evaluator = MulticlassClassificationEvaluator(labelCol='gender_Index', predictionCol='prediction')
lrAcc = evaluator.evaluate(predictions)
print('test accuracy = ', lrAcc)
evaluate_h2(validData, lrModel_h2)
lrPipeline_h2 = Pipeline(stages=[vecAssembler, lr_h2])
lrModel_h2 = lrPipeline_h2.fit(trainingData)
evaluate_h2(testData, lrModel_h2)
H2()
def H3():
print('=' * 20, 'problem H3', '=' * 20)
feature_col = ['mother_first', 'father_first', 'birth_city', 'gender', 'year_of_birth', 'month_of_birth',
'id_registration_city', 'id_registration_district', 'address_city',
'address_district', 'address_neighborhood', 'street_address'
]
oheOutputCols = [x + '_OHE' for x in feature_col]
vecAssembler = VectorAssembler(inputCols=oheOutputCols, outputCol='features')
vecTrainDF_h3 = vecAssembler.transform(trainingData)
trainingData.show(3)
lr_h3 = LogisticRegression(featuresCol='features', labelCol='first_Index',
maxIter=100, regParam=0.01, elasticNetParam=0)
lrModel_h3 = lr_h3.fit(vecTrainDF_h3)
def evaluate_h3(data):
print(lrModel_h3)
vecData = vecAssembler.transform(data)
predictions = lrModel_h3.transform(vecData)
predictions.select('national_identifier', 'probability', 'first', 'first_Index', 'prediction').orderBy(
'probability', ascending=False).show(n=10, truncate=30)
evaluator = MulticlassClassificationEvaluator(labelCol='first_Index', predictionCol='prediction')
lrAcc = evaluator.evaluate(predictions)
print('test accuracy = ', lrAcc)
evaluate_h3(validData)
evaluate_h3(testData)
from pyspark.sql.types import FloatType
from math import log
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.regression import LinearRegression
from pyspark.ml.feature import VectorAssembler
def H4():
print('='*2,'problem H4','='*20)
df_h4 = df_format_date.withColumn(
'year_of_birth', year('date_of_birth'))
df_population = df_h4.select("year_of_birth").groupBy('year_of_birth').agg(count('*').alias('total'))
df_population = df_population.withColumn('year', df_population['year_of_birth'].cast('int')).drop('year_of_birth')
df_population = df_population.filter(df_population['year'] > 1700)
df_population.orderBy('total').show(10)
def to_index(year):
return year - 1888
to_index_udf = udf(to_index, returnType=IntegerType())
min_year = df_population.select(min('year').alias('year')).collect()[0]
print(min_year)
new_df = df_population.withColumn('index', to_index_udf(df_population['year']))
new_df.show()
(trianing, test) = new_df.randomSplit([0.8, 0.2], seed=2020)
trianing.persist()
test.persist()
utCols=['index'],outputCol='features')
vecTrainDF = vecAssembler.transform(trianing)
lr_h4 = LinearRegression(featuresCol='features',labelCol='total')
lrModel_h4 = lr_h4.fit(vecTrainDF)
m = lrModel_h4.coefficients[0]
b = lrModel_h4.intercept
print(f"""The formula for the linear regression lines is num = {m:.2f}*index{b:.2f}""")
vecTestDF = vecAssembler.transform(test)
predictions = lrModel_h4.transform(vecTestDF)
predictions.orderBy('prediction', ascending=False).show(5)
regresssionEvaluator = RegressionEvaluator(predictionCol='prediction', labelCol='total', metricName='r2')
r2 = regresssionEvaluator.evaluate(predictions)
print(f"r2 is {r2}")
return log(num)
else:
return 0
log_num_udf = udf(log_num, returnType=FloatType())
log_df = new_df.withColumn('logTotal', log_num_udf(new_df['total']))
log_df.show()
vecAssembler = VectorAssembler(inputCols=['index'], outputCol='features')
lr_h4_log = LinearRegression(featuresCol='features', labelCol='logTotal')
training_log = trianing.withColumn('logTotal', log_num_udf('total'))
vecTrainDF_log = vecAssembler.transform(training_log)
lrModel_h4_log = lr_h4_log.fit(vecTrainDF_log)
m_log = lrModel_h4_log.coefficients[0]
b_log = lrModel_h4_log.intercept
print(f"""The formula for the linear regression lines is log(total) = {m_log:.3f}*index+{b_log:.3f}""")
test_log = test.withColumn('logTotal', log_num_udf('total'))
vecTestDF_log = vecAssembler.transform(test_log)
predictions_log = lrModel_h4_log.transform(vecTestDF_log)
predictions_log.orderBy('prediction', ascending=False).show(10)
regresssionEvaluator = RegressionEvaluator(predictionCol='prediction', labelCol='logTotal', metricName='r2')
r2_log = regresssionEvaluator.evaluate(predictions_log)
print(f"r2 is {r2_log}")
H4()
| true | true |
1c46fdcf707a39d6008c2679f4330a4c105e612a | 7,835 | py | Python | coffee.py | capjamesg/hypertext-coffee-pot | 2cf5987493066063908b467568a7c54c71c2ff66 | [
"MIT"
] | null | null | null | coffee.py | capjamesg/hypertext-coffee-pot | 2cf5987493066063908b467568a7c54c71c2ff66 | [
"MIT"
] | null | null | null | coffee.py | capjamesg/hypertext-coffee-pot | 2cf5987493066063908b467568a7c54c71c2ff66 | [
"MIT"
] | null | null | null | from config import *
import datetime
import logging
import socket
import json
import os
logging.basicConfig(filename="coffeepot.log", level=logging.DEBUG)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
pouring_milk = None
last_request = None
# rewrite the currently brewing file every time the program starts up
# a coffee pot that has been stopped in the middle of operation should not pick up where it left off (!)
with open("currently_brewing.json", "w+") as f:
f.write("{}")
if not os.path.isfile("past_coffees.json"):
with open("past_coffees.json", "w+") as f:
f.write("")
def ensure_request_is_valid(url, content_type, method, processing_request, connection):
if "://" not in url:
connection.send(b"HTCPCP/1.1 400 Bad Request\n\n")
processing_request = False
if url.split("://")[0].encode().decode("ascii") not in ACCEPTED_COFFEE_SCHEMES:
connection.send(b"HTCPCP/1.1 404 Not Found\r\n\r\n")
processing_request = False
if url.split("://")[1] != "james":
connection.send(b"HTCPCP/1.1 404 Not Found\r\n\r\n")
processing_request = False
if method not in ACCEPTED_METHODS:
connection.send(b"HTCPCP/1.1 501 Not Implemented\r\n\r\n")
processing_request = False
if content_type and content_type[0] != "Content-Type: application/coffee-pot-command":
connection.send(b"HTCPCP/1.1 415 Unsupported Media Type\r\n\r\n")
processing_request = False
return processing_request
def process_additions(headers, processing_request, pouring_milk, connection):
accept_additions = [header for header in headers if header.startswith("Accept-Additions")]
if len(accept_additions) > 0:
additions = accept_additions[0].split(":")[1].strip().split(";")
invalid_addition = False
for item in additions:
print(item.lower().strip())
if ACCEPTED_ADDITIONS.get(item.lower().strip()) is None:
response = "HTCPCP/1.1 406 Not Acceptable\r\n\r\n" + ", ".join(list(ACCEPTED_ADDITIONS.keys())).strip(", ")
connection.send(bytes(response.encode()))
invalid_addition = True
processing_request = False
elif item.lower() in MILKS:
# pour milk in 5 mins, after brew
pouring_milk = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%a, %d %b %Y %H:%M:%S")
if invalid_addition:
processing_request = False
else:
additions = None
return additions, processing_request, pouring_milk
def create_request_response(method, additions, pouring_milk):
response = ""
if method == "GET" or method == "PROPFIND":
with open("currently_brewing.json", "r") as f:
response = json.load(f)
response = json.dumps(response)
elif method == "BREW" or method == "POST":
response_body = message.split("\n")[-1]
if response_body == "stop":
with open("currently_brewing.json", "w+") as f:
f.write("{}")
elif response_body == "start":
now = datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S")
end_time = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%a, %d %b %Y %H:%M:%S")
if additions == None:
additions = []
if pouring_milk == None:
milk_status = ""
else:
milk_status = pouring_milk
record_to_save = json.dumps(
{
"date": now,
"beverage_type": "Coffee",
"additions": additions,
"brew_time_end": end_time,
"pouring_milk": milk_status
}
)
with open("past_coffees.json", "a+") as coffee_records:
coffee_records.write(record_to_save + "\n")
with open("currently_brewing.json", "w+") as brewing_record:
brewing_record.write(record_to_save)
else:
response = "HTCPCP/1.1 400 Bad Request\r\n\r\n"
elif method == "WHEN":
with open("currently_brewing.json", "r") as f:
response = json.load(f)
pouring_milk = datetime.datetime.strptime(pouring_milk, "%a, %d %b %Y %H:%M:%S")
brew_time_end_object = datetime.datetime.strptime(response.get("brew_time_end"), "%a, %d %b %Y %H:%M:%S")
if pouring_milk >= brew_time_end_object:
response = "Milk has stopped pouring."
else:
response = "Milk is not pouring."
pouring_milk = None
return response
while True:
# start listening for connections connections
server.listen()
print("Listening for connections on port " + str(PORT))
connection, address = server.accept()
# set timeout so requests cannot hang
connection.settimeout(5)
print("Connected to: ", address)
processing_request = True
while processing_request:
# get message
message = connection.recv(1024).decode()
last_request = message
if len(message.strip().replace("\n", "").replace("\r", "")) == 0:
processing_request = False
logging.info("Received message: " + message)
# get last coffee
with open("currently_brewing.json", "r") as f:
last_coffee = json.load(f)
method = message.split(" ")[0]
if last_coffee and last_coffee["brew_time_end"] and (method == "BREW" or method == "POST"):
# get last_coffee["brew_time_end"] as datetime object
last_brewed = datetime.datetime.strptime(last_coffee["brew_time_end"], "%a, %d %b %Y %H:%M:%S")
if last_brewed + datetime.timedelta(minutes=5) > datetime.datetime.now():
response = "HTCPCP/1.1 406 Not Acceptable\r\n\r\n" + ", ".join(list(ACCEPTED_ADDITIONS.keys())).strip(", ")
connection.send(bytes(response.encode()))
processing_request = False
else:
with open("currently_brewing.json", "w+") as f:
f.write("{}")
url = message.split(" ")[1]
headers = message.split("\n")
content_type = [header for header in headers if header.startswith("Content-Type")]
safe = [header for header in headers if header.startswith("Safe:")]
if safe and safe[0] == "Yes":
message = last_request
method = message.split(" ")[0]
url = message.split(" ")[1]
headers = message.split("\n")
processing_request = ensure_request_is_valid(url, content_type, method, processing_request, connection)
additions, processing_request, pouring_milk = process_additions(headers, processing_request, pouring_milk, connection)
if method in ACCEPTED_METHODS:
current_date = datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S")
# response body
headers_to_send = [
"HTCPCP/1.1 200 OK\r\n",
"Server: CoffeePot\r\n",
"Content-Type: message/coffeepot\r\n",
"Date: " + current_date + "\r\n",
]
response = create_request_response(method, additions, pouring_milk)
final_response = "".join(headers_to_send) + response
logging.info("Sending response: " + final_response)
print(final_response)
connection.send(bytes(final_response.encode("utf-8")))
processing_request = False
# close connection after request has been processed
logging.info("Closing connection")
connection.close()
logging.info("Connection closed") | 35.292793 | 126 | 0.596171 | from config import *
import datetime
import logging
import socket
import json
import os
logging.basicConfig(filename="coffeepot.log", level=logging.DEBUG)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
pouring_milk = None
last_request = None
with open("currently_brewing.json", "w+") as f:
f.write("{}")
if not os.path.isfile("past_coffees.json"):
with open("past_coffees.json", "w+") as f:
f.write("")
def ensure_request_is_valid(url, content_type, method, processing_request, connection):
if "://" not in url:
connection.send(b"HTCPCP/1.1 400 Bad Request\n\n")
processing_request = False
if url.split("://")[0].encode().decode("ascii") not in ACCEPTED_COFFEE_SCHEMES:
connection.send(b"HTCPCP/1.1 404 Not Found\r\n\r\n")
processing_request = False
if url.split("://")[1] != "james":
connection.send(b"HTCPCP/1.1 404 Not Found\r\n\r\n")
processing_request = False
if method not in ACCEPTED_METHODS:
connection.send(b"HTCPCP/1.1 501 Not Implemented\r\n\r\n")
processing_request = False
if content_type and content_type[0] != "Content-Type: application/coffee-pot-command":
connection.send(b"HTCPCP/1.1 415 Unsupported Media Type\r\n\r\n")
processing_request = False
return processing_request
def process_additions(headers, processing_request, pouring_milk, connection):
accept_additions = [header for header in headers if header.startswith("Accept-Additions")]
if len(accept_additions) > 0:
additions = accept_additions[0].split(":")[1].strip().split(";")
invalid_addition = False
for item in additions:
print(item.lower().strip())
if ACCEPTED_ADDITIONS.get(item.lower().strip()) is None:
response = "HTCPCP/1.1 406 Not Acceptable\r\n\r\n" + ", ".join(list(ACCEPTED_ADDITIONS.keys())).strip(", ")
connection.send(bytes(response.encode()))
invalid_addition = True
processing_request = False
elif item.lower() in MILKS:
pouring_milk = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%a, %d %b %Y %H:%M:%S")
if invalid_addition:
processing_request = False
else:
additions = None
return additions, processing_request, pouring_milk
def create_request_response(method, additions, pouring_milk):
response = ""
if method == "GET" or method == "PROPFIND":
with open("currently_brewing.json", "r") as f:
response = json.load(f)
response = json.dumps(response)
elif method == "BREW" or method == "POST":
response_body = message.split("\n")[-1]
if response_body == "stop":
with open("currently_brewing.json", "w+") as f:
f.write("{}")
elif response_body == "start":
now = datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S")
end_time = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%a, %d %b %Y %H:%M:%S")
if additions == None:
additions = []
if pouring_milk == None:
milk_status = ""
else:
milk_status = pouring_milk
record_to_save = json.dumps(
{
"date": now,
"beverage_type": "Coffee",
"additions": additions,
"brew_time_end": end_time,
"pouring_milk": milk_status
}
)
with open("past_coffees.json", "a+") as coffee_records:
coffee_records.write(record_to_save + "\n")
with open("currently_brewing.json", "w+") as brewing_record:
brewing_record.write(record_to_save)
else:
response = "HTCPCP/1.1 400 Bad Request\r\n\r\n"
elif method == "WHEN":
with open("currently_brewing.json", "r") as f:
response = json.load(f)
pouring_milk = datetime.datetime.strptime(pouring_milk, "%a, %d %b %Y %H:%M:%S")
brew_time_end_object = datetime.datetime.strptime(response.get("brew_time_end"), "%a, %d %b %Y %H:%M:%S")
if pouring_milk >= brew_time_end_object:
response = "Milk has stopped pouring."
else:
response = "Milk is not pouring."
pouring_milk = None
return response
while True:
server.listen()
print("Listening for connections on port " + str(PORT))
connection, address = server.accept()
connection.settimeout(5)
print("Connected to: ", address)
processing_request = True
while processing_request:
message = connection.recv(1024).decode()
last_request = message
if len(message.strip().replace("\n", "").replace("\r", "")) == 0:
processing_request = False
logging.info("Received message: " + message)
with open("currently_brewing.json", "r") as f:
last_coffee = json.load(f)
method = message.split(" ")[0]
if last_coffee and last_coffee["brew_time_end"] and (method == "BREW" or method == "POST"):
last_brewed = datetime.datetime.strptime(last_coffee["brew_time_end"], "%a, %d %b %Y %H:%M:%S")
if last_brewed + datetime.timedelta(minutes=5) > datetime.datetime.now():
response = "HTCPCP/1.1 406 Not Acceptable\r\n\r\n" + ", ".join(list(ACCEPTED_ADDITIONS.keys())).strip(", ")
connection.send(bytes(response.encode()))
processing_request = False
else:
with open("currently_brewing.json", "w+") as f:
f.write("{}")
url = message.split(" ")[1]
headers = message.split("\n")
content_type = [header for header in headers if header.startswith("Content-Type")]
safe = [header for header in headers if header.startswith("Safe:")]
if safe and safe[0] == "Yes":
message = last_request
method = message.split(" ")[0]
url = message.split(" ")[1]
headers = message.split("\n")
processing_request = ensure_request_is_valid(url, content_type, method, processing_request, connection)
additions, processing_request, pouring_milk = process_additions(headers, processing_request, pouring_milk, connection)
if method in ACCEPTED_METHODS:
current_date = datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S")
headers_to_send = [
"HTCPCP/1.1 200 OK\r\n",
"Server: CoffeePot\r\n",
"Content-Type: message/coffeepot\r\n",
"Date: " + current_date + "\r\n",
]
response = create_request_response(method, additions, pouring_milk)
final_response = "".join(headers_to_send) + response
logging.info("Sending response: " + final_response)
print(final_response)
connection.send(bytes(final_response.encode("utf-8")))
processing_request = False
logging.info("Closing connection")
connection.close()
logging.info("Connection closed") | true | true |
1c46fde441f196ee5cc51a5ec50072e5a1d3b4aa | 7,281 | py | Python | scripts/fig/util.py | ucbrise/snoopy | da4c98e3876c10cf52aa51ece3b62c5e8b8e335a | [
"Apache-2.0"
] | 9 | 2021-11-10T20:34:00.000Z | 2022-03-23T02:30:29.000Z | scripts/fig/util.py | ucbrise/snoopy | da4c98e3876c10cf52aa51ece3b62c5e8b8e335a | [
"Apache-2.0"
] | null | null | null | scripts/fig/util.py | ucbrise/snoopy | da4c98e3876c10cf52aa51ece3b62c5e8b8e335a | [
"Apache-2.0"
] | 4 | 2021-09-30T05:12:06.000Z | 2022-03-18T03:05:21.000Z | import json
import math
import random
from collections import defaultdict
from scipy.special import lambertw
def parseData(filename):
results = []
f = open(filename, "r")
for line in f:
elems = line.split()
result = {
"clients": int(elems[0]),
"data_size": int(elems[1]),
"suborams": int(elems[2]),
"iter": int(elems[3]),
"balancers": int(elems[4]),
"mean_latency": float(elems[6]),
"min_latenecy": float(elems[7]),
"max_latency": float(elems[8]),
"var_latency": float(elems[9]),
"std_latency": float(elems[10]),
"50_latency": float(elems[11]),
"75_latency": float(elems[12]),
"90_latency": float(elems[13]),
"95_latency": float(elems[14]),
"99_latency": float(elems[15]),
"throughput": float(elems[16])
}
results.append(result)
return results
def parseDataNew(filename):
results = []
f = open(filename, "r")
for line in f:
elems = line.split()
result = {
"clients": int(elems[0]),
"data_size": int(elems[1]),
"suborams": int(elems[2]),
"balancers": int(elems[3]),
"iter": int(elems[4]),
"mean_latency": float(elems[5]),
"min_latenecy": float(elems[6]),
"max_latency": float(elems[7]),
"var_latency": float(elems[8]),
"std_latency": float(elems[9]),
"50_latency": float(elems[10]),
"75_latency": float(elems[11]),
"90_latency": float(elems[12]),
"95_latency": float(elems[13]),
"99_latency": float(elems[14]),
"throughput": float(elems[15])
}
results.append(result)
return results
def parseDataNew2(filename):
results = []
f = open(filename, "r")
for line in f:
elems = line.split()
result = {
"clients": int(elems[0]),
"data_size": int(elems[1]),
"suborams": int(elems[2]),
"balancers": int(elems[3]),
"epoch_ms": int(elems[4]),
"iter": int(elems[5]),
"mean_latency": float(elems[6]),
"min_latenecy": float(elems[7]),
"max_latency": float(elems[8]),
"var_latency": float(elems[9]),
"std_latency": float(elems[10]),
"50_latency": float(elems[11]),
"75_latency": float(elems[12]),
"90_latency": float(elems[13]),
"95_latency": float(elems[14]),
"99_latency": float(elems[15]),
"throughput": float(elems[16])
}
results.append(result)
return results
def getMaxThroughputForNumBalancers(results, num_balancers):
ret = 0
for result in results:
if result["balancers"] == num_balancers:
ret = max(ret, result["throughput"])
return ret
def getMaxThroughputForNumBalancersWithMaxLatency(results, num_balancers, max_latency, suborams=None):
ret = 0
for result in results:
if result["balancers"] == num_balancers and result["90_latency"] <= max_latency:
if suborams is None or result["suborams"] == suborams:
ret = max(ret, result["throughput"])
return ret
def getMaxThroughputForNumBalancersWithMaxMeanLatency(results, num_balancers, max_latency, suborams=None):
ret = 0
for result in results:
if result["balancers"] == num_balancers and result["50_latency"] <= max_latency:
if suborams is None or result["suborams"] == suborams:
ret = max(ret, result["throughput"])
return ret
def getLatencyForMaxThroughputForNumBalancers(results, num_balancers):
throughput = 0
ret = 0
for result in results:
if result["balancers"] == num_balancers:
if (throughput < result["throughput"]):
throughput = result["throughput"]
ret = result["mean_latency"]
return ret
def getMaxThroughputForEpochMs(results, epoch_ms):
ret = 0
for result in results:
if result["epoch_ms"] == epoch_ms:
ret = max(ret, result["throughput"])
return ret
def getMaxDataForNumSuborams(results, num_suborams, max_latency, latency_type):
ret = 0
for result in results:
if result["suborams"] == num_suborams and result[latency_type] < max_latency:
print(("Acceptable latency for %d suborams: %d") % (result["suborams"], result[latency_type]))
ret = max(ret, result["data_size"])
return ret
def getTupleListOfVals(results, *labels):
ret = []
for result in results:
res = ()
for l in labels:
res += (result[l],)
if res not in ret:
ret.append(res)
return ret
def getListOfVals(results, label):
ret = []
for result in results:
if result[label] not in ret:
ret.append(result[label])
return ret
def getLatencyForSuboramAndDataSize(results, num_suborams, data_size, latency_type):
for result in results:
if result["suborams"] == num_suborams and result["data_size"] == data_size:
return result[latency_type]
def f(N, n_suborams, secparam=128):
mu = N / n_suborams
alpha = math.log(n_suborams * (2 ** secparam))
rhs = alpha / (math.e * mu) - 1 / math.e
branch = 0
epsilon = math.e ** (lambertw(rhs, branch) + 1) - 1
#epsilon = (alpha + math.sqrt(2 * mu * alpha)) / mu # uncomment for looser bound
#print(alpha, rhs, lambertw(rhs, 0), lambertw(rhs, 1))
#print("bound", suborams, secparam, alpha, rhs, lambertw(rhs), epsilon)
return mu * (1 + epsilon)
def hash_requests(reqs, n_suborams, run):
offset = run * reqs
secret = b'Sixteen byte key'
buckets = defaultdict(int)
for i in range(offset, offset+reqs):
"""
cobj = CMAC.new(secret, ciphermod=AES)
cobj.update(i.to_bytes(i.bit_length(), 'big'))
h = int(cobj.hexdigest(), 16)
"""
h = int(random.random() * n_suborams)
bucket = h % n_suborams
buckets[bucket] += 1
return max(buckets.values())
def max_requests(n_suborams, target, secparam):
"""
Get maximum request batch size for a given # of suborams that each support target requests.
"""
l = n_suborams
r = 2 ** 32
m = 0
while l <= r:
m = math.floor((l+r)/ 2)
bound = f(m, n_suborams, secparam)
if bound > target:
r = m - 1
elif bound < target:
l = m + 1
else:
return m
return m
def parse_args(parser):
parser.add_argument('input', type=str, help='input data')
parser.add_argument('output', type=str, help='output file')
parser.add_argument('-b', '--baseline', help='baseline data')
parser.add_argument('-t', '--title', help='set graph title')
parser.add_argument('-l', '--large', action='store_true',
help='output large graph (default: false)')
args = parser.parse_args()
return args
def parse_baseline(filename):
with open(filename, 'r') as f:
baseline = json.load(f)
return baseline | 33.708333 | 106 | 0.573136 | import json
import math
import random
from collections import defaultdict
from scipy.special import lambertw
def parseData(filename):
results = []
f = open(filename, "r")
for line in f:
elems = line.split()
result = {
"clients": int(elems[0]),
"data_size": int(elems[1]),
"suborams": int(elems[2]),
"iter": int(elems[3]),
"balancers": int(elems[4]),
"mean_latency": float(elems[6]),
"min_latenecy": float(elems[7]),
"max_latency": float(elems[8]),
"var_latency": float(elems[9]),
"std_latency": float(elems[10]),
"50_latency": float(elems[11]),
"75_latency": float(elems[12]),
"90_latency": float(elems[13]),
"95_latency": float(elems[14]),
"99_latency": float(elems[15]),
"throughput": float(elems[16])
}
results.append(result)
return results
def parseDataNew(filename):
results = []
f = open(filename, "r")
for line in f:
elems = line.split()
result = {
"clients": int(elems[0]),
"data_size": int(elems[1]),
"suborams": int(elems[2]),
"balancers": int(elems[3]),
"iter": int(elems[4]),
"mean_latency": float(elems[5]),
"min_latenecy": float(elems[6]),
"max_latency": float(elems[7]),
"var_latency": float(elems[8]),
"std_latency": float(elems[9]),
"50_latency": float(elems[10]),
"75_latency": float(elems[11]),
"90_latency": float(elems[12]),
"95_latency": float(elems[13]),
"99_latency": float(elems[14]),
"throughput": float(elems[15])
}
results.append(result)
return results
def parseDataNew2(filename):
results = []
f = open(filename, "r")
for line in f:
elems = line.split()
result = {
"clients": int(elems[0]),
"data_size": int(elems[1]),
"suborams": int(elems[2]),
"balancers": int(elems[3]),
"epoch_ms": int(elems[4]),
"iter": int(elems[5]),
"mean_latency": float(elems[6]),
"min_latenecy": float(elems[7]),
"max_latency": float(elems[8]),
"var_latency": float(elems[9]),
"std_latency": float(elems[10]),
"50_latency": float(elems[11]),
"75_latency": float(elems[12]),
"90_latency": float(elems[13]),
"95_latency": float(elems[14]),
"99_latency": float(elems[15]),
"throughput": float(elems[16])
}
results.append(result)
return results
def getMaxThroughputForNumBalancers(results, num_balancers):
ret = 0
for result in results:
if result["balancers"] == num_balancers:
ret = max(ret, result["throughput"])
return ret
def getMaxThroughputForNumBalancersWithMaxLatency(results, num_balancers, max_latency, suborams=None):
ret = 0
for result in results:
if result["balancers"] == num_balancers and result["90_latency"] <= max_latency:
if suborams is None or result["suborams"] == suborams:
ret = max(ret, result["throughput"])
return ret
def getMaxThroughputForNumBalancersWithMaxMeanLatency(results, num_balancers, max_latency, suborams=None):
ret = 0
for result in results:
if result["balancers"] == num_balancers and result["50_latency"] <= max_latency:
if suborams is None or result["suborams"] == suborams:
ret = max(ret, result["throughput"])
return ret
def getLatencyForMaxThroughputForNumBalancers(results, num_balancers):
throughput = 0
ret = 0
for result in results:
if result["balancers"] == num_balancers:
if (throughput < result["throughput"]):
throughput = result["throughput"]
ret = result["mean_latency"]
return ret
def getMaxThroughputForEpochMs(results, epoch_ms):
ret = 0
for result in results:
if result["epoch_ms"] == epoch_ms:
ret = max(ret, result["throughput"])
return ret
def getMaxDataForNumSuborams(results, num_suborams, max_latency, latency_type):
ret = 0
for result in results:
if result["suborams"] == num_suborams and result[latency_type] < max_latency:
print(("Acceptable latency for %d suborams: %d") % (result["suborams"], result[latency_type]))
ret = max(ret, result["data_size"])
return ret
def getTupleListOfVals(results, *labels):
ret = []
for result in results:
res = ()
for l in labels:
res += (result[l],)
if res not in ret:
ret.append(res)
return ret
def getListOfVals(results, label):
ret = []
for result in results:
if result[label] not in ret:
ret.append(result[label])
return ret
def getLatencyForSuboramAndDataSize(results, num_suborams, data_size, latency_type):
for result in results:
if result["suborams"] == num_suborams and result["data_size"] == data_size:
return result[latency_type]
def f(N, n_suborams, secparam=128):
mu = N / n_suborams
alpha = math.log(n_suborams * (2 ** secparam))
rhs = alpha / (math.e * mu) - 1 / math.e
branch = 0
epsilon = math.e ** (lambertw(rhs, branch) + 1) - 1
1 + epsilon)
def hash_requests(reqs, n_suborams, run):
offset = run * reqs
secret = b'Sixteen byte key'
buckets = defaultdict(int)
for i in range(offset, offset+reqs):
h = int(random.random() * n_suborams)
bucket = h % n_suborams
buckets[bucket] += 1
return max(buckets.values())
def max_requests(n_suborams, target, secparam):
l = n_suborams
r = 2 ** 32
m = 0
while l <= r:
m = math.floor((l+r)/ 2)
bound = f(m, n_suborams, secparam)
if bound > target:
r = m - 1
elif bound < target:
l = m + 1
else:
return m
return m
def parse_args(parser):
parser.add_argument('input', type=str, help='input data')
parser.add_argument('output', type=str, help='output file')
parser.add_argument('-b', '--baseline', help='baseline data')
parser.add_argument('-t', '--title', help='set graph title')
parser.add_argument('-l', '--large', action='store_true',
help='output large graph (default: false)')
args = parser.parse_args()
return args
def parse_baseline(filename):
with open(filename, 'r') as f:
baseline = json.load(f)
return baseline | true | true |
1c4702f1d0d7fa1c75b6ea73d0e090f76d63480b | 2,601 | py | Python | explore/viz/continuous.py | idc9/explore | ce8aa039de96b1dd9fecc19fa098c222863ac3ce | [
"MIT"
] | null | null | null | explore/viz/continuous.py | idc9/explore | ce8aa039de96b1dd9fecc19fa098c222863ac3ce | [
"MIT"
] | null | null | null | explore/viz/continuous.py | idc9/explore | ce8aa039de96b1dd9fecc19fa098c222863ac3ce | [
"MIT"
] | 1 | 2021-02-05T20:31:51.000Z | 2021-02-05T20:31:51.000Z | import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from scipy.stats import pearsonr
from explore.utils import safe_apply
from explore.viz.utils import bold, ABLine2D, fmt_pval
def plot_scatter(x, y, alpha=0.05, standardize=False, label=None):
"""
Parameters
----------
x, y: array-like (ideally pd.Series)
x, y values to plot. If pd.Series, uses 'name' to get x/y labels
alpha: float
Cutoff for correlation coefficient significance.
standardisze: bool
Whether or not to standardized (mean center and scale) variables.
True by defualt.
"""
xlab, ylab = '', ''
if hasattr(x, 'name'):
xlab = x.name
if hasattr(y, 'name'):
ylab = y.name
# drop missing values
df = pd.concat([pd.Series(x), pd.Series(y)], axis=1).dropna()
# optinally center/scale
if standardize:
df = safe_apply(StandardScaler().fit_transform, df)
xlab += ' (standardized)'
ylab += ' (standardized)'
x = df.iloc[:, 0].values.reshape(-1)
y = df.iloc[:, 1].values.reshape(-1)
# fit linear model
lm = LinearRegression(fit_intercept=True).fit(x.reshape(-1, 1), y)
slope = lm.coef_.item()
intercept = lm.intercept_
# if no label provided, compute correlation
if label is None:
alpha = 0.05
# compute pearson correlation
corr, pval = pearsonr(x, y)
reject = pval < alpha
label = get_cts_label(reject, corr, corr_name='pearson', pval=pval)
# scatter plot
plt.scatter(x, y, color='blue', s=2)
plt.xlabel(xlab)
plt.ylabel(ylab)
# line
ABLine2D(slope, intercept, label=label,
color='blue') # , linewidth=linewidth
plt.legend(loc='upper left')
def get_cts_label(reject, corr, corr_name, pval):
if reject:
# stat_str = bold('pearson \\ corr: {:1.2f} \\ (p={:1.2f})'.format(corr, pval))
# label = bold('{}: {:1.3f} (p={:1.3f})*'.format(corr_name, corr, pval))
# label = bold('{}: {:1.3f} (p={:.1e})*'.format(corr_name, corr, pval))
label = bold('{}: {:1.3f} (p={})*'.format(corr_name, corr,
fmt_pval(pval)))
else:
# stat_str = 'pearson corr: {:1.2f} (p={:1.2f})'.format(corr, pval)
# label = '{}: {:1.3f} (p={:1.3f})'.format(corr_name, corr, pval)
label = '{}: {:1.3f} (p={})'.format(corr_name, corr,
fmt_pval(pval))
return label
| 30.964286 | 87 | 0.582468 | import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from scipy.stats import pearsonr
from explore.utils import safe_apply
from explore.viz.utils import bold, ABLine2D, fmt_pval
def plot_scatter(x, y, alpha=0.05, standardize=False, label=None):
xlab, ylab = '', ''
if hasattr(x, 'name'):
xlab = x.name
if hasattr(y, 'name'):
ylab = y.name
df = pd.concat([pd.Series(x), pd.Series(y)], axis=1).dropna()
if standardize:
df = safe_apply(StandardScaler().fit_transform, df)
xlab += ' (standardized)'
ylab += ' (standardized)'
x = df.iloc[:, 0].values.reshape(-1)
y = df.iloc[:, 1].values.reshape(-1)
lm = LinearRegression(fit_intercept=True).fit(x.reshape(-1, 1), y)
slope = lm.coef_.item()
intercept = lm.intercept_
if label is None:
alpha = 0.05
corr, pval = pearsonr(x, y)
reject = pval < alpha
label = get_cts_label(reject, corr, corr_name='pearson', pval=pval)
plt.scatter(x, y, color='blue', s=2)
plt.xlabel(xlab)
plt.ylabel(ylab)
ABLine2D(slope, intercept, label=label,
color='blue')
plt.legend(loc='upper left')
def get_cts_label(reject, corr, corr_name, pval):
if reject:
label = bold('{}: {:1.3f} (p={})*'.format(corr_name, corr,
fmt_pval(pval)))
else:
label = '{}: {:1.3f} (p={})'.format(corr_name, corr,
fmt_pval(pval))
return label
| true | true |
1c47041f9ee93610c39d81b27b322f0c72c5c342 | 1,919 | py | Python | tests/metarl/torch/algos/test_maml_vpg.py | icml2020submission6857/metarl | 9b66cefa2b6bcb6a38096d629ce8853b47c7171d | [
"MIT"
] | 2 | 2020-03-15T14:35:15.000Z | 2021-02-15T16:38:00.000Z | tests/metarl/torch/algos/test_maml_vpg.py | icml2020submission6857/metarl | 9b66cefa2b6bcb6a38096d629ce8853b47c7171d | [
"MIT"
] | null | null | null | tests/metarl/torch/algos/test_maml_vpg.py | icml2020submission6857/metarl | 9b66cefa2b6bcb6a38096d629ce8853b47c7171d | [
"MIT"
] | 1 | 2020-02-24T03:04:23.000Z | 2020-02-24T03:04:23.000Z | """This script is a test that fails when MAML-VPG performance is too low."""
import torch
from metarl.envs import HalfCheetahDirEnv, normalize
from metarl.envs.base import MetaRLEnv
from metarl.experiment import deterministic, LocalRunner
from metarl.np.baselines import LinearFeatureBaseline
from metarl.torch.algos import MAMLVPG
from metarl.torch.policies import GaussianMLPPolicy
from tests.fixtures import snapshot_config
class TestMAMLVPG:
"""Test class for MAML-VPG."""
def setup_method(self):
"""Setup method which is called before every test."""
self.env = MetaRLEnv(
normalize(HalfCheetahDirEnv(), expected_action_scale=10.))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None,
)
self.baseline = LinearFeatureBaseline(env_spec=self.env.spec)
def teardown_method(self):
"""Teardown method which is called after every test."""
self.env.close()
def test_ppo_pendulum(self):
"""Test PPO with Pendulum environment."""
deterministic.set_seed(0)
rollouts_per_task = 5
max_path_length = 100
runner = LocalRunner(snapshot_config)
algo = MAMLVPG(env=self.env,
policy=self.policy,
baseline=self.baseline,
max_path_length=max_path_length,
meta_batch_size=5,
discount=0.99,
gae_lambda=1.,
inner_lr=0.1,
num_grad_updates=1)
runner.setup(algo, self.env)
last_avg_ret = runner.train(n_epochs=10,
batch_size=rollouts_per_task *
max_path_length)
assert last_avg_ret > -5
| 34.267857 | 76 | 0.610214 | import torch
from metarl.envs import HalfCheetahDirEnv, normalize
from metarl.envs.base import MetaRLEnv
from metarl.experiment import deterministic, LocalRunner
from metarl.np.baselines import LinearFeatureBaseline
from metarl.torch.algos import MAMLVPG
from metarl.torch.policies import GaussianMLPPolicy
from tests.fixtures import snapshot_config
class TestMAMLVPG:
def setup_method(self):
self.env = MetaRLEnv(
normalize(HalfCheetahDirEnv(), expected_action_scale=10.))
self.policy = GaussianMLPPolicy(
env_spec=self.env.spec,
hidden_sizes=(64, 64),
hidden_nonlinearity=torch.tanh,
output_nonlinearity=None,
)
self.baseline = LinearFeatureBaseline(env_spec=self.env.spec)
def teardown_method(self):
self.env.close()
def test_ppo_pendulum(self):
deterministic.set_seed(0)
rollouts_per_task = 5
max_path_length = 100
runner = LocalRunner(snapshot_config)
algo = MAMLVPG(env=self.env,
policy=self.policy,
baseline=self.baseline,
max_path_length=max_path_length,
meta_batch_size=5,
discount=0.99,
gae_lambda=1.,
inner_lr=0.1,
num_grad_updates=1)
runner.setup(algo, self.env)
last_avg_ret = runner.train(n_epochs=10,
batch_size=rollouts_per_task *
max_path_length)
assert last_avg_ret > -5
| true | true |
1c470467bb157c6b60fde6c16bf077f9e16b1e83 | 1,063 | py | Python | python/neuroglancer/default_credentials_manager.py | ilastik/neuroglancer | c8dc0982e3e235866a6144d467022e22af1300e0 | [
"Apache-2.0"
] | 20 | 2017-03-05T19:35:02.000Z | 2021-07-05T09:32:27.000Z | python/neuroglancer/default_credentials_manager.py | ilastik/neuroglancer | c8dc0982e3e235866a6144d467022e22af1300e0 | [
"Apache-2.0"
] | 410 | 2017-02-06T16:58:55.000Z | 2022-03-24T08:29:56.000Z | python/neuroglancer/default_credentials_manager.py | ilastik/neuroglancer | c8dc0982e3e235866a6144d467022e22af1300e0 | [
"Apache-2.0"
] | 13 | 2017-04-13T13:36:42.000Z | 2021-09-14T17:15:23.000Z | # @license
# Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from . import credentials_provider, google_credentials
default_credentials_manager = credentials_provider.CredentialsManager()
default_credentials_manager.register(
u'google-brainmaps',
lambda _parameters: google_credentials.GoogleCredentialsProvider(
client_id=u'639403125587-ue3c18dalqidqehs1n1p5rjvgni5f7qu.apps.googleusercontent.com',
client_secret=u'kuaqECaVXOKEJ2L6ifZu4Aqt',
scopes=[u'https://www.googleapis.com/auth/brainmaps'],
))
| 42.52 | 94 | 0.777046 |
from . import credentials_provider, google_credentials
default_credentials_manager = credentials_provider.CredentialsManager()
default_credentials_manager.register(
u'google-brainmaps',
lambda _parameters: google_credentials.GoogleCredentialsProvider(
client_id=u'639403125587-ue3c18dalqidqehs1n1p5rjvgni5f7qu.apps.googleusercontent.com',
client_secret=u'kuaqECaVXOKEJ2L6ifZu4Aqt',
scopes=[u'https://www.googleapis.com/auth/brainmaps'],
))
| true | true |
1c4704a0a504b68ddee07f8b85b5a5909cee1a87 | 1,698 | py | Python | sevdesk/client/models/invoice_change_status_json_body.py | HpLightcorner/SevDesk-Python-Client | 303ca8dddd78da4291e7d23692ccfb147c7ba31a | [
"MIT"
] | null | null | null | sevdesk/client/models/invoice_change_status_json_body.py | HpLightcorner/SevDesk-Python-Client | 303ca8dddd78da4291e7d23692ccfb147c7ba31a | [
"MIT"
] | null | null | null | sevdesk/client/models/invoice_change_status_json_body.py | HpLightcorner/SevDesk-Python-Client | 303ca8dddd78da4291e7d23692ccfb147c7ba31a | [
"MIT"
] | null | null | null | from typing import Any, Dict, List, Type, TypeVar
import attr
from ..models.invoice_change_status_json_body_value import (
InvoiceChangeStatusJsonBodyValue,
)
T = TypeVar("T", bound="InvoiceChangeStatusJsonBody")
@attr.s(auto_attribs=True)
class InvoiceChangeStatusJsonBody:
"""
Attributes:
value (InvoiceChangeStatusJsonBodyValue): Please have a look in our docs Example: 100.
"""
value: InvoiceChangeStatusJsonBodyValue
additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)
def to_dict(self) -> Dict[str, Any]:
value = self.value.value
field_dict: Dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"value": value,
}
)
return field_dict
@classmethod
def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
d = src_dict.copy()
value = InvoiceChangeStatusJsonBodyValue(d.pop("value"))
invoice_change_status_json_body = cls(
value=value,
)
invoice_change_status_json_body.additional_properties = d
return invoice_change_status_json_body
@property
def additional_keys(self) -> List[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties
| 27.387097 | 94 | 0.660188 | from typing import Any, Dict, List, Type, TypeVar
import attr
from ..models.invoice_change_status_json_body_value import (
InvoiceChangeStatusJsonBodyValue,
)
T = TypeVar("T", bound="InvoiceChangeStatusJsonBody")
@attr.s(auto_attribs=True)
class InvoiceChangeStatusJsonBody:
value: InvoiceChangeStatusJsonBodyValue
additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)
def to_dict(self) -> Dict[str, Any]:
value = self.value.value
field_dict: Dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"value": value,
}
)
return field_dict
@classmethod
def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
d = src_dict.copy()
value = InvoiceChangeStatusJsonBodyValue(d.pop("value"))
invoice_change_status_json_body = cls(
value=value,
)
invoice_change_status_json_body.additional_properties = d
return invoice_change_status_json_body
@property
def additional_keys(self) -> List[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties
| true | true |
1c47055e964491c450560bbb9bf677126d271f38 | 346 | py | Python | flanker/mime/message/utils.py | meta-x/flanker | 1e37baa1db2ecee238ac3de1e36a2948e0a6d3ad | [
"Apache-2.0"
] | 1 | 2015-11-08T12:57:12.000Z | 2015-11-08T12:57:12.000Z | flanker/mime/message/utils.py | meta-x/flanker | 1e37baa1db2ecee238ac3de1e36a2948e0a6d3ad | [
"Apache-2.0"
] | null | null | null | flanker/mime/message/utils.py | meta-x/flanker | 1e37baa1db2ecee238ac3de1e36a2948e0a6d3ad | [
"Apache-2.0"
] | 1 | 2020-12-18T08:33:56.000Z | 2020-12-18T08:33:56.000Z | from cStringIO import StringIO
from contextlib import closing
from email.generator import Generator
def python_message_to_string(msg):
"""Converts python message to string in a proper way"""
with closing(StringIO()) as fp:
g = Generator(fp, mangle_from_=False)
g.flatten(msg, unixfrom=False)
return fp.getvalue()
| 31.454545 | 59 | 0.722543 | from cStringIO import StringIO
from contextlib import closing
from email.generator import Generator
def python_message_to_string(msg):
with closing(StringIO()) as fp:
g = Generator(fp, mangle_from_=False)
g.flatten(msg, unixfrom=False)
return fp.getvalue()
| true | true |
1c470582964b938e3223bcd1617f3e7be1a1716e | 18,456 | py | Python | excellent/_version.py | arokem/excellent-science | e25e62ba766bd7292240cf8bd8596f926d59baf9 | [
"BSD-3-Clause"
] | null | null | null | excellent/_version.py | arokem/excellent-science | e25e62ba766bd7292240cf8bd8596f926d59baf9 | [
"BSD-3-Clause"
] | 1 | 2018-07-31T21:27:27.000Z | 2018-07-31T21:27:27.000Z | excellent/_version.py | arokem/excellent-science | e25e62ba766bd7292240cf8bd8596f926d59baf9 | [
"BSD-3-Clause"
] | null | null | null |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains the computed version number.
# This file is released into the public domain. Generated by
# versioneer-0.18 (https://github.com/warner/python-versioneer)
"""Git implementation of _version.py."""
import errno
import os
import re
import subprocess
import sys
def get_keywords():
"""Get the keywords needed to look up the version information."""
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, so they must
# each be defined on a line of their own. _version.py will just call
# get_keywords().
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
git_date = "$Format:%ci$"
keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
return keywords
class VersioneerConfig:
"""Container for Versioneer configuration parameters."""
def get_config():
"""Create, populate and return the VersioneerConfig() object."""
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.tag_prefix = "v"
cfg.parentdir_prefix = "None"
cfg.versionfile_source = "excellent/_version.py"
cfg.verbose = False
return cfg
class NotThisMethod(Exception):
"""Exception raised if a method is not valid for the current scenario."""
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
env=None):
"""Call the given command(s)."""
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, env=env,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
return None, p.returncode
return stdout, p.returncode
def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an appropriately named parent directory
"""
rootdirs = []
for i in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix):
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None, "date": None}
else:
rootdirs.append(root)
root = os.path.dirname(root) # up a level
if verbose:
print("Tried directories %s but none started with prefix %s" %
(str(rootdirs), parentdir_prefix))
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
@register_vcs_handler("git", "get_keywords")
def git_get_keywords(versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
f.close()
except EnvironmentError:
pass
return keywords
@register_vcs_handler("git", "keywords")
def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
# datestamp. However we prefer "%ci" (which expands to an "ISO-8601
# -like" string, which we must then edit to make compliant), because
# it's been around since git-1.5.3, and it's too difficult to
# discover which version we're using, or to work around using an
# older one.
date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
# expansion behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %s" % r)
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None,
"date": date}
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags", "date": None}
@register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
"""
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
hide_stderr=True)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
raise NotThisMethod("'git rev-parse --git-dir' returned error")
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
describe_out = describe_out.strip()
full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if full_out is None:
raise NotThisMethod("'git rev-parse' failed")
full_out = full_out.strip()
pieces = {}
pieces["long"] = full_out
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
# TAG might have hyphens.
git_describe = describe_out
# look for -dirty suffix
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
# now we have TAG-NUM-gHEX or HEX
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
return pieces
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
# commit: short hex revision ID
pieces["short"] = mo.group(3)
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
pieces["distance"] = int(count_out) # total number of commits
# commit date: see ISO-8601 comment in git_versions_from_keywords()
date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],
cwd=root)[0].strip()
pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
return pieces
def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
def render_pep440(pieces):
"""Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exception #1
rendered = "0.post.dev%d" % pieces["distance"]
return rendered
def render_pep440_post(pieces):
"""TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
return rendered
def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
return rendered
def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None}
if not style or style == "default":
style = "pep440" # the default
if style == "pep440":
rendered = render_pep440(pieces)
elif style == "pep440-pre":
rendered = render_pep440_pre(pieces)
elif style == "pep440-post":
rendered = render_pep440_post(pieces)
elif style == "pep440-old":
rendered = render_pep440_old(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None,
"date": pieces.get("date")}
def get_versions():
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
# case we can only use expanded keywords.
cfg = get_config()
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
except NotThisMethod:
pass
try:
root = os.path.realpath(__file__)
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in cfg.versionfile_source.split('/'):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree",
"date": None}
try:
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
return render(pieces, cfg.style)
except NotThisMethod:
pass
try:
if cfg.parentdir_prefix:
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version", "date": None}
| 35.424184 | 79 | 0.584634 |
import errno
import os
import re
import subprocess
import sys
def get_keywords():
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
git_date = "$Format:%ci$"
keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
return keywords
class VersioneerConfig:
def get_config():
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.tag_prefix = "v"
cfg.parentdir_prefix = "None"
cfg.versionfile_source = "excellent/_version.py"
cfg.verbose = False
return cfg
class NotThisMethod(Exception):
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method):
def decorate(f):
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
env=None):
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
p = subprocess.Popen([c] + args, cwd=cwd, env=env,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
return None, p.returncode
return stdout, p.returncode
def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []
for i in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix):
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None, "date": None}
else:
rootdirs.append(root)
root = os.path.dirname(root)
if verbose:
print("Tried directories %s but none started with prefix %s" %
(str(rootdirs), parentdir_prefix))
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
@register_vcs_handler("git", "get_keywords")
def git_get_keywords(versionfile_abs):
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
f.close()
except EnvironmentError:
pass
return keywords
@register_vcs_handler("git", "keywords")
def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# -like" string, which we must then edit to make compliant), because
# older one.
date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
for ref in sorted(tags):
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %s" % r)
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None,
"date": date}
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags", "date": None}
@register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
hide_stderr=True)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
raise NotThisMethod("'git rev-parse --git-dir' returned error")
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
describe_out = describe_out.strip()
full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if full_out is None:
raise NotThisMethod("'git rev-parse' failed")
full_out = full_out.strip()
pieces = {}
pieces["long"] = full_out
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
# TAG might have hyphens.
git_describe = describe_out
# look for -dirty suffix
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
# now we have TAG-NUM-gHEX or HEX
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
return pieces
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
# commit: short hex revision ID
pieces["short"] = mo.group(3)
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
pieces["distance"] = int(count_out) # total number of commits
# commit date: see ISO-8601 comment in git_versions_from_keywords()
date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],
cwd=root)[0].strip()
pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
return pieces
def plus_or_dot(pieces):
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
def render_pep440(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
def render_pep440_pre(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exception #1
rendered = "0.post.dev%d" % pieces["distance"]
return rendered
def render_pep440_post(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
return rendered
def render_pep440_old(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
return rendered
def render_git_describe(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render_git_describe_long(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered
def render(pieces, style):
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None}
if not style or style == "default":
style = "pep440" # the default
if style == "pep440":
rendered = render_pep440(pieces)
elif style == "pep440-pre":
rendered = render_pep440_pre(pieces)
elif style == "pep440-post":
rendered = render_pep440_post(pieces)
elif style == "pep440-old":
rendered = render_pep440_old(pieces)
elif style == "git-describe":
rendered = render_git_describe(pieces)
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None,
"date": pieces.get("date")}
def get_versions():
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
cfg = get_config()
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
except NotThisMethod:
pass
try:
root = os.path.realpath(__file__)
for i in cfg.versionfile_source.split('/'):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree",
"date": None}
try:
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
return render(pieces, cfg.style)
except NotThisMethod:
pass
try:
if cfg.parentdir_prefix:
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version", "date": None}
| true | true |
1c4705b0614ddedee8f02cb903791afebf6e7a81 | 72,735 | py | Python | src/sage/combinat/words/word_generators.py | bopopescu/sagemath | 39f452b2691c5ac86654fea22414fa5851893b48 | [
"BSL-1.0"
] | 3 | 2018-09-11T11:16:26.000Z | 2019-09-10T15:26:37.000Z | src/sage/combinat/words/word_generators.py | bopopescu/sagemath | 39f452b2691c5ac86654fea22414fa5851893b48 | [
"BSL-1.0"
] | 2 | 2018-10-30T13:40:20.000Z | 2020-07-23T12:13:30.000Z | src/sage/combinat/words/word_generators.py | bopopescu/sagemath | 39f452b2691c5ac86654fea22414fa5851893b48 | [
"BSL-1.0"
] | 1 | 2020-07-23T10:29:58.000Z | 2020-07-23T10:29:58.000Z | # -*- coding: utf-8 -*-
r"""
Common words
AUTHORS:
- Franco Saliola (2008-12-17): merged into sage
- Sebastien Labbe (2008-12-17): merged into sage
- Arnaud Bergeron (2008-12-17): merged into sage
- Amy Glen (2008-12-17): merged into sage
- Sebastien Labbe (2009-12-19): Added S-adic words (:trac:`7543`)
USE:
To see a list of all word constructors, type ``words.`` and then press the tab
key. The documentation for each constructor includes information about each
word, which provides a useful reference.
REFERENCES:
.. [AC03] \B. Adamczewski, J. Cassaigne, On the transcendence of real
numbers with a regular expansion, J. Number Theory 103 (2003)
27--37.
.. [BmBGL07] \A. Blondin-Masse, S. Brlek, A. Glen, and S. Labbe. On the
critical exponent of generalized Thue-Morse words. *Discrete Math.
Theor. Comput. Sci.* 9 (1):293--304, 2007.
.. [BmBGL09] \A. Blondin-Masse, S. Brlek, A. Garon, and S. Labbe. Christoffel
and Fibonacci Tiles, DGCI 2009, Montreal, to appear in LNCS.
.. [Loth02] \M. Lothaire, Algebraic Combinatorics On Words, vol. 90 of
Encyclopedia of Mathematics and its Applications, Cambridge
University Press, U.K., 2002.
.. [Fogg] Pytheas Fogg,
https://www.lirmm.fr/arith/wiki/PytheasFogg/S-adiques.
EXAMPLES::
sage: t = words.ThueMorseWord(); t
word: 0110100110010110100101100110100110010110...
"""
#*****************************************************************************
# Copyright (C) 2008 Franco Saliola <saliola@gmail.com>,
# Sebastien Labbe <slabqc@gmail.com>,
# Arnaud Bergeron <abergeron@gmail.com>,
# Amy Glen <amy.glen@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import print_function
from six.moves import range
from itertools import cycle, count
from random import randint
from sage.misc.cachefunc import cached_method
from sage.rings.all import ZZ, RR
from sage.rings.infinity import Infinity
from sage.combinat.words.abstract_word import Word_class
from sage.combinat.words.word import FiniteWord_list
from sage.combinat.words.finite_word import FiniteWord_class, Factorization
from sage.combinat.words.words import FiniteWords, InfiniteWords
from sage.combinat.words.morphism import WordMorphism
from sage.arith.all import gcd
from sage.misc.decorators import rename_keyword
def _build_tab(sym, tab, W):
r"""
Internal function building a coding table for the ``phi_inv_tab`` function.
TESTS::
sage: from sage.combinat.words.word_generators import _build_tab
sage: _build_tab(1, [], Words([1, 2]))
[1]
sage: _build_tab(1, [1], Words([1, 2]))
[1, 2]
sage: _build_tab(2, [1], Words([1, 2]))
[2, 2]
sage: _build_tab(2, [1, 2], Words([1, 2]))
[2, 2, 1]
sage: _build_tab(1, [2, 2], Words([1, 2]))
[1, 1, 2]
"""
c = W.alphabet().cardinality()
res = [sym]
if len(tab) == 0:
return res
if sym == 1:
res += tab
res[1] = (res[1] % c) + 1
return res
w = W([sym]).delta_inv(W, tab[0])
w = w[1:]
res.append((w[-1] % c) + 1)
for i in range(1, len(tab)):
w = w.delta_inv(W, tab[i])
res.append((w[-1] % c) + 1)
return res
class LowerChristoffelWord(FiniteWord_list):
r"""
Returns the lower Christoffel word of slope `p/q`, where `p` and
`q` are relatively prime non-negative integers, over the given
two-letter alphabet.
The *Christoffel word of slope `p/q`* is obtained from the
Cayley graph of `\ZZ/(p+q)\ZZ` with generator `q` as
follows. If `u \rightarrow v` is an edge in the Cayley graph, then
`v = u + p \mod{p+q}`. Label the edge `u \rightarrow v` by
``alphabet[1]`` if `u < v` and ``alphabet[0]`` otherwise. The Christoffel
word is the word obtained by reading the edge labels along the
cycle beginning from 0.
EXAMPLES::
sage: words.LowerChristoffelWord(4,7)
word: 00100100101
::
sage: words.LowerChristoffelWord(4,7,alphabet='ab')
word: aabaabaabab
TESTS::
sage: words.LowerChristoffelWord(1,0)
word: 1
sage: words.LowerChristoffelWord(0,1,'xy')
word: x
sage: words.LowerChristoffelWord(1,1)
word: 01
"""
def __init__(self, p, q, alphabet=(0,1), algorithm='cf'):
r"""
INPUT:
- ``p`` - integer coprime with ``q``.
- ``q`` - integer coprime with ``p``.
- ``alphabet`` - sequence of two elements (optional, default: (0, 1)).
- ``algorithm`` - construction method (optional, default: 'cf').
It can be one of the following:
- ``'linear'`` - linear algorithm in the length of the word.
- ``'cf'`` - fast method using continued fraction.
TESTS::
sage: words.ChristoffelWord(9, 4, algorithm='linear')
word: 0110110110111
sage: words.ChristoffelWord(9, 4, algorithm='cf')
word: 0110110110111
sage: words.ChristoffelWord(4, 9, algorithm='linear')
word: 0001001001001
sage: words.ChristoffelWord(4, 9, algorithm='cf')
word: 0001001001001
::
sage: words.LowerChristoffelWord(4,8)
Traceback (most recent call last):
...
ValueError: 4 and 8 are not relatively prime
sage: words.LowerChristoffelWord(17, 39, 'xyz')
Traceback (most recent call last):
...
ValueError: alphabet must contain exactly two distinct elements
sage: w = words.LowerChristoffelWord(4,7)
sage: w2 = loads(dumps(w))
sage: w == w2
True
sage: type(w2)
<class 'sage.combinat.words.word_generators.LowerChristoffelWord'>
sage: _ = w2.standard_factorization() # hackish test for self.__p and self.__q
"""
if len(set(alphabet)) != 2:
raise ValueError("alphabet must contain exactly two distinct elements")
# Compute gcd of p, q; raise TypeError if not 1.
if gcd(p,q) != 1:
raise ValueError("%s and %s are not relatively prime" % (p, q))
# Compute the Christoffel word
if algorithm == 'linear':
w = []
u = 0
if (p, q) == (0, 1):
w = [alphabet[0]]
else:
for i in range(p + q):
v = (u+p) % (p+q)
new_letter = alphabet[0] if u < v else alphabet[1]
w.append(new_letter)
u = v
elif algorithm == 'cf':
if (p, q) == (0, 1):
w = [alphabet[0]]
elif (p, q) == (1, 0):
w = [alphabet[1]]
else:
from sage.rings.rational_field import QQ
cf = QQ((p, q)).continued_fraction_list()
u = [alphabet[0]]
v = [alphabet[1]]
#do not consider the first zero if p < q
start = 1 if p < q else 0
for i in range(start, len(cf)-1):
if i % 2 == 0:
u = u + v * cf[i]
else:
v = u * cf[i] + v
i = len(cf)-1
if i % 2 == 0:
u = u + v * (cf[i]-1)
else:
v = u * (cf[i]-1) + v
w = u + v
else:
raise ValueError('Unknown algorithm (=%s)'%algorithm)
super(LowerChristoffelWord, self).__init__(FiniteWords(alphabet), w)
self.__p = p
self.__q = q
def markoff_number(self):
r"""
Returns the Markoff number associated to the Christoffel word self.
The *Markoff number* of a Christoffel word `w` is `trace(M(w))/3`,
where `M(w)` is the `2\times 2` matrix obtained by applying the
morphism:
0 -> matrix(2,[2,1,1,1])
1 -> matrix(2,[5,2,2,1])
EXAMPLES::
sage: w0 = words.LowerChristoffelWord(4,7)
sage: w1, w2 = w0.standard_factorization()
sage: (m0,m1,m2) = (w.markoff_number() for w in (w0,w1,w2))
sage: (m0,m1,m2)
(294685, 13, 7561)
sage: m0**2 + m1**2 + m2**2 == 3*m0*m1*m2
True
"""
from sage.matrix.constructor import matrix
eta = {0:matrix(2,[2,1,1,1]), 1:matrix(2,[5,2,2,1])}
M = matrix(2,[1,0,0,1])
for a in self:
M *= eta[a]
return M.trace()/3
def standard_factorization(self):
r"""
Returns the standard factorization of the Christoffel word ``self``.
The *standard factorization* of a Christoffel word `w` is the
unique factorization of `w` into two Christoffel words.
EXAMPLES::
sage: w = words.LowerChristoffelWord(5,9)
sage: w
word: 00100100100101
sage: w1, w2 = w.standard_factorization()
sage: w1
word: 001
sage: w2
word: 00100100101
::
sage: w = words.LowerChristoffelWord(51,37)
sage: w1, w2 = w.standard_factorization()
sage: w1
word: 0101011010101101011
sage: w2
word: 0101011010101101011010101101010110101101...
sage: w1 * w2 == w
True
"""
p, q = self.__p, self.__q
index = 0
u = 0
for i in range(p + q):
v = (u+p) % (p+q)
if v == 1:
index = i
break
u = v
w1, w2 = self[:index+1], self[index+1:]
return Factorization([LowerChristoffelWord(w1.count(1),w1.count(0)),
LowerChristoffelWord(w2.count(1),w2.count(0))])
def __reduce__(self):
r"""
EXAMPLES::
sage: from sage.combinat.words.word_generators import LowerChristoffelWord
sage: w = LowerChristoffelWord(5,7)
sage: w.__reduce__()
(<class 'sage.combinat.words.word_generators.LowerChristoffelWord'>, (5, 7, {0, 1}))
"""
return self.__class__, (self.__p, self.__q, self.parent().alphabet())
class WordGenerator(object):
r"""
Constructor of several famous words.
EXAMPLES::
sage: words.ThueMorseWord()
word: 0110100110010110100101100110100110010110...
::
sage: words.FibonacciWord()
word: 0100101001001010010100100101001001010010...
::
sage: words.ChristoffelWord(5, 8)
word: 0010010100101
::
sage: words.RandomWord(10, 4) # not tested random
word: 1311131221
::
sage: words.CodingOfRotationWord(alpha=0.618, beta=0.618)
word: 1010110101101101011010110110101101101011...
::
sage: tm = WordMorphism('a->ab,b->ba')
sage: fib = WordMorphism('a->ab,b->a')
sage: tmword = words.ThueMorseWord([0, 1])
sage: from itertools import repeat
sage: words.s_adic(tmword, repeat('a'), {0:tm, 1:fib})
word: abbaababbaabbaabbaababbaababbaabbaababba...
.. NOTE::
To see a list of all word constructors, type ``words.`` and then
hit the TAB key. The documentation for each constructor
includes information about each word, which provides a useful
reference.
TESTS::
sage: from sage.combinat.words.word_generators import WordGenerator
sage: words2 = WordGenerator()
sage: type(loads(dumps(words2)))
<class 'sage.combinat.words.word_generators.WordGenerator'>
"""
def ThueMorseWord(self, alphabet=(0, 1), base=2):
r"""
Returns the (Generalized) Thue-Morse word over the given alphabet.
There are several ways to define the Thue-Morse word `t`.
We use the following definition: `t[n]` is the sum modulo `m` of
the digits in the given base expansion of `n`.
See [BmBGL07]_, [Brlek89]_, and [MH38]_.
INPUT:
- ``alphabet`` - (default: (0, 1) ) any container that is suitable to
build an instance of OrderedAlphabet (list, tuple, str, ...)
- ``base`` - an integer (default : 2) greater or equal to 2
EXAMPLES:
Thue-Morse word::
sage: t = words.ThueMorseWord(); t
word: 0110100110010110100101100110100110010110...
Thue-Morse word on other alphabets::
sage: t = words.ThueMorseWord('ab'); t
word: abbabaabbaababbabaababbaabbabaabbaababba...
::
sage: t = words.ThueMorseWord(['L1', 'L2'])
sage: t[:8]
word: L1,L2,L2,L1,L2,L1,L1,L2
Generalized Thue Morse word::
sage: words.ThueMorseWord(alphabet=(0,1,2), base=2)
word: 0112122012202001122020012001011212202001...
sage: t = words.ThueMorseWord(alphabet=(0,1,2), base=5); t
word: 0120112012201200120112012120122012001201...
sage: t[100:130].critical_exponent()
10/3
TESTS::
sage: words.ThueMorseWord(alphabet='ab', base=1)
Traceback (most recent call last):
...
ValueError: base (=1) and len(alphabet) (=2) must be at least 2
REFERENCES:
.. [Brlek89] Brlek, S. 1989. «Enumeration of the factors in the Thue-Morse
word», *Discrete Appl. Math.*, vol. 24, p. 83--96.
.. [MH38] Morse, M., et G. A. Hedlund. 1938. «Symbolic dynamics»,
*American Journal of Mathematics*, vol. 60, p. 815--866.
"""
W = InfiniteWords(alphabet)
alphabet = W.alphabet()
m = alphabet.cardinality()
if base < 2 or m < 2 :
raise ValueError("base (=%s) and len(alphabet) (=%s) must be at least 2"%(base, m))
from functools import partial
f = partial(self._ThueMorseWord_nth_digit, alphabet=alphabet, base=base)
return W(f, datatype='callable')
def _ThueMorseWord_nth_digit(self, n, alphabet=(0,1), base=2):
r"""
Returns the `n`-th letter of the (Generalized) Thue-Morse word.
The `n`-th digit of the Thue-Morse word can be defined as the number
of bits in the 2-complement representation of the position
modulo 2 which is what this function uses. The running time
is `O(\log n)` where `n` is the position desired.
The `n`-th digit of the Generalized Thue Morse word can be defined as
the sum of the digits of `n` written in the given base mod `m`,
where `m` is the length of the given alphabet.
INPUT:
- ``n`` - integer, the position
- ``alphabet`` - an alphabet (default : (0, 1) ) of size at least 2
- ``base`` - an integer (default : 2) greater or equal to 2
OUTPUT:
0 or 1 -- the digit at the position
letter -- the letter of alphabet at the position
TESTS::
sage: from sage.combinat.words.word_generators import WordGenerator
sage: WordGenerator()._ThueMorseWord_nth_digit(0)
0
sage: WordGenerator()._ThueMorseWord_nth_digit(3)
0
sage: WordGenerator()._ThueMorseWord_nth_digit(32)
1
sage: WordGenerator()._ThueMorseWord_nth_digit(6, 'abc', base = 7)
'a'
Negative input::
sage: words._ThueMorseWord_nth_digit(-7)
Traceback (most recent call last):
...
NotImplementedError: nth digit of Thue-Morse word is not implemented for negative value of n
"""
if n < 0:
raise NotImplementedError("nth digit of Thue-Morse word is not implemented for negative value of n")
m = len(alphabet)
if base == 2 and m == 2:
for tn in count():
if n == 0:
return alphabet[tn & 1]
n &= n - 1
elif base < 2 or m < 2 :
raise ValueError("base (=%s) and len(alphabet) (=%s) must be at least 2"%(base, m))
else:
return alphabet[ZZ(sum(ZZ(n).digits(base = base))).mod(m)]
def FibonacciWord(self, alphabet=(0, 1), construction_method="recursive"):
r"""
Returns the Fibonacci word on the given two-letter alphabet.
INPUT:
- ``alphabet`` -- any container of length two that is suitable to
build an instance of OrderedAlphabet (list, tuple, str, ...)
- ``construction_method`` -- can be any of the following:
"recursive", "fixed point", "function" (see below for definitions).
Recursive construction: the Fibonacci word is the limit of the
following sequence of words: `S_0 = 0`, `S_1 = 01`,
`S_n = S_{n-1} S_{n-2}` for `n \geq 2`.
Fixed point construction: the Fibonacci word is the fixed point of the
morphism: `0 \mapsto 01` and `1 \mapsto 0`. Hence, it can be constructed
by the following read-write process:
#. beginning at the first letter of `01`,
#. if the next letter is `0`, append `01` to the word;
#. if the next letter is `1`, append `1` to the word;
#. move to the next letter of the word.
Function: Over the alphabet `\{1, 2\}`, the n-th letter of the
Fibonacci word is
`\lfloor (n+2) \varphi \rfloor - \lfloor (n+1) \varphi \rfloor`
where `\varphi=(1+\sqrt{5})/2` is the golden ratio.
EXAMPLES::
sage: w = words.FibonacciWord(construction_method="recursive"); w
word: 0100101001001010010100100101001001010010...
::
sage: v = words.FibonacciWord(construction_method="recursive", alphabet='ab'); v
word: abaababaabaababaababaabaababaabaababaaba...
::
sage: u = words.FibonacciWord(construction_method="fixed point"); u
word: 0100101001001010010100100101001001010010...
::
sage: words.FibonacciWord(construction_method="fixed point", alphabet=[4, 1])
word: 4144141441441414414144144141441441414414...
::
sage: words.FibonacciWord([0,1], 'function')
word: 0100101001001010010100100101001001010010...
sage: words.FibonacciWord('ab', 'function')
word: abaababaabaababaababaabaababaabaababaaba...
TESTS::
sage: from math import floor, sqrt
sage: golden_ratio = (1 + sqrt(5))/2.0
sage: a = golden_ratio / (1 + 2*golden_ratio)
sage: wn = lambda n : int(floor(a*(n+2)) - floor(a*(n+1)))
sage: f = Words([0,1])(wn); f
word: 0100101001001010010100100101001001010010...
sage: f[:10000] == w[:10000]
True
sage: f[:10000] == u[:10000] #long time
True
sage: words.FibonacciWord("abc")
Traceback (most recent call last):
...
TypeError: alphabet does not contain two distinct elements
"""
W = InfiniteWords(alphabet)
alphabet = W.alphabet()
if alphabet.cardinality() != 2:
raise TypeError("alphabet does not contain two distinct elements")
a,b = alphabet
if construction_method == "recursive":
w = W(self._FibonacciWord_RecursiveConstructionIterator(alphabet),
datatype='iter')
return w
elif construction_method in ("fixed point", "fixed_point"):
d = {b:[a],a:[a,b]}
w = self.FixedPointOfMorphism(d, a)
return w
elif construction_method == "function":
from sage.functions.other import sqrt, floor
phi = (1 + sqrt(5))/2 # the golden ratio
f = lambda n:a if floor((n+2)*phi) - floor((n+1)*phi) == 2 else b
return W(f)
else:
raise NotImplementedError
def _FibonacciWord_RecursiveConstructionIterator(self,alphabet=(0,1)):
r"""
Iterates over the symbols of the Fibonacci word, as defined by
the following recursive construction: the Fibonacci word is the
limit of the sequence `S_0 = 0`, `S_1 = 01`, `S_n = S_{n-1}
S_{n-2}` for `n \geq 2`.
TESTS::
sage: from sage.combinat.words.word_generators import WordGenerator
sage: from itertools import islice
sage: it = WordGenerator()._FibonacciWord_RecursiveConstructionIterator()
sage: list(islice(it,13r))
[0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1]
"""
Fib0 = [0]
Fib1 = [0,1]
n = 0
while True:
it = iter(Fib1[n:])
for i in it:
n += 1
yield alphabet[i]
else:
Fib1, Fib0 = Fib1 + Fib0, Fib1
def FixedPointOfMorphism(self, morphism, first_letter):
r"""
Returns the fixed point of the morphism beginning with
``first_letter``.
A *fixed point* of a morphism `\varphi` is a word `w` such that
`\varphi(w) = w`.
INPUT:
- ``morphism`` -- endomorphism prolongable on ``first_letter``. It
must be something that WordMorphism's constructor understands
(dict, str, ...).
- ``first_letter`` -- the first letter of the fixed point
OUTPUT:
The fixed point of the morphism beginning with ``first_letter``
EXAMPLES::
sage: mu = {0:[0,1], 1:[1,0]}
sage: tm = words.FixedPointOfMorphism(mu,0); tm
word: 0110100110010110100101100110100110010110...
sage: TM = words.ThueMorseWord()
sage: tm[:1000] == TM[:1000]
True
::
sage: mu = {0:[0,1], 1:[0]}
sage: f = words.FixedPointOfMorphism(mu,0); f
word: 0100101001001010010100100101001001010010...
sage: F = words.FibonacciWord(); F
word: 0100101001001010010100100101001001010010...
sage: f[:1000] == F[:1000]
True
::
sage: fp = words.FixedPointOfMorphism('a->abc,b->,c->','a'); fp
word: abc
"""
return WordMorphism(morphism).fixed_point(letter=first_letter)
def CodingOfRotationWord(self, alpha, beta, x=0, alphabet=(0,1)):
r"""
Returns the infinite word obtained from the coding of rotation of
parameters `(\alpha,\beta, x)` over the given two-letter alphabet.
The *coding of rotation* corresponding to the parameters
`(\alpha,\beta, x)` is the symbolic sequence `u = (u_n)_{n\geq 0}`
defined over the binary alphabet `\{0, 1\}` by `u_n = 1` if
`x+n\alpha\in[0, \beta[` and `u_n = 0` otherwise. See [AC03]_.
EXAMPLES::
sage: alpha = 0.45
sage: beta = 0.48
sage: words.CodingOfRotationWord(0.45, 0.48)
word: 1101010101001010101011010101010010101010...
::
sage: words.CodingOfRotationWord(0.45, 0.48, alphabet='xy')
word: yyxyxyxyxyxxyxyxyxyxyyxyxyxyxyxxyxyxyxyx...
TESTS::
sage: words.CodingOfRotationWord(0.51,0.43,alphabet=[1,0,2])
Traceback (most recent call last):
...
TypeError: alphabet does not contain two distinct elements
"""
if len(set(alphabet)) != 2:
raise TypeError("alphabet does not contain two distinct elements")
from functools import partial
f = partial(self._CodingOfRotationWord_function,alpha=alpha,beta=beta,x=x,alphabet=alphabet)
w = InfiniteWords(alphabet)(f, datatype='callable')
return w
def _CodingOfRotationWord_function(self, n, alpha, beta, x=0, alphabet=(0,1)):
r"""
Internal function that returns the symbol in position `n` of the
coding of rotation word corresponding to the parameters `\alpha`,
`\beta`, and `x`.
TESTS::
sage: alpha, beta = 0.45, 0.48
sage: words._CodingOfRotationWord_function(3, alpha, beta)
1
sage: words._CodingOfRotationWord_function(10, alpha, beta)
0
sage: words._CodingOfRotationWord_function(17, alpha, beta)
0
"""
hauteur = x + n * alpha
fracH = hauteur.frac()
if fracH < 0:
fracH += 1
if 0 <= fracH < beta:
return alphabet[1]
else:
return alphabet[0]
@rename_keyword(cf='slope')
def CharacteristicSturmianWord(self, slope, alphabet=(0, 1), bits=None):
r"""
Returns the characteristic Sturmian word (also called standard
Sturmian word) of given slope.
Over a binary alphabet `\{a,b\}`, the characteristic Sturmian
word `c_\alpha` of irrational slope `\alpha` is the infinite word
satisfying `s_{\alpha,0} = ac_\alpha` and `s'_{\alpha,0} = bc_\alpha`,
where `s_{\alpha,0}` and `s'_{\alpha,0}` are respectively the lower
and upper mechanical words with slope `\alpha` and intercept `0`.
Equivalently, for irrational `\alpha`,
`c_\alpha = s_{\alpha,\alpha} = s'_{\alpha,\alpha}`.
Let `\alpha = [0, d_1 + 1, d_2, d_3, \ldots]` be the continued
fraction expansion of `\alpha`. It has been shown that the
characteristic Sturmian word of slope `\alpha` is also the limit of
the sequence: `s_0 = b, s_1 = a, \ldots, s_{n+1} = s_n^{d_n} s_{n-1}`
for `n > 0`.
See Section 2.1 of [Loth02]_ for more details.
INPUT:
- ``slope`` - the slope of the word. It can be one of the following :
- real number in `]0, 1[`
- iterable over the continued fraction expansion of a real
number in `]0, 1[`
- ``alphabet`` - any container of length two that is suitable to
build an instance of OrderedAlphabet (list, tuple, str, ...)
- ``bits`` - integer (optional and considered only if ``slope`` is
a real number) the number of bits to consider when computing the
continued fraction.
OUTPUT:
word
ALGORITHM:
Let `[0, d_1 + 1, d_2, d_3, \ldots]` be the continued fraction
expansion of `\alpha`. Then, the characteristic Sturmian word of
slope `\alpha` is the limit of the sequence: `s_0 = b`, `s_1 = a`
and `s_{n+1} = s_n^{d_n} s_{n-1}` for `n > 0`.
EXAMPLES:
From real slope::
sage: words.CharacteristicSturmianWord(1/golden_ratio^2)
word: 0100101001001010010100100101001001010010...
sage: words.CharacteristicSturmianWord(4/5)
word: 11110
sage: words.CharacteristicSturmianWord(5/14)
word: 01001001001001
sage: words.CharacteristicSturmianWord(pi-3)
word: 0000001000000100000010000001000000100000...
From an iterator of the continued fraction expansion of a real::
sage: def cf():
....: yield 0
....: yield 2
....: while True: yield 1
sage: F = words.CharacteristicSturmianWord(cf()); F
word: 0100101001001010010100100101001001010010...
sage: Fib = words.FibonacciWord(); Fib
word: 0100101001001010010100100101001001010010...
sage: F[:10000] == Fib[:10000]
True
The alphabet may be specified::
sage: words.CharacteristicSturmianWord(cf(), 'rs')
word: rsrrsrsrrsrrsrsrrsrsrrsrrsrsrrsrrsrsrrsr...
The characteristic sturmian word of slope `(\sqrt{3}-1)/2`::
sage: words.CharacteristicSturmianWord((sqrt(3)-1)/2)
word: 0100100101001001001010010010010100100101...
The same word defined from the continued fraction expansion of
`(\sqrt{3}-1)/2`::
sage: from itertools import cycle, chain
sage: it = chain([0], cycle([2, 1]))
sage: words.CharacteristicSturmianWord(it)
word: 0100100101001001001010010010010100100101...
The first terms of the standard sequence of the characteristic
sturmian word of slope `(\sqrt{3}-1)/2`::
sage: words.CharacteristicSturmianWord([0,2])
word: 01
sage: words.CharacteristicSturmianWord([0,2,1])
word: 010
sage: words.CharacteristicSturmianWord([0,2,1,2])
word: 01001001
sage: words.CharacteristicSturmianWord([0,2,1,2,1])
word: 01001001010
sage: words.CharacteristicSturmianWord([0,2,1,2,1,2])
word: 010010010100100100101001001001
sage: words.CharacteristicSturmianWord([0,2,1,2,1,2,1])
word: 0100100101001001001010010010010100100101...
TESTS::
sage: words.CharacteristicSturmianWord([1,1,1],'xyz')
Traceback (most recent call last):
...
TypeError: alphabet does not contain two distinct elements
::
sage: words.CharacteristicSturmianWord(5/4)
Traceback (most recent call last):
...
ValueError: The argument slope (=5/4) must be in ]0,1[.
::
sage: words.CharacteristicSturmianWord(1/golden_ratio^2)
word: 0100101001001010010100100101001001010010...
sage: _.length()
+Infinity
::
sage: a = words.LowerMechanicalWord(1/pi)[1:]
sage: b = words.UpperMechanicalWord(1/pi)[1:]
sage: c = words.CharacteristicSturmianWord(1/pi)
sage: n = 500; a[:n] == b[:n] == c[:n]
True
::
sage: alpha = random()
sage: c = words.CharacteristicSturmianWord(alpha)
sage: l = words.LowerMechanicalWord(alpha)[1:]
sage: u = words.UpperMechanicalWord(alpha)[1:]
sage: i = 10000; j = i + 500; c[i:j] == l[i:j] == u[i:j]
True
::
sage: a, b = 207, 232
sage: u = words.ChristoffelWord(a, b)
sage: v = words.CharacteristicSturmianWord(a/(a+b))
sage: v.length()
439
sage: u[1:-1] == v[:-2]
True
"""
if len(set(alphabet)) != 2:
raise TypeError("alphabet does not contain two distinct elements")
if slope in RR:
if not 0 < slope < 1:
msg = "The argument slope (=%s) must be in ]0,1[."%slope
raise ValueError(msg)
from sage.rings.continued_fraction import continued_fraction
cf = continued_fraction(slope)
if cf.length() == Infinity:
parent = InfiniteWords(alphabet)
else:
parent = FiniteWords(alphabet)
cf = iter(cf)
elif hasattr(slope, '__iter__'):
cf = iter(slope)
parent = InfiniteWords(alphabet)
else:
raise TypeError("slope (=%s) must be a real number"%slope +
"or an iterable.")
w = parent(self._CharacteristicSturmianWord_LetterIterator(cf,alphabet),
datatype='iter')
return w
def _CharacteristicSturmianWord_LetterIterator(self, cf, alphabet=(0,1)):
r"""
Returns an iterator over the symbols of the characteristic
Sturmian word of slope ``cf``.
INPUT:
- ``cf`` - iterator, the continued fraction expansion of a real
number in `]0, 1[`.
- ``alphabet`` - the alphabet (optional, default ``(0,1)``) of
the output
OUTPUT:
iterator of letters
ALGORITHM:
Let `[0, d_1 + 1, d_2, d_3, \ldots]` be the continued fraction
expansion of `\alpha`. Then, the characteristic Sturmian word of
slope `\alpha` is the limit of the sequence: `s_0 = 1`, `s_1 = 0`
and `s_{n+1} = s_n^{d_n} s_{n-1}` for `n > 0`.
EXAMPLES::
sage: continued_fraction(1/golden_ratio^2)[:8]
[0; 2, 1, 1, 1, 1, 2]
sage: cf = iter(_)
sage: Word(words._CharacteristicSturmianWord_LetterIterator(cf))
word: 0100101001001010010100100101001010
::
sage: alpha = (sqrt(3)-1)/2
sage: continued_fraction(alpha)[:10]
[0; 2, 1, 2, 1, 2, 1, 2, 1, 2]
sage: cf = iter(_)
sage: Word(words._CharacteristicSturmianWord_LetterIterator(cf))
word: 0100100101001001001010010010010100100101...
"""
try:
if next(cf) != 0:
raise ValueError("The first term of the continued fraction expansion must be zero.")
except StopIteration:
return
s0 = [1]
s1 = [0]
try:
e = next(cf)
except StopIteration:
return
if not e >= 1:
raise ValueError("The second term of the continued fraction expansion must be larger or equal to 1.")
s1, s0 = s1*(e-1) + s0, s1
n = 0
while True:
try:
for i in s1[n:]:
n += 1
yield alphabet[i]
else:
s1, s0 = s1*next(cf) + s0, s1
except StopIteration:
return
def KolakoskiWord(self, alphabet=(1,2)):
r"""
Returns the Kolakoski word over the given alphabet and
starting with the first letter of the alphabet.
Let `A = \{a,b\}` be an alphabet, where `a` and `b` are two
distinct positive integers. The Kolakoski word `K_{a,b}`
over `A` and starting with `a` is the unique infinite word `w`
such that `w = \Delta(w)`, where `\Delta(w)` is the word
encoding the runs of `w` (see ``delta()`` method on words for
more details).
Note that `K_{a,b} \neq K_{b,a}`. On the other hand, the
words `K_{a,b}` and `K_{b,a}` are the unique two words over `A`
that are fixed by `\Delta`.
Also note that the Kolakoski word is also known as the
Oldenburger word.
INPUT:
- ``alphabet`` - (default: (1,2)) an iterable of two positive
integers
OUTPUT:
infinite word
EXAMPLES:
The usual Kolakoski word::
sage: w = words.KolakoskiWord()
sage: w
word: 1221121221221121122121121221121121221221...
sage: w.delta()
word: 1221121221221121122121121221121121221221...
The other Kolakoski word on the same alphabet::
sage: w = words.KolakoskiWord(alphabet = (2,1))
sage: w
word: 2211212212211211221211212211211212212211...
sage: w.delta()
word: 2211212212211211221211212211211212212211...
It is naturally generalized to any two integers alphabet::
sage: w = words.KolakoskiWord(alphabet = (2,5))
sage: w
word: 2255222225555522552255225555522222555552...
sage: w.delta()
word: 2255222225555522552255225555522222555552...
TESTS::
sage: for i in range(1,10):
....: for j in range(1,10):
....: if i != j:
....: w = words.KolakoskiWord(alphabet=(i,j))
....: assert w[:50] == w.delta()[:50]
::
sage: words.KolakoskiWord((0, 2))
Traceback (most recent call last):
...
ValueError: The alphabet (=(0, 2)) must consist of two distinct positive integers
REFERENCES:
.. [Kolakoski66] William Kolakoski, proposal 5304, American Mathematical Monthly
72 (1965), 674; for a partial solution, see "Self Generating Runs,"
by Necdet Üçoluk, Amer. Math. Mon. 73 (1966), 681-2.
"""
a, b = alphabet
if a not in ZZ or a <= 0 or b not in ZZ or b <= 0 or a == b:
msg = 'The alphabet (=%s) must consist of two distinct positive integers'%(alphabet,)
raise ValueError(msg)
return InfiniteWords(alphabet)(self._KolakoskiWord_iterator(a, b), datatype = 'iter')
def _KolakoskiWord_iterator(self, a=1, b=2):
r"""
Returns an iterator over the Kolakoski word over ``{a,b}``
and starting with ``a``.
Let `A = \{a,b\}` be an alphabet, where `a` and `b` are two
distinct positive integers. The Kolakoski word `K_{a,b}`
over `A` and starting with `a` is the unique infinite word `w`
such that `w = \Delta(w)`, where `\Delta(w)` is the word
encoding the runs of `w` (see ``delta()`` method on words for
more details).
Note that `K_{a,b} \neq K_{b,a}`. On the other hand, the
words `K_{a,b}` and `K_{b,a}` are the unique two words over `A`
that are fixed by `\Delta`.
INPUT:
- ``a`` - positive integer (default: 1), the first letter occurring
in the returned Kolakoski word.
- ``b`` - positive integer (default: 2), the second and last letter
occuring in the returned Kolakoski word.
OUTPUT:
iterator
EXAMPLES:
The first ten letters of `K_{3,5}`::
sage: iter = words._KolakoskiWord_iterator(3, 5)
sage: Word(iter)[:10]
word: 3335553335
See ``words.KolakoskiWord()`` for more documentation.
"""
# First, we need to treat the basis case
w = [a] * a
for _ in range(a):
yield a
if a == 1:
w.extend([b] * b)
for _ in range(b):
yield b
w.pop(0)
w.pop(0)
# Letters swap function
bar = lambda x : a if x == b else b
current_letter = bar(w[-1])
# Now we are ready to go in the recursive part
while True:
for _ in range(w[0]):
yield current_letter
w.append(current_letter)
w.pop(0)
current_letter = bar(current_letter)
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None):
r"""
Returns the lower mechanical word with slope `\alpha` and
intercept `\rho`
The lower mechanical word `s_{\alpha,\rho}` with
slope `\alpha` and intercept `\rho` is defined by
`s_{\alpha,\rho}(n) = \lfloor\alpha(n+1) + \rho\rfloor -
\lfloor\alpha n + \rho\rfloor`. [Loth02]_
INPUT:
- ``alpha`` -- real number such that `0 \leq\alpha\leq 1`
- ``rho`` -- real number (optional, default: 0)
- ``alphabet`` -- iterable of two elements or ``None``
(optional, default: ``None``)
OUTPUT:
infinite word
EXAMPLES::
sage: words.LowerMechanicalWord(1/golden_ratio^2)
word: 0010010100100101001010010010100100101001...
sage: words.LowerMechanicalWord(1/5)
word: 0000100001000010000100001000010000100001...
sage: words.LowerMechanicalWord(1/pi)
word: 0001001001001001001001000100100100100100...
TESTS::
sage: m = words.LowerMechanicalWord(1/golden_ratio^2)[1:]
sage: s = words.CharacteristicSturmianWord(1/golden_ratio^2)
sage: m[:500] == s[:500]
True
Check that this returns a word in an alphabet (:trac:`10054`)::
sage: words.UpperMechanicalWord(1/golden_ratio^2).parent()
Infinite words over {0, 1}
"""
if not 0 <= alpha <= 1:
raise ValueError("Parameter alpha (=%s) must be in [0,1]."%alpha)
from sage.functions.other import floor
from sage.combinat.words.alphabet import build_alphabet
if alphabet is None or alphabet in ((0, 1), [0, 1]):
alphabet = build_alphabet([0, 1])
s = lambda n: floor(alpha*(n+1) + rho) - floor(alpha*n + rho)
else:
alphabet = build_alphabet(alphabet)
card = alphabet.cardinality()
if card != 2:
raise TypeError("size of alphabet (=%s) must be two"%card)
s = lambda n: alphabet[floor(alpha*(n+1) + rho) - floor(alpha*n + rho)]
return InfiniteWords(alphabet)(s)
def UpperMechanicalWord(self, alpha, rho=0, alphabet=None):
r"""
Returns the upper mechanical word with slope `\alpha` and
intercept `\rho`
The upper mechanical word `s'_{\alpha,\rho}` with
slope `\alpha` and intercept `\rho` is defined by
`s'_{\alpha,\rho}(n) = \lceil\alpha(n+1) + \rho\rceil -
\lceil\alpha n + \rho\rceil`. [Loth02]_
INPUT:
- ``alpha`` -- real number such that `0 \leq\alpha\leq 1`
- ``rho`` -- real number (optional, default: 0)
- ``alphabet`` -- iterable of two elements or ``None``
(optional, default: ``None``)
OUTPUT:
infinite word
EXAMPLES::
sage: words.UpperMechanicalWord(1/golden_ratio^2)
word: 1010010100100101001010010010100100101001...
sage: words.UpperMechanicalWord(1/5)
word: 1000010000100001000010000100001000010000...
sage: words.UpperMechanicalWord(1/pi)
word: 1001001001001001001001000100100100100100...
TESTS::
sage: m = words.UpperMechanicalWord(1/golden_ratio^2)[1:]
sage: s = words.CharacteristicSturmianWord(1/golden_ratio^2)
sage: m[:500] == s[:500]
True
Check that this returns a word in an alphabet (:trac:`10054`)::
sage: words.UpperMechanicalWord(1/golden_ratio^2).parent()
Infinite words over {0, 1}
"""
if not 0 <= alpha <= 1:
raise ValueError("Parameter alpha (=%s) must be in [0,1]."%alpha)
from sage.functions.other import ceil
from sage.combinat.words.alphabet import build_alphabet
if alphabet is None or alphabet in ((0, 1), [0, 1]):
alphabet = build_alphabet([0, 1])
s = lambda n: ceil(alpha*(n+1) + rho) - ceil(alpha*n + rho)
else:
alphabet = build_alphabet(alphabet)
card = alphabet.cardinality()
if card != 2:
raise TypeError("size of alphabet (=%s) must be two"%card)
s = lambda n: alphabet[ceil(alpha*(n+1) + rho) - ceil(alpha*n + rho)]
return InfiniteWords(alphabet)(s)
def StandardEpisturmianWord(self, directive_word):
r"""
Returns the standard episturmian word (or epistandard word) directed by
directive_word. Over a 2-letter alphabet, this function
gives characteristic Sturmian words.
An infinite word `w` over a finite alphabet `A` is said to be
*standard episturmian* (or *epistandard*) iff there exists an
infinite word `x_1x_2x_3\cdots` over `A` (called the *directive
word* of `w`) such that `w` is the limit as `n` goes to infinity of
`Pal(x_1\cdots x_n)`, where `Pal` is the iterated palindromic closure
function.
Note that an infinite word is *episturmian* if it has the same set
of factors as some epistandard word.
See for instance [DJP01]_, [JP02]_, and [GJ07]_.
INPUT:
- ``directive_word`` - an infinite word or a period of a periodic
infinite word
EXAMPLES::
sage: Fibonacci = words.StandardEpisturmianWord(Words('ab')('ab')); Fibonacci
word: abaababaabaababaababaabaababaabaababaaba...
sage: Tribonacci = words.StandardEpisturmianWord(Words('abc')('abc')); Tribonacci
word: abacabaabacababacabaabacabacabaabacababa...
sage: S = words.StandardEpisturmianWord(Words('abcd')('aabcabada')); S
word: aabaacaabaaabaacaabaabaacaabaaabaacaabaa...
sage: S = words.StandardEpisturmianWord(Fibonacci); S
word: abaabaababaabaabaababaabaababaabaabaabab...
sage: S[:25]
word: abaabaababaabaabaababaaba
sage: S = words.StandardEpisturmianWord(Tribonacci); S
word: abaabacabaabaabacabaababaabacabaabaabaca...
sage: words.StandardEpisturmianWord(123)
Traceback (most recent call last):
...
TypeError: directive_word is not a word, so it cannot be used to build an episturmian word
sage: words.StandardEpisturmianWord(Words('ab'))
Traceback (most recent call last):
...
TypeError: directive_word is not a word, so it cannot be used to build an episturmian word
REFERENCES:
.. [JP02] \J. Justin, G. Pirillo, Episturmian words and episturmian
morphisms, Theoret. Comput. Sci. 276 (2002) 281--313.
.. [GJ07] \A. Glen, J. Justin, Episturmian words: a survey, Preprint,
2007, :arxiv:`0801.1655`.
"""
if not isinstance(directive_word, Word_class):
raise TypeError("directive_word is not a word, so it cannot be used to build an episturmian word")
epistandard = directive_word.parent()(\
self._StandardEpisturmianWord_LetterIterator(directive_word), \
datatype='iter')
return epistandard
def _StandardEpisturmianWord_LetterIterator(self, directive_word):
r"""
Internal iterating over the symbols of the standard episturmian
word defined by the (directive) word directive_word.
An infinite word `w` over a finite alphabet `A` is standard episturmian
(or epistandard) iff there exists an infinite word `x_1x_2x_3\ldots`
over `A` (called the directive word of `w`) such that `w` is the limit
as `n` goes to infinity of `Pal(x_1x_2\cdots x_n)`, where `Pal` is the
iterated palindromic closure function.
INPUT:
- ``directive_word`` - an infinite word or a finite word. If
directive_word is finite, then it is repeated to give
an infinite word.
TESTS::
sage: import itertools
sage: it = words._StandardEpisturmianWord_LetterIterator(Word('ab'))
sage: list(itertools.islice(it, 13r))
['a', 'b', 'a', 'a', 'b', 'a', 'b', 'a', 'a', 'b', 'a', 'a', 'b']
"""
if isinstance(directive_word, FiniteWord_class):
d = cycle(directive_word)
else:
d = iter(directive_word)
W = directive_word.parent()
w = W(next(d))
n = 0
while True:
for x in w[n:]:
n += 1
yield x
else:
w = W(w*W(next(d))).palindromic_closure()
def MinimalSmoothPrefix(self, n):
r"""
This function finds and returns the minimal smooth prefix of length
``n``.
See [BMP07]_ for a definition.
INPUT:
- ``n`` -- the desired length of the prefix
OUTPUT:
word -- the prefix
.. NOTE::
Be patient, this function can take a really long time if asked
for a large prefix.
EXAMPLES::
sage: words.MinimalSmoothPrefix(10)
word: 1212212112
REFERENCES:
.. [BMP07] \S. Brlek, G. Melançon, G. Paquin, Properties of the extremal
infinite smooth words, Discrete Math. Theor. Comput. Sci. 9 (2007)
33--49.
"""
tab = []
W = FiniteWords([1, 2])
suff1 = W([1, 2, 2]).phi_inv()
suff2 = W([2, 2]).phi_inv()
w = [1]
tab = _build_tab(1, tab, W)
for k in range(1, n):
if suff1._phi_inv_tab(tab) < suff2._phi_inv_tab(tab):
w.append(1)
tab = _build_tab(1, tab, W)
else:
w.append(2)
tab = _build_tab(2, tab, W)
return W(w)
def RandomWord(self, n, m=2, alphabet=None):
r"""
Return a random word of length `n` over the given `m`-letter
alphabet.
INPUT:
- ``n`` - integer, the length of the word
- ``m`` - integer (default 2), the size of the output alphabet
- ``alphabet`` - (default is `\{0,1,...,m-1\}`) any container of
length m that is suitable to build an instance of
OrderedAlphabet (list, tuple, str, ...)
EXAMPLES::
sage: words.RandomWord(10) # random results
word: 0110100101
sage: words.RandomWord(10, 4) # random results
word: 0322313320
sage: words.RandomWord(100, 7) # random results
word: 2630644023642516442650025611300034413310...
sage: words.RandomWord(100, 7, range(-3,4)) # random results
word: 1,3,-1,-1,3,2,2,0,1,-2,1,-1,-3,-2,2,0,3,0,-3,0,3,0,-2,-2,2,0,1,-3,2,-2,-2,2,0,2,1,-2,-3,-2,-1,0,...
sage: words.RandomWord(100, 5, "abcde") # random results
word: acebeaaccdbedbbbdeadeebbdeeebeaaacbadaac...
sage: words.RandomWord(17, 5, "abcde") # random results
word: dcacbbecbddebaadd
TESTS::
sage: words.RandomWord(2,3,"abcd")
Traceback (most recent call last):
...
TypeError: alphabet does not contain 3 distinct elements
"""
if alphabet is None:
alphabet = list(range(m))
if len(set(alphabet)) != m:
raise TypeError("alphabet does not contain %s distinct elements" % m)
return FiniteWords(alphabet)([alphabet[randint(0,m-1)] for i in range(n)])
LowerChristoffelWord = LowerChristoffelWord
ChristoffelWord = LowerChristoffelWord
def UpperChristoffelWord(self, p, q, alphabet=(0,1)):
r"""
Returns the upper Christoffel word of slope `p/q`, where
`p` and `q` are relatively prime non-negative
integers, over the given alphabet.
The *upper Christoffel word of slope `p/q`* is equal to the
reversal of the lower Christoffel word of slope `p/q`.
Equivalently, if `xuy` is the lower Christoffel word of
slope `p/q`, where `x` and `y` are letters,
then `yux` is the upper Christoffel word of slope
`p/q` (because `u` is a palindrome).
INPUT:
- ``alphabet`` - any container of length two that is
suitable to build an instance of OrderedAlphabet (list, tuple, str,
...)
EXAMPLES::
sage: words.UpperChristoffelWord(1,0)
word: 1
::
sage: words.UpperChristoffelWord(0,1)
word: 0
::
sage: words.UpperChristoffelWord(1,1)
word: 10
::
sage: words.UpperChristoffelWord(4,7)
word: 10100100100
TESTS::
sage: words.UpperChristoffelWord(51,43,"abc")
Traceback (most recent call last):
...
ValueError: alphabet must contain exactly two distinct elements
"""
w = words.LowerChristoffelWord(p, q, alphabet=alphabet).reversal()
return w
@cached_method
def _fibonacci_tile(self, n, q_0=None, q_1=3):
r"""
Returns the word `q_n` defined by the recurrence below.
The sequence `(q_n)_{n\in\NN}` is defined by `q_0=\varepsilon`,
`q_1=3` and
.. MATH::
q_n = \begin{cases}
q_{n-1}q_{n-2} & \text{if} n\equiv 2 \mod 3, \\
q_{n-1}\bar{q_{n-2}} & \text{if} n\equiv 0,1 \mod 3.
\end{cases}
where the operator `\bar{\,}` exchanges the `1` and `3`.
INPUT:
- ``n`` - non negative integer
- ``q_0`` - first initial value (default: None) It can be None, 0, 1,
2 or 3.
- ``q_1`` - second initial value (default: 3) It can be None, 0, 1, 2
or 3.
EXAMPLES::
sage: for i in range(10): words._fibonacci_tile(i)
word:
word: 3
word: 3
word: 31
word: 311
word: 31131
word: 31131133
word: 3113113313313
word: 311311331331331131133
word: 3113113313313311311331331331131131
REFERENCES:
[BmBGL09]_
"""
from sage.combinat.words.all import WordMorphism
W = FiniteWords([0,1,2,3])
bar = WordMorphism({0:0,1:3,3:1,2:2},codomain=W)
if n==0:
a = [] if q_0 is None else [q_0]
return W(a)
elif n==1:
b = [] if q_1 is None else [q_1]
return W(b)
elif n%3 == 2:
u = self._fibonacci_tile(n-1,q_0,q_1)
v = self._fibonacci_tile(n-2,q_0,q_1)
return u * v
else:
u = self._fibonacci_tile(n-1,q_0,q_1)
v = bar(self._fibonacci_tile(n-2,q_0,q_1))
return u * v
def fibonacci_tile(self, n):
r"""
Returns the `n`-th Fibonacci Tile [BmBGL09]_.
EXAMPLES::
sage: for i in range(3): words.fibonacci_tile(i)
Path: 3210
Path: 323030101212
Path: 3230301030323212323032321210121232121010...
"""
w = self._fibonacci_tile(3*n+1)
w = w**4
from sage.combinat.words.paths import WordPaths
P = WordPaths([0,1,2,3])
l = list(w.partial_sums(start=3,mod=4))
return P(l)[:-1]
def dual_fibonacci_tile(self, n):
r"""
Returns the `n`-th dual Fibonacci Tile [BmBGL09]_.
EXAMPLES::
sage: for i in range(4): words.dual_fibonacci_tile(i)
Path: 3210
Path: 32123032301030121012
Path: 3212303230103230321232101232123032123210...
Path: 3212303230103230321232101232123032123210...
"""
w = self._fibonacci_tile(3*n+1,3,3)
w = w**4
from sage.combinat.words.paths import WordPaths
P = WordPaths([0,1,2,3])
l = list(w.partial_sums(start=3,mod=4))
return P(l)[:-1]
def _s_adic_iterator(self, sequence, letters):
r"""
Returns the iterator over the `s`-adic infinite word obtained from a
sequence of morphisms applied on letters where the hypothesis of
nested prefixes is used.
DEFINITION (from [Fogg]_):
Let `w` be a infinite word over an alphabet `A = A_0`. A
standard representation of $w$ is obtained from a sequence of
substitutions `\sigma_k : A_{k+1} \to A_k` and a sequence of letters
`a_k \in A_k` such that:
.. MATH::
\lim_{k\to\infty} \sigma_0 \circ \sigma_1 \circ \cdots
\sigma_k(a_k).
Given a set of substitutions `S`, we say that the representation is
`S`-adic standard if the substitutions are chosen in `S`.
INPUT:
- ``sequence`` - An iterable sequence of morphisms. It may be finite
or infinite.
- ``letters`` - An iterable sequence of letters. The image of the
(i+1)-th letter under the (i+1)-th morphism must start with the i-th
letter.
OUTPUT:
iterator of letters
EXAMPLES:
Let's define three morphisms and compute the first nested succesive
prefixes of the `s`-adic word::
sage: m1 = WordMorphism('e->gh,f->hg')
sage: m2 = WordMorphism('c->ef,d->e')
sage: m3 = WordMorphism('a->cd,b->dc')
sage: Word(words._s_adic_iterator([m1],'e'))
word: gh
sage: Word(words._s_adic_iterator([m1,m2],'ec'))
word: ghhg
sage: Word(words._s_adic_iterator([m1,m2,m3],'eca'))
word: ghhggh
If the letters don't satisfy the hypothesis of the algorithm, an
error is raised::
sage: Word(words._s_adic_iterator([m1,m2,m3],'ecb'))
Traceback (most recent call last):
...
ValueError: The hypothesis of the algorithm used is not satisfied: the image of the 3-th letter (=b) under the 3-th morphism (=a->cd, b->dc) should start with the 2-th letter (=c).
Two examples of infinite `s`-adic words::
sage: tm = WordMorphism('a->ab,b->ba')
sage: fib = WordMorphism('a->ab,b->a')
sage: from itertools import repeat
sage: Word(words._s_adic_iterator(repeat(tm),repeat('a')))
word: abbabaabbaababbabaababbaabbabaabbaababba...
sage: Word(words._s_adic_iterator(repeat(fib),repeat('a')))
word: abaababaabaababaababaabaababaabaababaaba...
A less trivial infinite `s`-adic word::
sage: D = {4:tm,5:fib}
sage: tmword = words.ThueMorseWord([4,5])
sage: it = (D[a] for a in tmword)
sage: Word(words._s_adic_iterator(it, repeat('a')))
word: abbaababbaabbaabbaababbaababbaabbaababba...
The morphism `\sigma: a \mapsto ba, b \mapsto b` cannot satisfy the
hypothesis of the algorithm (nested prefixes)::
sage: sigma = WordMorphism('a->ba,b->b')
sage: Word(words._s_adic_iterator(repeat(sigma),repeat('a')))
Traceback (most recent call last):
...
ValueError: The hypothesis of the algorithm used is not satisfied: the image of the 2-th letter (=a) under the 2-th morphism (=a->ba, b->b) should start with the 1-th letter (=a).
AUTHORS:
- Sebastien Labbe (2009-12-18): initial version
"""
from itertools import tee
from builtins import zip
sequence_it,sequence = tee(sequence)
m = next(sequence_it)
codomain = m.codomain()
p = codomain.identity_morphism()
letters_it,letters = tee(letters)
precedent_letter = m(next(letters_it))[0]
yield precedent_letter
for (i,(m,a)) in enumerate(zip(sequence, letters)):
if not precedent_letter == m(a)[0]:
raise ValueError("The hypothesis of the algorithm used is not satisfied: the image of the %s-th letter (=%s) under the %s-th morphism (=%s) should start with the %s-th letter (=%s)."%(i+1,a,i+1,m,i,precedent_letter))
w = p(m(a)[1:])
for b in w:
yield b
p = p * m
precedent_letter = a
def s_adic(self, sequence, letters, morphisms=None):
r"""
Returns the `s`-adic infinite word obtained from a sequence of
morphisms applied on a letter.
DEFINITION (from [Fogg]_):
Let `w` be a infinite word over an alphabet `A = A_0`. A
standard representation of `w` is obtained from a sequence of
substitutions `\sigma_k : A_{k+1} \to A_k` and a sequence of letters
`a_k \in A_k` such that:
.. MATH::
\lim_{k\to\infty} \sigma_0 \circ \sigma_1 \circ \cdots
\sigma_k(a_k).
Given a set of substitutions `S`, we say that the representation is
`S`-adic standard if the substitutions are chosen in `S`.
INPUT:
- ``sequence`` - An iterable sequence of indices or of morphisms. It
may be finite or infinite. If ``sequence`` is infinite, the image
of the `(i+1)`-th letter under the `(i+1)`-th morphism must start
with the `i`-th letter.
- ``letters`` - A letter or a sequence of letters.
- ``morphisms`` - dict, list, callable or ``None`` (optional, default
``None``) an object that maps indices to morphisms. If ``None``, then
``sequence`` must consist of morphisms.
OUTPUT:
A word.
EXAMPLES:
Let's define three morphisms and compute the first nested succesive
prefixes of the `s`-adic word::
sage: m1 = WordMorphism('e->gh,f->hg')
sage: m2 = WordMorphism('c->ef,d->e')
sage: m3 = WordMorphism('a->cd,b->dc')
sage: words.s_adic([m1],'e')
word: gh
sage: words.s_adic([m1,m2],'ec')
word: ghhg
sage: words.s_adic([m1,m2,m3],'eca')
word: ghhggh
When the given sequence of morphism is finite, one may simply give
the last letter, i.e. ``'a'``, instead of giving all of them,
i.e. ``'eca'``::
sage: words.s_adic([m1,m2,m3],'a')
word: ghhggh
sage: words.s_adic([m1,m2,m3],'b')
word: ghghhg
If the letters don't satisfy the hypothesis of the algorithm
(nested prefixes), an error is raised::
sage: words.s_adic([m1,m2,m3],'ecb')
Traceback (most recent call last):
...
ValueError: The hypothesis of the algorithm used is not satisfied: the image of the 3-th letter (=b) under the 3-th morphism (=a->cd, b->dc) should start with the 2-th letter (=c).
Let's define the Thue-Morse morphism and the Fibonacci morphism
which will be used below to illustrate more examples and let's import
the ``repeat`` tool from the ``itertools``::
sage: tm = WordMorphism('a->ab,b->ba')
sage: fib = WordMorphism('a->ab,b->a')
sage: from itertools import repeat
Two trivial examples of infinite `s`-adic words::
sage: words.s_adic(repeat(tm),repeat('a'))
word: abbabaabbaababbabaababbaabbabaabbaababba...
::
sage: words.s_adic(repeat(fib),repeat('a'))
word: abaababaabaababaababaabaababaabaababaaba...
A less trivial infinite `s`-adic word::
sage: D = {4:tm,5:fib}
sage: tmword = words.ThueMorseWord([4,5])
sage: it = (D[a] for a in tmword)
sage: words.s_adic(it, repeat('a'))
word: abbaababbaabbaabbaababbaababbaabbaababba...
The same thing using a sequence of indices::
sage: tmword = words.ThueMorseWord([0,1])
sage: words.s_adic(tmword, repeat('a'), [tm,fib])
word: abbaababbaabbaabbaababbaababbaabbaababba...
The correspondance of the indices may be given as a dict::
sage: words.s_adic(tmword, repeat('a'), {0:tm,1:fib})
word: abbaababbaabbaabbaababbaababbaabbaababba...
because dict are more versatile for indices::
sage: tmwordTF = words.ThueMorseWord('TF')
sage: words.s_adic(tmwordTF, repeat('a'), {'T':tm,'F':fib})
word: abbaababbaabbaabbaababbaababbaabbaababba...
or by a callable::
sage: f = lambda n: tm if n == 0 else fib
sage: words.s_adic(words.ThueMorseWord(), repeat('a'), f)
word: abbaababbaabbaabbaababbaababbaabbaababba...
Random infinite `s`-adic words::
sage: from sage.misc.prandom import randint
sage: def it():
....: while True: yield randint(0,1)
sage: words.s_adic(it(), repeat('a'), [tm,fib])
word: abbaabababbaababbaabbaababbaabababbaabba...
sage: words.s_adic(it(), repeat('a'), [tm,fib])
word: abbaababbaabbaababbaababbaabbaababbaabba...
sage: words.s_adic(it(), repeat('a'), [tm,fib])
word: abaaababaabaabaaababaabaaababaaababaabaa...
An example where the sequences cycle on two morphisms and two
letters::
sage: G = WordMorphism('a->cd,b->dc')
sage: H = WordMorphism('c->ab,d->ba')
sage: from itertools import cycle
sage: words.s_adic([G,H],'ac')
word: cddc
sage: words.s_adic(cycle([G,H]),cycle('ac'))
word: cddcdccddccdcddcdccdcddccddcdccddccdcddc...
The morphism `\sigma: a\mapsto ba, b\mapsto b` can't satisfy the
hypothesis of the nested prefixes, but one may compute arbitrarily
long finite words having the limit `\sigma^\omega(a)`::
sage: sigma = WordMorphism('a->ba,b->b')
sage: words.s_adic(repeat(sigma),repeat('a'))
Traceback (most recent call last):
...
ValueError: The hypothesis of the algorithm used is not satisfied: the image of the 2-th letter (=a) under the 2-th morphism (=a->ba, b->b) should start with the 1-th letter (=a).
sage: words.s_adic([sigma],'a')
word: ba
sage: words.s_adic([sigma,sigma],'a')
word: bba
sage: words.s_adic([sigma]*3,'a')
word: bbba
sage: words.s_adic([sigma]*4,'a')
word: bbbba
sage: words.s_adic([sigma]*5,'a')
word: bbbbba
sage: words.s_adic([sigma]*6,'a')
word: bbbbbba
sage: words.s_adic([sigma]*7,'a')
word: bbbbbbba
The following examples illustrates an `S`-adic word defined over an
infinite set `S` of morphisms `x_h`::
sage: x = lambda h:WordMorphism({1:[2],2:[3]+[1]*(h+1),3:[3]+[1]*h})
sage: for h in [0,1,2,3]:
....: print("{} {}".format(h, x(h)))
0 1->2, 2->31, 3->3
1 1->2, 2->311, 3->31
2 1->2, 2->3111, 3->311
3 1->2, 2->31111, 3->3111
sage: w = Word(lambda n : valuation(n+1, 2) ); w
word: 0102010301020104010201030102010501020103...
sage: s = words.s_adic(w, repeat(3), x); s
word: 3232232232322322322323223223232232232232...
sage: prefixe = s[:10000]
sage: list(map(prefixe.number_of_factors, range(15)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
sage: [_[i+1] - _[i] for i in range(len(_)-1)]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
TESTS::
sage: tm = WordMorphism('a->ab,b->ba')
sage: fib = WordMorphism('a->ab,b->a')
sage: w = words.s_adic([fib,tm,tm,fib,tm,fib]*3,'a')
sage: w
word: abaaabaababaabaaababaaababaaabaababaabaa...
sage: w.length()
32400
sage: w.parent()
Finite words over {'a', 'b'}
sage: type(w)
<class 'sage.combinat.words.word.FiniteWord_callable_with_caching'>
::
sage: words.s_adic([fib,tm,tm,fib,tm,fib],'aaaaaaa')
word: abaaabaababaabaaababaaababaaabaababa
::
sage: words.s_adic([0,1,0,1,0,1,0,1],'a',[tm,fib])
word: abbaabababbaabbaababbaababbaabababbaabba...
::
sage: words.s_adic([fib,fib],'bb')
Traceback (most recent call last):
...
ValueError: The hypothesis of the algorithm used is not satisfied: the image of the 2-th letter (=b) under the 2-th morphism (=a->ab, b->a) should start with the 1-th letter (=b).
Test on different letters::
sage: tm = WordMorphism({0:[0,1], 1:[1,0]})
sage: fib = WordMorphism({0:[0,1], 1:[0]})
sage: f = lambda n: tm if n == 0 else fib
sage: words.s_adic(words.ThueMorseWord(), repeat(0), f)
word: 0110010110011001100101100101100110010110...
Testing the message error for the third argument::
sage: words.s_adic(words.ThueMorseWord(), repeat(0), 5)
Traceback (most recent call last):
...
TypeError: morphisms (=5) must be None, callable or provide a __getitem__ method.
AUTHORS:
- Sebastien Labbe (2009-12-18): initial version
"""
if morphisms is None:
seq = sequence
elif hasattr(morphisms, '__getitem__'):
seq = (morphisms[i] for i in sequence)
elif hasattr(morphisms, '__call__'):
seq = (morphisms(i) for i in sequence)
else:
raise TypeError("morphisms (=%s) must be None, callable or provide a __getitem__ method."%morphisms)
from sage.combinat.words.word import FiniteWord_class
if isinstance(sequence,(tuple,list,str,FiniteWord_class)) \
and hasattr(letters, "__len__") and len(letters) == 1:
from sage.misc.all import prod
return prod(seq)(letters)
from itertools import tee
seq_it,seq= tee(seq)
m = next(seq_it)
W = m.codomain()
kwds = {}
kwds['data'] = self._s_adic_iterator(seq,letters)
kwds['datatype'] = 'iter'
kwds['caching'] = True
#kwds['check'] = False
return W.shift()(**kwds)
def PalindromicDefectWord(self, k=1, alphabet='ab'):
r"""
Return the finite word `w = a b^k a b^{k-1} a a b^{k-1} a b^{k} a`.
As described by Brlek, Hamel, Nivat and Reutenauer in [BHNR04]_, this
finite word `w` is such that the infinite periodic word `w^{\omega}`
has palindromic defect ``k``.
INPUT:
- ``k`` -- positive integer (optional, default: 1)
- ``alphabet`` -- iterable (optional, default: ``'ab'``) of size two
OUTPUT:
finite word
EXAMPLES::
sage: words.PalindromicDefectWord(10)
word: abbbbbbbbbbabbbbbbbbbaabbbbbbbbbabbbbbbb...
::
sage: w = words.PalindromicDefectWord(3)
sage: w
word: abbbabbaabbabbba
sage: w.defect()
0
sage: (w^2).defect()
3
sage: (w^3).defect()
3
On other alphabets::
sage: words.PalindromicDefectWord(3, alphabet='cd')
word: cdddcddccddcdddc
sage: words.PalindromicDefectWord(3, alphabet=['c', 3])
word: c333c33cc33c333c
TESTS::
sage: k = 25
sage: (words.PalindromicDefectWord(k)^2).defect()
25
If k is negative or zero, then we get the same word::
sage: words.PalindromicDefectWord(0)
word: aaaaaa
sage: words.PalindromicDefectWord(-3)
word: aaaaaa
"""
kk = k-1
a, b = alphabet
if not (isinstance(a, str) and isinstance(b, str)):
a, b = (a,), (b,)
w = a + b*k + a + b*kk + a + a + b*kk + a + b*k + a
return FiniteWords(alphabet)(w)
def BaumSweetWord(self):
r"""
Returns the Baum-Sweet Word.
The Baum-Sweet Sequence is an infinite word over the alphabet `\{0,1\}`
defined by the following string substitution rules:
`00 \rightarrow 0000`
`01 \rightarrow 1001`
`10 \rightarrow 0100`
`11 \rightarrow 1101`
The substitution rule above can be considered as a morphism on the
submonoid of `\{0,1\}` generated by `\{00,01,10,11\}` (which is a free
monoid on these generators).
It is also defined as the concatenation of the terms from the Baum-Sweet
Sequence:
.. MATH::
b_n = \begin{cases}
0, & \text{if } n = 0 \\
1, & \text{if } m \text{ is even} \\
b_{\frac{m-1}{2}}, & \text{if } m \text{ is odd}
\end{cases}
where `n=m4^k` and `m` is not divisible by 4 if `m \neq 0`.
The individual terms of the Baum-Sweet Sequence are also given by:
.. MATH::
b_n = \begin{cases}
1, & \text{if the binary representation of} n \text{ contains no block of consecutive 0's of odd length}\\
0, & \text{otherwise}\\
\end{cases}\\
for `n > 0` with `b_0 = 1`.
For more information see:
:wikipedia:`Baum-Sweet_sequence`.
EXAMPLES:
Baum-Sweet Word::
sage: w = words.BaumSweetWord(); w
word: 1101100101001001100100000100100101001001...
Block Definition::
sage: w = words.BaumSweetWord()
sage: f = lambda n: '1' if all(len(x)%2==0 for x in bin(n)[2:].split('1')) else '0'
sage: all(f(i) == w[i] for i in range(1,100))
True
"""
outer = WordMorphism('a->00,b->01,c->10,d->11')
inner = WordMorphism('a->aa,b->cb,c->ba,d->db')
return outer(inner.fixed_point('d'))
words = WordGenerator()
| 35.376946 | 232 | 0.56017 |
from __future__ import print_function
from six.moves import range
from itertools import cycle, count
from random import randint
from sage.misc.cachefunc import cached_method
from sage.rings.all import ZZ, RR
from sage.rings.infinity import Infinity
from sage.combinat.words.abstract_word import Word_class
from sage.combinat.words.word import FiniteWord_list
from sage.combinat.words.finite_word import FiniteWord_class, Factorization
from sage.combinat.words.words import FiniteWords, InfiniteWords
from sage.combinat.words.morphism import WordMorphism
from sage.arith.all import gcd
from sage.misc.decorators import rename_keyword
def _build_tab(sym, tab, W):
c = W.alphabet().cardinality()
res = [sym]
if len(tab) == 0:
return res
if sym == 1:
res += tab
res[1] = (res[1] % c) + 1
return res
w = W([sym]).delta_inv(W, tab[0])
w = w[1:]
res.append((w[-1] % c) + 1)
for i in range(1, len(tab)):
w = w.delta_inv(W, tab[i])
res.append((w[-1] % c) + 1)
return res
class LowerChristoffelWord(FiniteWord_list):
def __init__(self, p, q, alphabet=(0,1), algorithm='cf'):
if len(set(alphabet)) != 2:
raise ValueError("alphabet must contain exactly two distinct elements")
if gcd(p,q) != 1:
raise ValueError("%s and %s are not relatively prime" % (p, q))
if algorithm == 'linear':
w = []
u = 0
if (p, q) == (0, 1):
w = [alphabet[0]]
else:
for i in range(p + q):
v = (u+p) % (p+q)
new_letter = alphabet[0] if u < v else alphabet[1]
w.append(new_letter)
u = v
elif algorithm == 'cf':
if (p, q) == (0, 1):
w = [alphabet[0]]
elif (p, q) == (1, 0):
w = [alphabet[1]]
else:
from sage.rings.rational_field import QQ
cf = QQ((p, q)).continued_fraction_list()
u = [alphabet[0]]
v = [alphabet[1]]
start = 1 if p < q else 0
for i in range(start, len(cf)-1):
if i % 2 == 0:
u = u + v * cf[i]
else:
v = u * cf[i] + v
i = len(cf)-1
if i % 2 == 0:
u = u + v * (cf[i]-1)
else:
v = u * (cf[i]-1) + v
w = u + v
else:
raise ValueError('Unknown algorithm (=%s)'%algorithm)
super(LowerChristoffelWord, self).__init__(FiniteWords(alphabet), w)
self.__p = p
self.__q = q
def markoff_number(self):
from sage.matrix.constructor import matrix
eta = {0:matrix(2,[2,1,1,1]), 1:matrix(2,[5,2,2,1])}
M = matrix(2,[1,0,0,1])
for a in self:
M *= eta[a]
return M.trace()/3
def standard_factorization(self):
p, q = self.__p, self.__q
index = 0
u = 0
for i in range(p + q):
v = (u+p) % (p+q)
if v == 1:
index = i
break
u = v
w1, w2 = self[:index+1], self[index+1:]
return Factorization([LowerChristoffelWord(w1.count(1),w1.count(0)),
LowerChristoffelWord(w2.count(1),w2.count(0))])
def __reduce__(self):
return self.__class__, (self.__p, self.__q, self.parent().alphabet())
class WordGenerator(object):
def ThueMorseWord(self, alphabet=(0, 1), base=2):
W = InfiniteWords(alphabet)
alphabet = W.alphabet()
m = alphabet.cardinality()
if base < 2 or m < 2 :
raise ValueError("base (=%s) and len(alphabet) (=%s) must be at least 2"%(base, m))
from functools import partial
f = partial(self._ThueMorseWord_nth_digit, alphabet=alphabet, base=base)
return W(f, datatype='callable')
def _ThueMorseWord_nth_digit(self, n, alphabet=(0,1), base=2):
if n < 0:
raise NotImplementedError("nth digit of Thue-Morse word is not implemented for negative value of n")
m = len(alphabet)
if base == 2 and m == 2:
for tn in count():
if n == 0:
return alphabet[tn & 1]
n &= n - 1
elif base < 2 or m < 2 :
raise ValueError("base (=%s) and len(alphabet) (=%s) must be at least 2"%(base, m))
else:
return alphabet[ZZ(sum(ZZ(n).digits(base = base))).mod(m)]
def FibonacciWord(self, alphabet=(0, 1), construction_method="recursive"):
W = InfiniteWords(alphabet)
alphabet = W.alphabet()
if alphabet.cardinality() != 2:
raise TypeError("alphabet does not contain two distinct elements")
a,b = alphabet
if construction_method == "recursive":
w = W(self._FibonacciWord_RecursiveConstructionIterator(alphabet),
datatype='iter')
return w
elif construction_method in ("fixed point", "fixed_point"):
d = {b:[a],a:[a,b]}
w = self.FixedPointOfMorphism(d, a)
return w
elif construction_method == "function":
from sage.functions.other import sqrt, floor
phi = (1 + sqrt(5))/2
f = lambda n:a if floor((n+2)*phi) - floor((n+1)*phi) == 2 else b
return W(f)
else:
raise NotImplementedError
def _FibonacciWord_RecursiveConstructionIterator(self,alphabet=(0,1)):
Fib0 = [0]
Fib1 = [0,1]
n = 0
while True:
it = iter(Fib1[n:])
for i in it:
n += 1
yield alphabet[i]
else:
Fib1, Fib0 = Fib1 + Fib0, Fib1
def FixedPointOfMorphism(self, morphism, first_letter):
return WordMorphism(morphism).fixed_point(letter=first_letter)
def CodingOfRotationWord(self, alpha, beta, x=0, alphabet=(0,1)):
if len(set(alphabet)) != 2:
raise TypeError("alphabet does not contain two distinct elements")
from functools import partial
f = partial(self._CodingOfRotationWord_function,alpha=alpha,beta=beta,x=x,alphabet=alphabet)
w = InfiniteWords(alphabet)(f, datatype='callable')
return w
def _CodingOfRotationWord_function(self, n, alpha, beta, x=0, alphabet=(0,1)):
hauteur = x + n * alpha
fracH = hauteur.frac()
if fracH < 0:
fracH += 1
if 0 <= fracH < beta:
return alphabet[1]
else:
return alphabet[0]
@rename_keyword(cf='slope')
def CharacteristicSturmianWord(self, slope, alphabet=(0, 1), bits=None):
if len(set(alphabet)) != 2:
raise TypeError("alphabet does not contain two distinct elements")
if slope in RR:
if not 0 < slope < 1:
msg = "The argument slope (=%s) must be in ]0,1[."%slope
raise ValueError(msg)
from sage.rings.continued_fraction import continued_fraction
cf = continued_fraction(slope)
if cf.length() == Infinity:
parent = InfiniteWords(alphabet)
else:
parent = FiniteWords(alphabet)
cf = iter(cf)
elif hasattr(slope, '__iter__'):
cf = iter(slope)
parent = InfiniteWords(alphabet)
else:
raise TypeError("slope (=%s) must be a real number"%slope +
"or an iterable.")
w = parent(self._CharacteristicSturmianWord_LetterIterator(cf,alphabet),
datatype='iter')
return w
def _CharacteristicSturmianWord_LetterIterator(self, cf, alphabet=(0,1)):
try:
if next(cf) != 0:
raise ValueError("The first term of the continued fraction expansion must be zero.")
except StopIteration:
return
s0 = [1]
s1 = [0]
try:
e = next(cf)
except StopIteration:
return
if not e >= 1:
raise ValueError("The second term of the continued fraction expansion must be larger or equal to 1.")
s1, s0 = s1*(e-1) + s0, s1
n = 0
while True:
try:
for i in s1[n:]:
n += 1
yield alphabet[i]
else:
s1, s0 = s1*next(cf) + s0, s1
except StopIteration:
return
def KolakoskiWord(self, alphabet=(1,2)):
a, b = alphabet
if a not in ZZ or a <= 0 or b not in ZZ or b <= 0 or a == b:
msg = 'The alphabet (=%s) must consist of two distinct positive integers'%(alphabet,)
raise ValueError(msg)
return InfiniteWords(alphabet)(self._KolakoskiWord_iterator(a, b), datatype = 'iter')
def _KolakoskiWord_iterator(self, a=1, b=2):
w = [a] * a
for _ in range(a):
yield a
if a == 1:
w.extend([b] * b)
for _ in range(b):
yield b
w.pop(0)
w.pop(0)
bar = lambda x : a if x == b else b
current_letter = bar(w[-1])
while True:
for _ in range(w[0]):
yield current_letter
w.append(current_letter)
w.pop(0)
current_letter = bar(current_letter)
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None):
if not 0 <= alpha <= 1:
raise ValueError("Parameter alpha (=%s) must be in [0,1]."%alpha)
from sage.functions.other import floor
from sage.combinat.words.alphabet import build_alphabet
if alphabet is None or alphabet in ((0, 1), [0, 1]):
alphabet = build_alphabet([0, 1])
s = lambda n: floor(alpha*(n+1) + rho) - floor(alpha*n + rho)
else:
alphabet = build_alphabet(alphabet)
card = alphabet.cardinality()
if card != 2:
raise TypeError("size of alphabet (=%s) must be two"%card)
s = lambda n: alphabet[floor(alpha*(n+1) + rho) - floor(alpha*n + rho)]
return InfiniteWords(alphabet)(s)
def UpperMechanicalWord(self, alpha, rho=0, alphabet=None):
if not 0 <= alpha <= 1:
raise ValueError("Parameter alpha (=%s) must be in [0,1]."%alpha)
from sage.functions.other import ceil
from sage.combinat.words.alphabet import build_alphabet
if alphabet is None or alphabet in ((0, 1), [0, 1]):
alphabet = build_alphabet([0, 1])
s = lambda n: ceil(alpha*(n+1) + rho) - ceil(alpha*n + rho)
else:
alphabet = build_alphabet(alphabet)
card = alphabet.cardinality()
if card != 2:
raise TypeError("size of alphabet (=%s) must be two"%card)
s = lambda n: alphabet[ceil(alpha*(n+1) + rho) - ceil(alpha*n + rho)]
return InfiniteWords(alphabet)(s)
def StandardEpisturmianWord(self, directive_word):
if not isinstance(directive_word, Word_class):
raise TypeError("directive_word is not a word, so it cannot be used to build an episturmian word")
epistandard = directive_word.parent()(\
self._StandardEpisturmianWord_LetterIterator(directive_word), \
datatype='iter')
return epistandard
def _StandardEpisturmianWord_LetterIterator(self, directive_word):
if isinstance(directive_word, FiniteWord_class):
d = cycle(directive_word)
else:
d = iter(directive_word)
W = directive_word.parent()
w = W(next(d))
n = 0
while True:
for x in w[n:]:
n += 1
yield x
else:
w = W(w*W(next(d))).palindromic_closure()
def MinimalSmoothPrefix(self, n):
tab = []
W = FiniteWords([1, 2])
suff1 = W([1, 2, 2]).phi_inv()
suff2 = W([2, 2]).phi_inv()
w = [1]
tab = _build_tab(1, tab, W)
for k in range(1, n):
if suff1._phi_inv_tab(tab) < suff2._phi_inv_tab(tab):
w.append(1)
tab = _build_tab(1, tab, W)
else:
w.append(2)
tab = _build_tab(2, tab, W)
return W(w)
def RandomWord(self, n, m=2, alphabet=None):
if alphabet is None:
alphabet = list(range(m))
if len(set(alphabet)) != m:
raise TypeError("alphabet does not contain %s distinct elements" % m)
return FiniteWords(alphabet)([alphabet[randint(0,m-1)] for i in range(n)])
LowerChristoffelWord = LowerChristoffelWord
ChristoffelWord = LowerChristoffelWord
def UpperChristoffelWord(self, p, q, alphabet=(0,1)):
w = words.LowerChristoffelWord(p, q, alphabet=alphabet).reversal()
return w
@cached_method
def _fibonacci_tile(self, n, q_0=None, q_1=3):
from sage.combinat.words.all import WordMorphism
W = FiniteWords([0,1,2,3])
bar = WordMorphism({0:0,1:3,3:1,2:2},codomain=W)
if n==0:
a = [] if q_0 is None else [q_0]
return W(a)
elif n==1:
b = [] if q_1 is None else [q_1]
return W(b)
elif n%3 == 2:
u = self._fibonacci_tile(n-1,q_0,q_1)
v = self._fibonacci_tile(n-2,q_0,q_1)
return u * v
else:
u = self._fibonacci_tile(n-1,q_0,q_1)
v = bar(self._fibonacci_tile(n-2,q_0,q_1))
return u * v
def fibonacci_tile(self, n):
w = self._fibonacci_tile(3*n+1)
w = w**4
from sage.combinat.words.paths import WordPaths
P = WordPaths([0,1,2,3])
l = list(w.partial_sums(start=3,mod=4))
return P(l)[:-1]
def dual_fibonacci_tile(self, n):
w = self._fibonacci_tile(3*n+1,3,3)
w = w**4
from sage.combinat.words.paths import WordPaths
P = WordPaths([0,1,2,3])
l = list(w.partial_sums(start=3,mod=4))
return P(l)[:-1]
def _s_adic_iterator(self, sequence, letters):
from itertools import tee
from builtins import zip
sequence_it,sequence = tee(sequence)
m = next(sequence_it)
codomain = m.codomain()
p = codomain.identity_morphism()
letters_it,letters = tee(letters)
precedent_letter = m(next(letters_it))[0]
yield precedent_letter
for (i,(m,a)) in enumerate(zip(sequence, letters)):
if not precedent_letter == m(a)[0]:
raise ValueError("The hypothesis of the algorithm used is not satisfied: the image of the %s-th letter (=%s) under the %s-th morphism (=%s) should start with the %s-th letter (=%s)."%(i+1,a,i+1,m,i,precedent_letter))
w = p(m(a)[1:])
for b in w:
yield b
p = p * m
precedent_letter = a
def s_adic(self, sequence, letters, morphisms=None):
if morphisms is None:
seq = sequence
elif hasattr(morphisms, '__getitem__'):
seq = (morphisms[i] for i in sequence)
elif hasattr(morphisms, '__call__'):
seq = (morphisms(i) for i in sequence)
else:
raise TypeError("morphisms (=%s) must be None, callable or provide a __getitem__ method."%morphisms)
from sage.combinat.words.word import FiniteWord_class
if isinstance(sequence,(tuple,list,str,FiniteWord_class)) \
and hasattr(letters, "__len__") and len(letters) == 1:
from sage.misc.all import prod
return prod(seq)(letters)
from itertools import tee
seq_it,seq= tee(seq)
m = next(seq_it)
W = m.codomain()
kwds = {}
kwds['data'] = self._s_adic_iterator(seq,letters)
kwds['datatype'] = 'iter'
kwds['caching'] = True
return W.shift()(**kwds)
def PalindromicDefectWord(self, k=1, alphabet='ab'):
kk = k-1
a, b = alphabet
if not (isinstance(a, str) and isinstance(b, str)):
a, b = (a,), (b,)
w = a + b*k + a + b*kk + a + a + b*kk + a + b*k + a
return FiniteWords(alphabet)(w)
def BaumSweetWord(self):
outer = WordMorphism('a->00,b->01,c->10,d->11')
inner = WordMorphism('a->aa,b->cb,c->ba,d->db')
return outer(inner.fixed_point('d'))
words = WordGenerator()
| true | true |
1c4705d90e26f7a3b0aec0c56259738df2567122 | 584 | py | Python | hail/python/hailtop/hailctl/dataproc/gcloud.py | sigmarkarl/hail | 11b7c22342a945c61b24c5f8babf4ab411d3d2f1 | [
"MIT"
] | 2 | 2020-12-15T21:20:24.000Z | 2020-12-21T19:46:26.000Z | hail/python/hailtop/hailctl/dataproc/gcloud.py | Dania-Abuhijleh/hail | a187dc0867801ca1eee774588fe58604a133a0d9 | [
"MIT"
] | 2 | 2016-11-17T03:06:10.000Z | 2017-12-05T19:00:24.000Z | hail/python/hailtop/hailctl/dataproc/gcloud.py | Dania-Abuhijleh/hail | a187dc0867801ca1eee774588fe58604a133a0d9 | [
"MIT"
] | 2 | 2020-07-28T18:55:19.000Z | 2020-10-19T16:43:03.000Z | import subprocess
import sys
import typing
def run(command: typing.List[str]):
"""Run a gcloud command."""
return subprocess.check_call(["gcloud"] + command)
def get_config(setting: str) -> typing.Optional[str]:
"""Get a gcloud configuration value."""
try:
return subprocess.check_output(["gcloud", "config", "get-value", setting], stderr=subprocess.DEVNULL).decode().strip()
except subprocess.CalledProcessError as e:
print(f"Warning: could not run 'gcloud config get-value {setting}': {e.output.decode}", file=sys.stderr)
return None
| 32.444444 | 126 | 0.690068 | import subprocess
import sys
import typing
def run(command: typing.List[str]):
return subprocess.check_call(["gcloud"] + command)
def get_config(setting: str) -> typing.Optional[str]:
try:
return subprocess.check_output(["gcloud", "config", "get-value", setting], stderr=subprocess.DEVNULL).decode().strip()
except subprocess.CalledProcessError as e:
print(f"Warning: could not run 'gcloud config get-value {setting}': {e.output.decode}", file=sys.stderr)
return None
| true | true |
1c47072151d6e3a3679673ef4f334e87c2edc417 | 10,991 | py | Python | sdk/python/pulumi_azure_nextgen/network/v20190701/virtual_hub.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_nextgen/network/v20190701/virtual_hub.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_nextgen/network/v20190701/virtual_hub.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"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
from ... import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['VirtualHub']
class VirtualHub(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
address_prefix: Optional[pulumi.Input[str]] = None,
express_route_gateway: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
p2_s_vpn_gateway: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
route_table: Optional[pulumi.Input[pulumi.InputType['VirtualHubRouteTableArgs']]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
virtual_hub_name: Optional[pulumi.Input[str]] = None,
virtual_network_connections: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['HubVirtualNetworkConnectionArgs']]]]] = None,
virtual_wan: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
vpn_gateway: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
VirtualHub Resource.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] address_prefix: Address-prefix for this VirtualHub.
:param pulumi.Input[pulumi.InputType['SubResourceArgs']] express_route_gateway: The expressRouteGateway associated with this VirtualHub.
:param pulumi.Input[str] id: Resource ID.
:param pulumi.Input[str] location: Resource location.
:param pulumi.Input[pulumi.InputType['SubResourceArgs']] p2_s_vpn_gateway: The P2SVpnGateway associated with this VirtualHub.
:param pulumi.Input[str] resource_group_name: The resource group name of the VirtualHub.
:param pulumi.Input[pulumi.InputType['VirtualHubRouteTableArgs']] route_table: The routeTable associated with this virtual hub.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags.
:param pulumi.Input[str] virtual_hub_name: The name of the VirtualHub.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['HubVirtualNetworkConnectionArgs']]]] virtual_network_connections: List of all vnet connections with this VirtualHub.
:param pulumi.Input[pulumi.InputType['SubResourceArgs']] virtual_wan: The VirtualWAN to which the VirtualHub belongs.
:param pulumi.Input[pulumi.InputType['SubResourceArgs']] vpn_gateway: The VpnGateway associated with this VirtualHub.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
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__ = dict()
__props__['address_prefix'] = address_prefix
__props__['express_route_gateway'] = express_route_gateway
__props__['id'] = id
if location is None:
raise TypeError("Missing required property 'location'")
__props__['location'] = location
__props__['p2_s_vpn_gateway'] = p2_s_vpn_gateway
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['route_table'] = route_table
__props__['tags'] = tags
if virtual_hub_name is None:
raise TypeError("Missing required property 'virtual_hub_name'")
__props__['virtual_hub_name'] = virtual_hub_name
__props__['virtual_network_connections'] = virtual_network_connections
__props__['virtual_wan'] = virtual_wan
__props__['vpn_gateway'] = vpn_gateway
__props__['etag'] = None
__props__['name'] = None
__props__['provisioning_state'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/latest:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20180401:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20180601:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20180701:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20180801:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20181001:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20181101:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20181201:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190201:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190401:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190601:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190801:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190901:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20191101:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20191201:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200301:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200401:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200501:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200601:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200701:VirtualHub")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(VirtualHub, __self__).__init__(
'azure-nextgen:network/v20190701:VirtualHub',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'VirtualHub':
"""
Get an existing VirtualHub 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__ = dict()
return VirtualHub(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="addressPrefix")
def address_prefix(self) -> pulumi.Output[Optional[str]]:
"""
Address-prefix for this VirtualHub.
"""
return pulumi.get(self, "address_prefix")
@property
@pulumi.getter
def etag(self) -> pulumi.Output[str]:
"""
A unique read-only string that changes whenever the resource is updated.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter(name="expressRouteGateway")
def express_route_gateway(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
"""
The expressRouteGateway associated with this VirtualHub.
"""
return pulumi.get(self, "express_route_gateway")
@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]:
"""
Resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="p2SVpnGateway")
def p2_s_vpn_gateway(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
"""
The P2SVpnGateway associated with this VirtualHub.
"""
return pulumi.get(self, "p2_s_vpn_gateway")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
"""
The provisioning state of the virtual hub resource.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="routeTable")
def route_table(self) -> pulumi.Output[Optional['outputs.VirtualHubRouteTableResponse']]:
"""
The routeTable associated with this virtual hub.
"""
return pulumi.get(self, "route_table")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Resource tags.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Resource type.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="virtualNetworkConnections")
def virtual_network_connections(self) -> pulumi.Output[Optional[Sequence['outputs.HubVirtualNetworkConnectionResponse']]]:
"""
List of all vnet connections with this VirtualHub.
"""
return pulumi.get(self, "virtual_network_connections")
@property
@pulumi.getter(name="virtualWan")
def virtual_wan(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
"""
The VirtualWAN to which the VirtualHub belongs.
"""
return pulumi.get(self, "virtual_wan")
@property
@pulumi.getter(name="vpnGateway")
def vpn_gateway(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
"""
The VpnGateway associated with this VirtualHub.
"""
return pulumi.get(self, "vpn_gateway")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| 48.20614 | 1,370 | 0.670731 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['VirtualHub']
class VirtualHub(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
address_prefix: Optional[pulumi.Input[str]] = None,
express_route_gateway: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
p2_s_vpn_gateway: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
route_table: Optional[pulumi.Input[pulumi.InputType['VirtualHubRouteTableArgs']]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
virtual_hub_name: Optional[pulumi.Input[str]] = None,
virtual_network_connections: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['HubVirtualNetworkConnectionArgs']]]]] = None,
virtual_wan: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
vpn_gateway: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
__props__=None,
__name__=None,
__opts__=None):
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
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__ = dict()
__props__['address_prefix'] = address_prefix
__props__['express_route_gateway'] = express_route_gateway
__props__['id'] = id
if location is None:
raise TypeError("Missing required property 'location'")
__props__['location'] = location
__props__['p2_s_vpn_gateway'] = p2_s_vpn_gateway
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['route_table'] = route_table
__props__['tags'] = tags
if virtual_hub_name is None:
raise TypeError("Missing required property 'virtual_hub_name'")
__props__['virtual_hub_name'] = virtual_hub_name
__props__['virtual_network_connections'] = virtual_network_connections
__props__['virtual_wan'] = virtual_wan
__props__['vpn_gateway'] = vpn_gateway
__props__['etag'] = None
__props__['name'] = None
__props__['provisioning_state'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/latest:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20180401:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20180601:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20180701:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20180801:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20181001:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20181101:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20181201:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190201:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190401:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190601:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190801:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20190901:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20191101:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20191201:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200301:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200401:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200501:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200601:VirtualHub"), pulumi.Alias(type_="azure-nextgen:network/v20200701:VirtualHub")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(VirtualHub, __self__).__init__(
'azure-nextgen:network/v20190701:VirtualHub',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'VirtualHub':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
return VirtualHub(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="addressPrefix")
def address_prefix(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "address_prefix")
@property
@pulumi.getter
def etag(self) -> pulumi.Output[str]:
return pulumi.get(self, "etag")
@property
@pulumi.getter(name="expressRouteGateway")
def express_route_gateway(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
return pulumi.get(self, "express_route_gateway")
@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="p2SVpnGateway")
def p2_s_vpn_gateway(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
return pulumi.get(self, "p2_s_vpn_gateway")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="routeTable")
def route_table(self) -> pulumi.Output[Optional['outputs.VirtualHubRouteTableResponse']]:
return pulumi.get(self, "route_table")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
return pulumi.get(self, "type")
@property
@pulumi.getter(name="virtualNetworkConnections")
def virtual_network_connections(self) -> pulumi.Output[Optional[Sequence['outputs.HubVirtualNetworkConnectionResponse']]]:
return pulumi.get(self, "virtual_network_connections")
@property
@pulumi.getter(name="virtualWan")
def virtual_wan(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
return pulumi.get(self, "virtual_wan")
@property
@pulumi.getter(name="vpnGateway")
def vpn_gateway(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
return pulumi.get(self, "vpn_gateway")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| true | true |
1c47074abf2983d50cd994c75924c03df0a98653 | 2,586 | py | Python | tally_ho/apps/tally/tests/views/reports/test_overall_votes.py | onaio/tally-ho | f7a81909755924370653051bfc8315588dc75356 | [
"Apache-2.0"
] | 12 | 2015-09-07T17:12:42.000Z | 2021-12-29T07:51:18.000Z | tally_ho/apps/tally/tests/views/reports/test_overall_votes.py | onaio/tally-ho | f7a81909755924370653051bfc8315588dc75356 | [
"Apache-2.0"
] | 122 | 2018-09-18T04:05:39.000Z | 2022-01-17T10:12:48.000Z | tally_ho/apps/tally/tests/views/reports/test_overall_votes.py | onaio/tally-ho | f7a81909755924370653051bfc8315588dc75356 | [
"Apache-2.0"
] | 13 | 2015-06-06T17:32:34.000Z | 2020-09-10T12:58:07.000Z | from django.test import RequestFactory
from tally_ho.libs.permissions import groups
from tally_ho.apps.tally.views.reports import overall_votes
from tally_ho.libs.models.enums.entry_version import EntryVersion
from tally_ho.libs.tests.test_base import create_result_form, create_ballot,\
create_candidates, create_result, create_tally, create_center,\
create_station, TestBase
class TestOverallVotes(TestBase):
def setUp(self):
self.factory = RequestFactory()
self._create_permission_groups()
self._create_and_login_user()
self._add_user_to_group(self.user, groups.TALLY_MANAGER)
self.tally = create_tally()
self.tally.users.add(self.user)
ballot = create_ballot(tally=self.tally)
center = create_center('12345', tally=self.tally)
station = create_station(center)
result_form = create_result_form(
tally=self.tally,
ballot=ballot,
center=center,
station_number=station.station_number)
votes = 12
create_candidates(result_form, votes=votes, user=self.user,
num_results=1)
for result in result_form.results.all():
result.entry_version = EntryVersion.FINAL
result.save()
# create duplicate final results
create_result(result_form, result.candidate, self.user, votes)
def test_station_overall_votes_get(self):
"""Test that Station overall votes page is rendered"""
request = self._get_request()
view = overall_votes.OverallVotes.as_view()
request = self.factory.get(
f'/reports/internal/station-overall-votes/{self.tally.pk}')
request.user = self.user
response = view(
request,
tally_id=self.tally.pk,
group_name=groups.SUPER_ADMINISTRATOR)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Station Overall Progress")
def test_center_overall_votes_get(self):
"""Test that Center overall votes page is rendered"""
request = self._get_request()
view = overall_votes.OverallVotes.as_view()
request = self.factory.get(
f'/reports/internal/center-overall-votes/{self.tally.pk}')
request.user = self.user
response = view(
request,
tally_id=self.tally.pk,
group_name=groups.SUPER_ADMINISTRATOR)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Center Overall Progress")
| 40.40625 | 77 | 0.667827 | from django.test import RequestFactory
from tally_ho.libs.permissions import groups
from tally_ho.apps.tally.views.reports import overall_votes
from tally_ho.libs.models.enums.entry_version import EntryVersion
from tally_ho.libs.tests.test_base import create_result_form, create_ballot,\
create_candidates, create_result, create_tally, create_center,\
create_station, TestBase
class TestOverallVotes(TestBase):
def setUp(self):
self.factory = RequestFactory()
self._create_permission_groups()
self._create_and_login_user()
self._add_user_to_group(self.user, groups.TALLY_MANAGER)
self.tally = create_tally()
self.tally.users.add(self.user)
ballot = create_ballot(tally=self.tally)
center = create_center('12345', tally=self.tally)
station = create_station(center)
result_form = create_result_form(
tally=self.tally,
ballot=ballot,
center=center,
station_number=station.station_number)
votes = 12
create_candidates(result_form, votes=votes, user=self.user,
num_results=1)
for result in result_form.results.all():
result.entry_version = EntryVersion.FINAL
result.save()
create_result(result_form, result.candidate, self.user, votes)
def test_station_overall_votes_get(self):
request = self._get_request()
view = overall_votes.OverallVotes.as_view()
request = self.factory.get(
f'/reports/internal/station-overall-votes/{self.tally.pk}')
request.user = self.user
response = view(
request,
tally_id=self.tally.pk,
group_name=groups.SUPER_ADMINISTRATOR)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Station Overall Progress")
def test_center_overall_votes_get(self):
request = self._get_request()
view = overall_votes.OverallVotes.as_view()
request = self.factory.get(
f'/reports/internal/center-overall-votes/{self.tally.pk}')
request.user = self.user
response = view(
request,
tally_id=self.tally.pk,
group_name=groups.SUPER_ADMINISTRATOR)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Center Overall Progress")
| true | true |
1c4707f0fd319f5925e77eba1ff52dbd5d26aa43 | 23,378 | py | Python | PixivImageHandler.py | YukihoAA/PixivUtil2 | bd2dd3ca34b1277042ee5f3d74a80800985aa4cc | [
"BSD-2-Clause"
] | 1,872 | 2015-01-02T06:59:58.000Z | 2022-03-29T14:43:58.000Z | PixivImageHandler.py | YukihoAA/PixivUtil2 | bd2dd3ca34b1277042ee5f3d74a80800985aa4cc | [
"BSD-2-Clause"
] | 959 | 2015-01-02T05:42:57.000Z | 2022-03-28T10:00:56.000Z | PixivImageHandler.py | nao20010128nao/PU2-patched | 3a4dd523247727a510c0b75373ae79db754a34f7 | [
"BSD-2-Clause"
] | 310 | 2015-01-02T16:45:33.000Z | 2022-03-25T19:42:39.000Z | # -*- coding: utf-8 -*-
import datetime
import gc
import os
import re
import sys
import traceback
import urllib
from colorama import Fore, Style
import datetime_z
import PixivBrowserFactory
import PixivConstant
import PixivDownloadHandler
import PixivHelper
from PixivException import PixivException
__re_manga_page = re.compile(r'(\d+(_big)?_p\d+)')
def process_image(caller,
config,
artist=None,
image_id=None,
user_dir='',
bookmark=False,
search_tags='',
title_prefix="",
bookmark_count=-1,
image_response_count=-1,
notifier=None,
useblacklist=True,
manga_series_order=-1,
manga_series_parent=None) -> int:
# caller function/method
# TODO: ideally to be removed or passed as argument
db = caller.__dbManager__
if notifier is None:
notifier = PixivHelper.dummy_notifier
# override the config source if job_option is give for filename formats
extension_filter = None
if hasattr(config, "extensionFilter"):
extension_filter = config.extensionFilter
parse_medium_page = None
image = None
result = None
referer = f'https://www.pixiv.net/artworks/{image_id}'
filename = f'no-filename-{image_id}.tmp'
try:
msg = Fore.YELLOW + Style.NORMAL + f'Processing Image Id: {image_id}' + Style.RESET_ALL
PixivHelper.print_and_log(None, msg)
notifier(type="IMAGE", message=msg)
# check if already downloaded. images won't be downloaded twice - needed in process_image to catch any download
r = db.selectImageByImageId(image_id, cols='save_name')
exists = False
in_db = False
if r is not None:
exists = db.cleanupFileExists(r[0])
in_db = True
# skip if already recorded in db and alwaysCheckFileSize is disabled and overwrite is disabled.
if in_db and not config.alwaysCheckFileSize and not config.overwrite:
PixivHelper.print_and_log(None, f'Already downloaded in DB: {image_id}')
gc.collect()
return PixivConstant.PIXIVUTIL_SKIP_DUPLICATE_NO_WAIT
# get the medium page
try:
(image, parse_medium_page) = PixivBrowserFactory.getBrowser().getImagePage(image_id=image_id,
parent=artist,
from_bookmark=bookmark,
bookmark_count=bookmark_count,
manga_series_order=manga_series_order,
manga_series_parent=manga_series_parent)
if len(title_prefix) > 0:
caller.set_console_title(f"{title_prefix} ImageId: {image.imageId}")
else:
caller.set_console_title(f"MemberId: {image.artist.artistId} ImageId: {image.imageId}")
except PixivException as ex:
caller.ERROR_CODE = ex.errorCode
caller.__errorList.append(dict(type="Image", id=str(image_id), message=ex.message, exception=ex))
if ex.errorCode == PixivException.UNKNOWN_IMAGE_ERROR:
PixivHelper.print_and_log('error', ex.message)
elif ex.errorCode == PixivException.SERVER_ERROR:
PixivHelper.print_and_log('error', f'Giving up image_id (medium): {image_id}')
elif ex.errorCode > 2000:
PixivHelper.print_and_log('error', f'Image Error for {image_id}: {ex.message}')
if parse_medium_page is not None:
dump_filename = f'Error medium page for image {image_id}.html'
PixivHelper.dump_html(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', f'Dumping html to: {dump_filename}')
else:
PixivHelper.print_and_log('error', f'Image ID ({image_id}): {ex}')
PixivHelper.print_and_log('error', f'Stack Trace: {sys.exc_info()}')
return PixivConstant.PIXIVUTIL_NOT_OK
except Exception as ex:
PixivHelper.print_and_log('error', f'Image ID ({image_id}): {ex}')
if parse_medium_page is not None:
dump_filename = f'Error medium page for image {image_id}.html'
PixivHelper.dump_html(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', f'Dumping html to: {dump_filename}')
PixivHelper.print_and_log('error', f'Stack Trace: {sys.exc_info()}')
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
return PixivConstant.PIXIVUTIL_NOT_OK
download_image_flag = True
# date validation and blacklist tag validation
if config.dateDiff > 0:
if image.worksDateDateTime != datetime.datetime.fromordinal(1).replace(tzinfo=datetime_z.utc):
if image.worksDateDateTime < (datetime.datetime.today() - datetime.timedelta(config.dateDiff)).replace(tzinfo=datetime_z.utc):
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – it\'s older than: {config.dateDiff} day(s).')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_OLDER
if useblacklist:
if config.useBlacklistMembers and download_image_flag:
if str(image.originalArtist.artistId) in caller.__blacklistMembers:
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – blacklisted member id: {image.originalArtist.artistId}')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
if config.useBlacklistTags and download_image_flag:
for item in caller.__blacklistTags:
if item in image.imageTags:
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – blacklisted tag: {item}')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
break
if config.useBlacklistTitles and download_image_flag:
if config.useBlacklistTitlesRegex:
for item in caller.__blacklistTitles:
if re.search(rf"{item}", image.imageTitle):
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – Title matched: {item}')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
break
else:
for item in caller.__blacklistTitles:
if item in image.imageTitle:
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – Title contained: {item}')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
break
# Issue #726
if extension_filter is not None and len(extension_filter) > 0:
for url in image.imageUrls:
ext = PixivHelper.get_extension_from_url(url)
# add alias for ugoira
if "ugoira" in extension_filter:
extension_filter = f"{extension_filter}|zip"
if re.search(extension_filter, ext) is None:
download_image_flag = False
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} - url is not in the filter: {extension_filter} => {url}')
break
# issue #1027 filter by bookmark count
if bookmark_count is not None and int(bookmark_count) > -1 and int(image.bookmark_count) < int(bookmark_count):
download_image_flag = False
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} - post bookmark count {image.bookmark_count} is less than: {bookmark_count}')
if download_image_flag:
if artist is None:
PixivHelper.print_and_log(None, f'Member Name : {image.artist.artistName}')
PixivHelper.print_and_log(None, f'Member Avatar: {image.artist.artistAvatar}')
PixivHelper.print_and_log(None, f'Member Token : {image.artist.artistToken}')
PixivHelper.print_and_log(None, f'Member Background : {image.artist.artistBackground}')
PixivHelper.print_and_log(None, f"Title: {image.imageTitle}")
tags_str = ', '.join(image.imageTags)
PixivHelper.print_and_log(None, f"Tags : {tags_str}")
PixivHelper.print_and_log(None, f"Date : {image.worksDateDateTime}")
PixivHelper.print_and_log(None, f"Mode : {image.imageMode}")
PixivHelper.print_and_log(None, f"Bookmark Count : {image.bookmark_count}")
if config.useSuppressTags:
for item in caller.__suppressTags:
if item in image.imageTags:
image.imageTags.remove(item)
# get manga page
if image.imageMode == 'manga':
PixivHelper.print_and_log(None, f"Page Count : {image.imageCount}")
if user_dir == '': # Yavos: use config-options
target_dir = config.rootDirectory
else: # Yavos: use filename from list
target_dir = user_dir
result = PixivConstant.PIXIVUTIL_OK
manga_files = list()
page = 0
# Issue #639
source_urls = image.imageUrls
if config.downloadResized:
source_urls = image.imageResizedUrls
# debugging purpose, to avoid actual download
if caller.DEBUG_SKIP_DOWNLOAD_IMAGE:
return PixivConstant.PIXIVUTIL_OK
for img in source_urls:
PixivHelper.print_and_log(None, f'Image URL : {img}')
url = os.path.basename(img)
split_url = url.split('.')
if split_url[0].startswith(str(image_id)):
filename_format = config.filenameFormat
if image.imageMode == 'manga':
filename_format = config.filenameMangaFormat
filename = PixivHelper.make_filename(filename_format,
image,
tagsSeparator=config.tagsSeparator,
tagsLimit=config.tagsLimit,
fileUrl=url,
bookmark=bookmark,
searchTags=search_tags,
useTranslatedTag=config.useTranslatedTag,
tagTranslationLocale=config.tagTranslationLocale)
filename = PixivHelper.sanitize_filename(filename, target_dir)
if image.imageMode == 'manga' and config.createMangaDir:
manga_page = __re_manga_page.findall(filename)
if len(manga_page) > 0:
splitted_filename = filename.split(manga_page[0][0], 1)
splitted_manga_page = manga_page[0][0].split("_p", 1)
# filename = splitted_filename[0] + splitted_manga_page[0] + os.sep + "_p" + splitted_manga_page[1] + splitted_filename[1]
filename = f"{splitted_filename[0]}{splitted_manga_page[0]}{os.sep}_p{splitted_manga_page[1]}{splitted_filename[1]}"
PixivHelper.print_and_log('info', f'Filename : {filename}')
result = PixivConstant.PIXIVUTIL_NOT_OK
try:
(result, filename) = PixivDownloadHandler.download_image(caller,
img,
filename,
referer,
config.overwrite,
config.retry,
config.backupOldFile,
image,
page,
notifier)
if result == PixivConstant.PIXIVUTIL_NOT_OK:
PixivHelper.print_and_log('error', f'Image url not found/failed to download: {image.imageId}')
elif result == PixivConstant.PIXIVUTIL_ABORTED:
raise KeyboardInterrupt()
manga_files.append((image_id, page, filename))
page = page + 1
except urllib.error.URLError:
PixivHelper.print_and_log('error', f'Error when download_image(), giving up url: {img}')
PixivHelper.print_and_log(None, '')
if config.writeImageXMPPerImage:
filename_info_format = config.filenameInfoFormat or config.filenameFormat
# Issue #575
if image.imageMode == 'manga':
filename_info_format = config.filenameMangaInfoFormat or config.filenameMangaFormat or filename_info_format
info_filename = PixivHelper.make_filename(filename_info_format,
image,
tagsSeparator=config.tagsSeparator,
tagsLimit=config.tagsLimit,
fileUrl=url,
appendExtension=False,
bookmark=bookmark,
searchTags=search_tags,
useTranslatedTag=config.useTranslatedTag,
tagTranslationLocale=config.tagTranslationLocale)
info_filename = PixivHelper.sanitize_filename(info_filename, target_dir)
image.WriteXMP(info_filename + ".xmp")
if config.writeImageInfo or config.writeImageJSON or config.writeImageXMP:
filename_info_format = config.filenameInfoFormat or config.filenameFormat
# Issue #575
if image.imageMode == 'manga':
filename_info_format = config.filenameMangaInfoFormat or config.filenameMangaFormat or filename_info_format
info_filename = PixivHelper.make_filename(filename_info_format,
image,
tagsSeparator=config.tagsSeparator,
tagsLimit=config.tagsLimit,
fileUrl=url,
appendExtension=False,
bookmark=bookmark,
searchTags=search_tags,
useTranslatedTag=config.useTranslatedTag,
tagTranslationLocale=config.tagTranslationLocale)
info_filename = PixivHelper.sanitize_filename(info_filename, target_dir)
# trim _pXXX
info_filename = re.sub(r'_p?\d+$', '', info_filename)
if config.writeImageInfo:
image.WriteInfo(info_filename + ".txt")
if config.writeImageJSON:
image.WriteJSON(info_filename + ".json", config.RawJSONFilter)
if config.includeSeriesJSON and image.seriesNavData and image.seriesNavData['seriesId'] not in caller.__seriesDownloaded:
json_filename = PixivHelper.make_filename(config.filenameSeriesJSON,
image,
fileUrl=url,
appendExtension=False
)
json_filename = PixivHelper.sanitize_filename(json_filename, target_dir)
# trim _pXXX
json_filename = re.sub(r'_p?\d+$', '', json_filename)
image.WriteSeriesData(image.seriesNavData['seriesId'], caller.__seriesDownloaded, json_filename + ".json")
if config.writeImageXMP and not config.writeImageXMPPerImage:
image.WriteXMP(info_filename + ".xmp")
if image.imageMode == 'ugoira_view':
if config.writeUgoiraInfo:
image.WriteUgoiraData(filename + ".js")
# Handle #451
if config.createUgoira and (result in (PixivConstant.PIXIVUTIL_OK, PixivConstant.PIXIVUTIL_SKIP_DUPLICATE)):
PixivDownloadHandler.handle_ugoira(image, filename, config, notifier)
if config.writeUrlInDescription:
PixivHelper.write_url_in_description(image, config.urlBlacklistRegex, config.urlDumpFilename)
if in_db and not exists:
result = PixivConstant.PIXIVUTIL_CHECK_DOWNLOAD # There was something in the database which had not been downloaded
# Only save to db if all images is downloaded completely
if result in (PixivConstant.PIXIVUTIL_OK,
PixivConstant.PIXIVUTIL_SKIP_DUPLICATE,
PixivConstant.PIXIVUTIL_SKIP_LOCAL_LARGER):
try:
db.insertImage(image.artist.artistId, image.imageId, image.imageMode)
except BaseException:
PixivHelper.print_and_log('error', f'Failed to insert image id:{image.imageId} to DB')
db.updateImage(image.imageId, image.imageTitle, filename, image.imageMode)
if len(manga_files) > 0:
db.insertMangaImages(manga_files)
# map back to PIXIVUTIL_OK (because of ugoira file check)
result = 0
if image is not None:
del image
if parse_medium_page is not None:
del parse_medium_page
gc.collect()
PixivHelper.print_and_log(None, '\n')
return result
except Exception as ex:
if isinstance(ex, KeyboardInterrupt):
raise
caller.ERROR_CODE = getattr(ex, 'errorCode', -1)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.print_and_log('error', f'Error at process_image(): {image_id}')
PixivHelper.print_and_log('error', f'Exception: {sys.exc_info()}')
if parse_medium_page is not None:
dump_filename = f'Error medium page for image {image_id}.html'
PixivHelper.dump_html(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', f'Dumping html to: {dump_filename}')
raise
def process_manga_series(caller,
config,
manga_series_id: int,
start_page: int = 1,
end_page: int = 0,
notifier=None):
if notifier is None:
notifier = PixivHelper.dummy_notifier
try:
msg = Fore.YELLOW + Style.NORMAL + f'Processing Manga Series Id: {manga_series_id}' + Style.RESET_ALL
PixivHelper.print_and_log(None, msg)
notifier(type="MANGA_SERIES", message=msg)
if start_page != 1:
PixivHelper.print_and_log('info', 'Start Page: ' + str(start_page))
if end_page != 0:
PixivHelper.print_and_log('info', 'End Page: ' + str(end_page))
flag = True
current_page = start_page
while flag:
manga_series = PixivBrowserFactory.getBrowser().getMangaSeries(manga_series_id, current_page)
for (image_id, order) in manga_series.pages_with_order:
result = process_image(caller,
config,
artist=manga_series.artist,
image_id=image_id,
user_dir='',
bookmark=False,
search_tags='',
title_prefix="",
bookmark_count=-1,
image_response_count=-1,
notifier=notifier,
useblacklist=True,
manga_series_order=order,
manga_series_parent=manga_series)
PixivHelper.wait(result, config)
current_page += 1
if manga_series.is_last_page:
PixivHelper.print_and_log('info', f'Last Page {manga_series.current_page}')
flag = False
if current_page > end_page and end_page != 0:
PixivHelper.print_and_log('info', f'End Page reached {end_page}')
flag = False
if manga_series.pages_with_order is None or len(manga_series.pages_with_order) == 0:
PixivHelper.print_and_log('info', 'No more works.')
flag = False
except Exception as ex:
if isinstance(ex, KeyboardInterrupt):
raise
caller.ERROR_CODE = getattr(ex, 'errorCode', -1)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.print_and_log('error', f'Error at process_manga_series(): {manga_series_id}')
PixivHelper.print_and_log('error', f'Exception: {sys.exc_info()}')
raise
| 53.496568 | 155 | 0.529387 |
import datetime
import gc
import os
import re
import sys
import traceback
import urllib
from colorama import Fore, Style
import datetime_z
import PixivBrowserFactory
import PixivConstant
import PixivDownloadHandler
import PixivHelper
from PixivException import PixivException
__re_manga_page = re.compile(r'(\d+(_big)?_p\d+)')
def process_image(caller,
config,
artist=None,
image_id=None,
user_dir='',
bookmark=False,
search_tags='',
title_prefix="",
bookmark_count=-1,
image_response_count=-1,
notifier=None,
useblacklist=True,
manga_series_order=-1,
manga_series_parent=None) -> int:
db = caller.__dbManager__
if notifier is None:
notifier = PixivHelper.dummy_notifier
extension_filter = None
if hasattr(config, "extensionFilter"):
extension_filter = config.extensionFilter
parse_medium_page = None
image = None
result = None
referer = f'https://www.pixiv.net/artworks/{image_id}'
filename = f'no-filename-{image_id}.tmp'
try:
msg = Fore.YELLOW + Style.NORMAL + f'Processing Image Id: {image_id}' + Style.RESET_ALL
PixivHelper.print_and_log(None, msg)
notifier(type="IMAGE", message=msg)
r = db.selectImageByImageId(image_id, cols='save_name')
exists = False
in_db = False
if r is not None:
exists = db.cleanupFileExists(r[0])
in_db = True
# skip if already recorded in db and alwaysCheckFileSize is disabled and overwrite is disabled.
if in_db and not config.alwaysCheckFileSize and not config.overwrite:
PixivHelper.print_and_log(None, f'Already downloaded in DB: {image_id}')
gc.collect()
return PixivConstant.PIXIVUTIL_SKIP_DUPLICATE_NO_WAIT
# get the medium page
try:
(image, parse_medium_page) = PixivBrowserFactory.getBrowser().getImagePage(image_id=image_id,
parent=artist,
from_bookmark=bookmark,
bookmark_count=bookmark_count,
manga_series_order=manga_series_order,
manga_series_parent=manga_series_parent)
if len(title_prefix) > 0:
caller.set_console_title(f"{title_prefix} ImageId: {image.imageId}")
else:
caller.set_console_title(f"MemberId: {image.artist.artistId} ImageId: {image.imageId}")
except PixivException as ex:
caller.ERROR_CODE = ex.errorCode
caller.__errorList.append(dict(type="Image", id=str(image_id), message=ex.message, exception=ex))
if ex.errorCode == PixivException.UNKNOWN_IMAGE_ERROR:
PixivHelper.print_and_log('error', ex.message)
elif ex.errorCode == PixivException.SERVER_ERROR:
PixivHelper.print_and_log('error', f'Giving up image_id (medium): {image_id}')
elif ex.errorCode > 2000:
PixivHelper.print_and_log('error', f'Image Error for {image_id}: {ex.message}')
if parse_medium_page is not None:
dump_filename = f'Error medium page for image {image_id}.html'
PixivHelper.dump_html(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', f'Dumping html to: {dump_filename}')
else:
PixivHelper.print_and_log('error', f'Image ID ({image_id}): {ex}')
PixivHelper.print_and_log('error', f'Stack Trace: {sys.exc_info()}')
return PixivConstant.PIXIVUTIL_NOT_OK
except Exception as ex:
PixivHelper.print_and_log('error', f'Image ID ({image_id}): {ex}')
if parse_medium_page is not None:
dump_filename = f'Error medium page for image {image_id}.html'
PixivHelper.dump_html(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', f'Dumping html to: {dump_filename}')
PixivHelper.print_and_log('error', f'Stack Trace: {sys.exc_info()}')
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
return PixivConstant.PIXIVUTIL_NOT_OK
download_image_flag = True
# date validation and blacklist tag validation
if config.dateDiff > 0:
if image.worksDateDateTime != datetime.datetime.fromordinal(1).replace(tzinfo=datetime_z.utc):
if image.worksDateDateTime < (datetime.datetime.today() - datetime.timedelta(config.dateDiff)).replace(tzinfo=datetime_z.utc):
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – it\'s older than: {config.dateDiff} day(s).')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_OLDER
if useblacklist:
if config.useBlacklistMembers and download_image_flag:
if str(image.originalArtist.artistId) in caller.__blacklistMembers:
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – blacklisted member id: {image.originalArtist.artistId}')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
if config.useBlacklistTags and download_image_flag:
for item in caller.__blacklistTags:
if item in image.imageTags:
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – blacklisted tag: {item}')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
break
if config.useBlacklistTitles and download_image_flag:
if config.useBlacklistTitlesRegex:
for item in caller.__blacklistTitles:
if re.search(rf"{item}", image.imageTitle):
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – Title matched: {item}')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
break
else:
for item in caller.__blacklistTitles:
if item in image.imageTitle:
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} – Title contained: {item}')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
break
if extension_filter is not None and len(extension_filter) > 0:
for url in image.imageUrls:
ext = PixivHelper.get_extension_from_url(url)
if "ugoira" in extension_filter:
extension_filter = f"{extension_filter}|zip"
if re.search(extension_filter, ext) is None:
download_image_flag = False
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} - url is not in the filter: {extension_filter} => {url}')
break
not None and int(bookmark_count) > -1 and int(image.bookmark_count) < int(bookmark_count):
download_image_flag = False
PixivHelper.print_and_log('warn', f'Skipping image_id: {image_id} - post bookmark count {image.bookmark_count} is less than: {bookmark_count}')
if download_image_flag:
if artist is None:
PixivHelper.print_and_log(None, f'Member Name : {image.artist.artistName}')
PixivHelper.print_and_log(None, f'Member Avatar: {image.artist.artistAvatar}')
PixivHelper.print_and_log(None, f'Member Token : {image.artist.artistToken}')
PixivHelper.print_and_log(None, f'Member Background : {image.artist.artistBackground}')
PixivHelper.print_and_log(None, f"Title: {image.imageTitle}")
tags_str = ', '.join(image.imageTags)
PixivHelper.print_and_log(None, f"Tags : {tags_str}")
PixivHelper.print_and_log(None, f"Date : {image.worksDateDateTime}")
PixivHelper.print_and_log(None, f"Mode : {image.imageMode}")
PixivHelper.print_and_log(None, f"Bookmark Count : {image.bookmark_count}")
if config.useSuppressTags:
for item in caller.__suppressTags:
if item in image.imageTags:
image.imageTags.remove(item)
if image.imageMode == 'manga':
PixivHelper.print_and_log(None, f"Page Count : {image.imageCount}")
if user_dir == '':
target_dir = config.rootDirectory
else:
target_dir = user_dir
result = PixivConstant.PIXIVUTIL_OK
manga_files = list()
page = 0
source_urls = image.imageUrls
if config.downloadResized:
source_urls = image.imageResizedUrls
if caller.DEBUG_SKIP_DOWNLOAD_IMAGE:
return PixivConstant.PIXIVUTIL_OK
for img in source_urls:
PixivHelper.print_and_log(None, f'Image URL : {img}')
url = os.path.basename(img)
split_url = url.split('.')
if split_url[0].startswith(str(image_id)):
filename_format = config.filenameFormat
if image.imageMode == 'manga':
filename_format = config.filenameMangaFormat
filename = PixivHelper.make_filename(filename_format,
image,
tagsSeparator=config.tagsSeparator,
tagsLimit=config.tagsLimit,
fileUrl=url,
bookmark=bookmark,
searchTags=search_tags,
useTranslatedTag=config.useTranslatedTag,
tagTranslationLocale=config.tagTranslationLocale)
filename = PixivHelper.sanitize_filename(filename, target_dir)
if image.imageMode == 'manga' and config.createMangaDir:
manga_page = __re_manga_page.findall(filename)
if len(manga_page) > 0:
splitted_filename = filename.split(manga_page[0][0], 1)
splitted_manga_page = manga_page[0][0].split("_p", 1)
filename = f"{splitted_filename[0]}{splitted_manga_page[0]}{os.sep}_p{splitted_manga_page[1]}{splitted_filename[1]}"
PixivHelper.print_and_log('info', f'Filename : {filename}')
result = PixivConstant.PIXIVUTIL_NOT_OK
try:
(result, filename) = PixivDownloadHandler.download_image(caller,
img,
filename,
referer,
config.overwrite,
config.retry,
config.backupOldFile,
image,
page,
notifier)
if result == PixivConstant.PIXIVUTIL_NOT_OK:
PixivHelper.print_and_log('error', f'Image url not found/failed to download: {image.imageId}')
elif result == PixivConstant.PIXIVUTIL_ABORTED:
raise KeyboardInterrupt()
manga_files.append((image_id, page, filename))
page = page + 1
except urllib.error.URLError:
PixivHelper.print_and_log('error', f'Error when download_image(), giving up url: {img}')
PixivHelper.print_and_log(None, '')
if config.writeImageXMPPerImage:
filename_info_format = config.filenameInfoFormat or config.filenameFormat
if image.imageMode == 'manga':
filename_info_format = config.filenameMangaInfoFormat or config.filenameMangaFormat or filename_info_format
info_filename = PixivHelper.make_filename(filename_info_format,
image,
tagsSeparator=config.tagsSeparator,
tagsLimit=config.tagsLimit,
fileUrl=url,
appendExtension=False,
bookmark=bookmark,
searchTags=search_tags,
useTranslatedTag=config.useTranslatedTag,
tagTranslationLocale=config.tagTranslationLocale)
info_filename = PixivHelper.sanitize_filename(info_filename, target_dir)
image.WriteXMP(info_filename + ".xmp")
if config.writeImageInfo or config.writeImageJSON or config.writeImageXMP:
filename_info_format = config.filenameInfoFormat or config.filenameFormat
if image.imageMode == 'manga':
filename_info_format = config.filenameMangaInfoFormat or config.filenameMangaFormat or filename_info_format
info_filename = PixivHelper.make_filename(filename_info_format,
image,
tagsSeparator=config.tagsSeparator,
tagsLimit=config.tagsLimit,
fileUrl=url,
appendExtension=False,
bookmark=bookmark,
searchTags=search_tags,
useTranslatedTag=config.useTranslatedTag,
tagTranslationLocale=config.tagTranslationLocale)
info_filename = PixivHelper.sanitize_filename(info_filename, target_dir)
info_filename = re.sub(r'_p?\d+$', '', info_filename)
if config.writeImageInfo:
image.WriteInfo(info_filename + ".txt")
if config.writeImageJSON:
image.WriteJSON(info_filename + ".json", config.RawJSONFilter)
if config.includeSeriesJSON and image.seriesNavData and image.seriesNavData['seriesId'] not in caller.__seriesDownloaded:
json_filename = PixivHelper.make_filename(config.filenameSeriesJSON,
image,
fileUrl=url,
appendExtension=False
)
json_filename = PixivHelper.sanitize_filename(json_filename, target_dir)
json_filename = re.sub(r'_p?\d+$', '', json_filename)
image.WriteSeriesData(image.seriesNavData['seriesId'], caller.__seriesDownloaded, json_filename + ".json")
if config.writeImageXMP and not config.writeImageXMPPerImage:
image.WriteXMP(info_filename + ".xmp")
if image.imageMode == 'ugoira_view':
if config.writeUgoiraInfo:
image.WriteUgoiraData(filename + ".js")
if config.createUgoira and (result in (PixivConstant.PIXIVUTIL_OK, PixivConstant.PIXIVUTIL_SKIP_DUPLICATE)):
PixivDownloadHandler.handle_ugoira(image, filename, config, notifier)
if config.writeUrlInDescription:
PixivHelper.write_url_in_description(image, config.urlBlacklistRegex, config.urlDumpFilename)
if in_db and not exists:
result = PixivConstant.PIXIVUTIL_CHECK_DOWNLOAD
if result in (PixivConstant.PIXIVUTIL_OK,
PixivConstant.PIXIVUTIL_SKIP_DUPLICATE,
PixivConstant.PIXIVUTIL_SKIP_LOCAL_LARGER):
try:
db.insertImage(image.artist.artistId, image.imageId, image.imageMode)
except BaseException:
PixivHelper.print_and_log('error', f'Failed to insert image id:{image.imageId} to DB')
db.updateImage(image.imageId, image.imageTitle, filename, image.imageMode)
if len(manga_files) > 0:
db.insertMangaImages(manga_files)
result = 0
if image is not None:
del image
if parse_medium_page is not None:
del parse_medium_page
gc.collect()
PixivHelper.print_and_log(None, '\n')
return result
except Exception as ex:
if isinstance(ex, KeyboardInterrupt):
raise
caller.ERROR_CODE = getattr(ex, 'errorCode', -1)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.print_and_log('error', f'Error at process_image(): {image_id}')
PixivHelper.print_and_log('error', f'Exception: {sys.exc_info()}')
if parse_medium_page is not None:
dump_filename = f'Error medium page for image {image_id}.html'
PixivHelper.dump_html(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', f'Dumping html to: {dump_filename}')
raise
def process_manga_series(caller,
config,
manga_series_id: int,
start_page: int = 1,
end_page: int = 0,
notifier=None):
if notifier is None:
notifier = PixivHelper.dummy_notifier
try:
msg = Fore.YELLOW + Style.NORMAL + f'Processing Manga Series Id: {manga_series_id}' + Style.RESET_ALL
PixivHelper.print_and_log(None, msg)
notifier(type="MANGA_SERIES", message=msg)
if start_page != 1:
PixivHelper.print_and_log('info', 'Start Page: ' + str(start_page))
if end_page != 0:
PixivHelper.print_and_log('info', 'End Page: ' + str(end_page))
flag = True
current_page = start_page
while flag:
manga_series = PixivBrowserFactory.getBrowser().getMangaSeries(manga_series_id, current_page)
for (image_id, order) in manga_series.pages_with_order:
result = process_image(caller,
config,
artist=manga_series.artist,
image_id=image_id,
user_dir='',
bookmark=False,
search_tags='',
title_prefix="",
bookmark_count=-1,
image_response_count=-1,
notifier=notifier,
useblacklist=True,
manga_series_order=order,
manga_series_parent=manga_series)
PixivHelper.wait(result, config)
current_page += 1
if manga_series.is_last_page:
PixivHelper.print_and_log('info', f'Last Page {manga_series.current_page}')
flag = False
if current_page > end_page and end_page != 0:
PixivHelper.print_and_log('info', f'End Page reached {end_page}')
flag = False
if manga_series.pages_with_order is None or len(manga_series.pages_with_order) == 0:
PixivHelper.print_and_log('info', 'No more works.')
flag = False
except Exception as ex:
if isinstance(ex, KeyboardInterrupt):
raise
caller.ERROR_CODE = getattr(ex, 'errorCode', -1)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.print_and_log('error', f'Error at process_manga_series(): {manga_series_id}')
PixivHelper.print_and_log('error', f'Exception: {sys.exc_info()}')
raise
| true | true |
1c470806e2e0c073cf45685cb91f84d5d2ad841e | 725 | py | Python | jinjamator/plugins/content/timestamp/__init__.py | jinjamator/jinjamator | 6c48a6eedea9b9f461c66b5dddd609fa39610f0d | [
"Apache-2.0"
] | 7 | 2020-05-06T07:48:14.000Z | 2021-12-11T15:57:26.000Z | jinjamator/plugins/content/timestamp/__init__.py | jinjamator/jinjamator | 6c48a6eedea9b9f461c66b5dddd609fa39610f0d | [
"Apache-2.0"
] | 1 | 2020-04-11T15:13:07.000Z | 2020-04-27T20:01:34.000Z | jinjamator/plugins/content/timestamp/__init__.py | jinjamator/jinjamator | 6c48a6eedea9b9f461c66b5dddd609fa39610f0d | [
"Apache-2.0"
] | 1 | 2020-05-29T08:53:08.000Z | 2020-05-29T08:53:08.000Z | # Copyright 2020 Wilhelm Putz
# 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 time
import datetime
def today():
"""
returns a timestamp of today
"""
return time.mktime(datetime.date.today().timetuple())
| 30.208333 | 74 | 0.742069 |
import time
import datetime
def today():
return time.mktime(datetime.date.today().timetuple())
| true | true |
1c4708bae8c58607204d0b5e3851cd19bbe5f2b7 | 532 | py | Python | backend/home/migrations/0001_load_initial_data.py | crowdbotics-apps/waaafaa-33427 | 111391747de3d04519e8c83f809e510ba5f53267 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/home/migrations/0001_load_initial_data.py | crowdbotics-apps/waaafaa-33427 | 111391747de3d04519e8c83f809e510ba5f53267 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/home/migrations/0001_load_initial_data.py | crowdbotics-apps/waaafaa-33427 | 111391747de3d04519e8c83f809e510ba5f53267 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | from django.db import migrations
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "waaafaa-33427.botics.co"
site_params = {
"name": "waaafaa",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(defaults=site_params, id=1)
class Migration(migrations.Migration):
dependencies = [
("sites", "0002_alter_domain_unique"),
]
operations = [
migrations.RunPython(create_site),
]
| 20.461538 | 61 | 0.654135 | from django.db import migrations
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "waaafaa-33427.botics.co"
site_params = {
"name": "waaafaa",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(defaults=site_params, id=1)
class Migration(migrations.Migration):
dependencies = [
("sites", "0002_alter_domain_unique"),
]
operations = [
migrations.RunPython(create_site),
]
| true | true |
1c4709825b92854677eea70e53d6029daae416e6 | 157 | py | Python | lib/python/logan/__init__.py | melver/logan | e90da84388b1e966cf24f778cbabfee62d324c7d | [
"BSD-3-Clause"
] | null | null | null | lib/python/logan/__init__.py | melver/logan | e90da84388b1e966cf24f778cbabfee62d324c7d | [
"BSD-3-Clause"
] | null | null | null | lib/python/logan/__init__.py | melver/logan | e90da84388b1e966cf24f778cbabfee62d324c7d | [
"BSD-3-Clause"
] | null | null | null | """
Log Analyser
"""
import os
BASEPATH = os.path.abspath(os.path.join(
__file__, os.path.pardir, os.path.pardir, os.path.pardir,
os.path.pardir))
| 15.7 | 61 | 0.675159 |
import os
BASEPATH = os.path.abspath(os.path.join(
__file__, os.path.pardir, os.path.pardir, os.path.pardir,
os.path.pardir))
| true | true |
1c4709bd604c2f039002201b03f0a84178da694d | 7,125 | py | Python | utils/py27/Lib/test/test_glob.py | xahmol/8bit-Unity | b4f3bee00e012ca1755afba550a5270dce0a1054 | [
"BSD-2-Clause"
] | 42 | 2018-12-12T01:00:59.000Z | 2022-03-27T07:32:29.000Z | utils/py27/Lib/test/test_glob.py | xahmol/8bit-Unity | b4f3bee00e012ca1755afba550a5270dce0a1054 | [
"BSD-2-Clause"
] | 13 | 2020-11-06T13:50:45.000Z | 2022-01-25T07:17:37.000Z | utils/py27/Lib/test/test_glob.py | xahmol/8bit-Unity | b4f3bee00e012ca1755afba550a5270dce0a1054 | [
"BSD-2-Clause"
] | 8 | 2020-11-14T04:30:26.000Z | 2021-01-16T17:55:19.000Z | import glob
import os
import shutil
import sys
import unittest
from test.test_support import run_unittest, TESTFN
def fsdecode(s):
return unicode(s, sys.getfilesystemencoding())
class GlobTests(unittest.TestCase):
def norm(self, *parts):
return os.path.normpath(os.path.join(self.tempdir, *parts))
def mktemp(self, *parts):
filename = self.norm(*parts)
base, file = os.path.split(filename)
if not os.path.exists(base):
os.makedirs(base)
f = open(filename, 'w')
f.close()
def setUp(self):
self.tempdir = TESTFN + "_dir"
self.mktemp('a', 'D')
self.mktemp('aab', 'F')
self.mktemp('.aa', 'G')
self.mktemp('.bb', 'H')
self.mktemp('aaa', 'zzzF')
self.mktemp('ZZZ')
self.mktemp('a', 'bcd', 'EF')
self.mktemp('a', 'bcd', 'efg', 'ha')
if hasattr(os, 'symlink'):
os.symlink(self.norm('broken'), self.norm('sym1'))
os.symlink('broken', self.norm('sym2'))
os.symlink(os.path.join('a', 'bcd'), self.norm('sym3'))
def tearDown(self):
shutil.rmtree(self.tempdir)
def glob(self, *parts):
if len(parts) == 1:
pattern = parts[0]
else:
pattern = os.path.join(*parts)
p = os.path.join(self.tempdir, pattern)
res = glob.glob(p)
self.assertItemsEqual(glob.iglob(p), res)
ures = [fsdecode(x) for x in res]
self.assertItemsEqual(glob.glob(fsdecode(p)), ures)
self.assertItemsEqual(glob.iglob(fsdecode(p)), ures)
return res
def assertSequencesEqual_noorder(self, l1, l2):
l1 = list(l1)
l2 = list(l2)
self.assertEqual(set(l1), set(l2))
self.assertEqual(sorted(l1), sorted(l2))
def test_glob_literal(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('a'), [self.norm('a')])
eq(self.glob('a', 'D'), [self.norm('a', 'D')])
eq(self.glob('aab'), [self.norm('aab')])
eq(self.glob('zymurgy'), [])
res = glob.glob('*')
self.assertEqual({type(r) for r in res}, {str})
res = glob.glob(os.path.join(os.curdir, '*'))
self.assertEqual({type(r) for r in res}, {str})
# test return types are unicode, but only if os.listdir
# returns unicode filenames
tmp = os.listdir(fsdecode(os.curdir))
if {type(x) for x in tmp} == {unicode}:
res = glob.glob(u'*')
self.assertEqual({type(r) for r in res}, {unicode})
res = glob.glob(os.path.join(fsdecode(os.curdir), u'*'))
self.assertEqual({type(r) for r in res}, {unicode})
def test_glob_one_directory(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('a*'), map(self.norm, ['a', 'aab', 'aaa']))
eq(self.glob('*a'), map(self.norm, ['a', 'aaa']))
eq(self.glob('.*'), map(self.norm, ['.aa', '.bb']))
eq(self.glob('?aa'), map(self.norm, ['aaa']))
eq(self.glob('aa?'), map(self.norm, ['aaa', 'aab']))
eq(self.glob('aa[ab]'), map(self.norm, ['aaa', 'aab']))
eq(self.glob('*q'), [])
def test_glob_nested_directory(self):
eq = self.assertSequencesEqual_noorder
if os.path.normcase("abCD") == "abCD":
# case-sensitive filesystem
eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF')])
else:
# case insensitive filesystem
eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF'),
self.norm('a', 'bcd', 'efg')])
eq(self.glob('a', 'bcd', '*g'), [self.norm('a', 'bcd', 'efg')])
def test_glob_directory_names(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('*', 'D'), [self.norm('a', 'D')])
eq(self.glob('*', '*a'), [])
eq(self.glob('a', '*', '*', '*a'),
[self.norm('a', 'bcd', 'efg', 'ha')])
eq(self.glob('?a?', '*F'), [self.norm('aaa', 'zzzF'),
self.norm('aab', 'F')])
def test_glob_directory_with_trailing_slash(self):
# Patterns ending with a slash shouldn't match non-dirs
res = glob.glob(self.norm('Z*Z') + os.sep)
self.assertEqual(res, [])
res = glob.glob(self.norm('ZZZ') + os.sep)
self.assertEqual(res, [])
# When there is a wildcard pattern which ends with os.sep, glob()
# doesn't blow up.
res = glob.glob(self.norm('aa*') + os.sep)
self.assertEqual(len(res), 2)
# either of these results is reasonable
self.assertIn(set(res), [
{self.norm('aaa'), self.norm('aab')},
{self.norm('aaa') + os.sep, self.norm('aab') + os.sep},
])
def test_glob_unicode_directory_with_trailing_slash(self):
# Same as test_glob_directory_with_trailing_slash, but with an
# unicode argument.
res = glob.glob(fsdecode(self.norm('Z*Z') + os.sep))
self.assertEqual(res, [])
res = glob.glob(fsdecode(self.norm('ZZZ') + os.sep))
self.assertEqual(res, [])
res = glob.glob(fsdecode(self.norm('aa*') + os.sep))
self.assertEqual(len(res), 2)
# either of these results is reasonable
self.assertIn(set(res), [
{fsdecode(self.norm('aaa')), fsdecode(self.norm('aab'))},
{fsdecode(self.norm('aaa') + os.sep),
fsdecode(self.norm('aab') + os.sep)},
])
@unittest.skipUnless(hasattr(os, 'symlink'), "Requires symlink support")
def test_glob_symlinks(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('sym3'), [self.norm('sym3')])
eq(self.glob('sym3', '*'), [self.norm('sym3', 'EF'),
self.norm('sym3', 'efg')])
self.assertIn(self.glob('sym3' + os.sep),
[[self.norm('sym3')], [self.norm('sym3') + os.sep]])
eq(self.glob('*', '*F'),
[self.norm('aaa', 'zzzF'), self.norm('aab', 'F'),
self.norm('sym3', 'EF')])
@unittest.skipUnless(hasattr(os, 'symlink'), "Requires symlink support")
def test_glob_broken_symlinks(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('sym*'), [self.norm('sym1'), self.norm('sym2'),
self.norm('sym3')])
eq(self.glob('sym1'), [self.norm('sym1')])
eq(self.glob('sym2'), [self.norm('sym2')])
@unittest.skipUnless(sys.platform == "win32", "Win32 specific test")
def test_glob_magic_in_drive(self):
eq = self.assertSequencesEqual_noorder
eq(glob.glob('*:'), [])
eq(glob.glob(u'*:'), [])
eq(glob.glob('?:'), [])
eq(glob.glob(u'?:'), [])
def test_main():
run_unittest(GlobTests)
if __name__ == "__main__":
test_main()
| 39.148352 | 80 | 0.520982 | import glob
import os
import shutil
import sys
import unittest
from test.test_support import run_unittest, TESTFN
def fsdecode(s):
return unicode(s, sys.getfilesystemencoding())
class GlobTests(unittest.TestCase):
def norm(self, *parts):
return os.path.normpath(os.path.join(self.tempdir, *parts))
def mktemp(self, *parts):
filename = self.norm(*parts)
base, file = os.path.split(filename)
if not os.path.exists(base):
os.makedirs(base)
f = open(filename, 'w')
f.close()
def setUp(self):
self.tempdir = TESTFN + "_dir"
self.mktemp('a', 'D')
self.mktemp('aab', 'F')
self.mktemp('.aa', 'G')
self.mktemp('.bb', 'H')
self.mktemp('aaa', 'zzzF')
self.mktemp('ZZZ')
self.mktemp('a', 'bcd', 'EF')
self.mktemp('a', 'bcd', 'efg', 'ha')
if hasattr(os, 'symlink'):
os.symlink(self.norm('broken'), self.norm('sym1'))
os.symlink('broken', self.norm('sym2'))
os.symlink(os.path.join('a', 'bcd'), self.norm('sym3'))
def tearDown(self):
shutil.rmtree(self.tempdir)
def glob(self, *parts):
if len(parts) == 1:
pattern = parts[0]
else:
pattern = os.path.join(*parts)
p = os.path.join(self.tempdir, pattern)
res = glob.glob(p)
self.assertItemsEqual(glob.iglob(p), res)
ures = [fsdecode(x) for x in res]
self.assertItemsEqual(glob.glob(fsdecode(p)), ures)
self.assertItemsEqual(glob.iglob(fsdecode(p)), ures)
return res
def assertSequencesEqual_noorder(self, l1, l2):
l1 = list(l1)
l2 = list(l2)
self.assertEqual(set(l1), set(l2))
self.assertEqual(sorted(l1), sorted(l2))
def test_glob_literal(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('a'), [self.norm('a')])
eq(self.glob('a', 'D'), [self.norm('a', 'D')])
eq(self.glob('aab'), [self.norm('aab')])
eq(self.glob('zymurgy'), [])
res = glob.glob('*')
self.assertEqual({type(r) for r in res}, {str})
res = glob.glob(os.path.join(os.curdir, '*'))
self.assertEqual({type(r) for r in res}, {str})
tmp = os.listdir(fsdecode(os.curdir))
if {type(x) for x in tmp} == {unicode}:
res = glob.glob(u'*')
self.assertEqual({type(r) for r in res}, {unicode})
res = glob.glob(os.path.join(fsdecode(os.curdir), u'*'))
self.assertEqual({type(r) for r in res}, {unicode})
def test_glob_one_directory(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('a*'), map(self.norm, ['a', 'aab', 'aaa']))
eq(self.glob('*a'), map(self.norm, ['a', 'aaa']))
eq(self.glob('.*'), map(self.norm, ['.aa', '.bb']))
eq(self.glob('?aa'), map(self.norm, ['aaa']))
eq(self.glob('aa?'), map(self.norm, ['aaa', 'aab']))
eq(self.glob('aa[ab]'), map(self.norm, ['aaa', 'aab']))
eq(self.glob('*q'), [])
def test_glob_nested_directory(self):
eq = self.assertSequencesEqual_noorder
if os.path.normcase("abCD") == "abCD":
eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF')])
else:
eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF'),
self.norm('a', 'bcd', 'efg')])
eq(self.glob('a', 'bcd', '*g'), [self.norm('a', 'bcd', 'efg')])
def test_glob_directory_names(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('*', 'D'), [self.norm('a', 'D')])
eq(self.glob('*', '*a'), [])
eq(self.glob('a', '*', '*', '*a'),
[self.norm('a', 'bcd', 'efg', 'ha')])
eq(self.glob('?a?', '*F'), [self.norm('aaa', 'zzzF'),
self.norm('aab', 'F')])
def test_glob_directory_with_trailing_slash(self):
res = glob.glob(self.norm('Z*Z') + os.sep)
self.assertEqual(res, [])
res = glob.glob(self.norm('ZZZ') + os.sep)
self.assertEqual(res, [])
# When there is a wildcard pattern which ends with os.sep, glob()
# doesn't blow up.
res = glob.glob(self.norm('aa*') + os.sep)
self.assertEqual(len(res), 2)
self.assertIn(set(res), [
{self.norm('aaa'), self.norm('aab')},
{self.norm('aaa') + os.sep, self.norm('aab') + os.sep},
])
def test_glob_unicode_directory_with_trailing_slash(self):
res = glob.glob(fsdecode(self.norm('Z*Z') + os.sep))
self.assertEqual(res, [])
res = glob.glob(fsdecode(self.norm('ZZZ') + os.sep))
self.assertEqual(res, [])
res = glob.glob(fsdecode(self.norm('aa*') + os.sep))
self.assertEqual(len(res), 2)
self.assertIn(set(res), [
{fsdecode(self.norm('aaa')), fsdecode(self.norm('aab'))},
{fsdecode(self.norm('aaa') + os.sep),
fsdecode(self.norm('aab') + os.sep)},
])
@unittest.skipUnless(hasattr(os, 'symlink'), "Requires symlink support")
def test_glob_symlinks(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('sym3'), [self.norm('sym3')])
eq(self.glob('sym3', '*'), [self.norm('sym3', 'EF'),
self.norm('sym3', 'efg')])
self.assertIn(self.glob('sym3' + os.sep),
[[self.norm('sym3')], [self.norm('sym3') + os.sep]])
eq(self.glob('*', '*F'),
[self.norm('aaa', 'zzzF'), self.norm('aab', 'F'),
self.norm('sym3', 'EF')])
@unittest.skipUnless(hasattr(os, 'symlink'), "Requires symlink support")
def test_glob_broken_symlinks(self):
eq = self.assertSequencesEqual_noorder
eq(self.glob('sym*'), [self.norm('sym1'), self.norm('sym2'),
self.norm('sym3')])
eq(self.glob('sym1'), [self.norm('sym1')])
eq(self.glob('sym2'), [self.norm('sym2')])
@unittest.skipUnless(sys.platform == "win32", "Win32 specific test")
def test_glob_magic_in_drive(self):
eq = self.assertSequencesEqual_noorder
eq(glob.glob('*:'), [])
eq(glob.glob(u'*:'), [])
eq(glob.glob('?:'), [])
eq(glob.glob(u'?:'), [])
def test_main():
run_unittest(GlobTests)
if __name__ == "__main__":
test_main()
| true | true |
1c470a2db8942a6dac55dd86e4e59735900d2028 | 17,980 | py | Python | bamnostic/bai.py | pleongpt/bamnostic | c1d0b9035c9d3c3172fc276d26999884d6c4fa38 | [
"BSD-3-Clause"
] | null | null | null | bamnostic/bai.py | pleongpt/bamnostic | c1d0b9035c9d3c3172fc276d26999884d6c4fa38 | [
"BSD-3-Clause"
] | null | null | null | bamnostic/bai.py | pleongpt/bamnostic | c1d0b9035c9d3c3172fc276d26999884d6c4fa38 | [
"BSD-3-Clause"
] | 1 | 2019-11-09T06:03:16.000Z | 2019-11-09T06:03:16.000Z | #!/user/bin/env python
# -*- coding: utf-8 -*-
"""BAI file parser
.. include:: <isonum.txt>
Copyright |copy| 2018, Marcus D. Sherman
This code is part of the bamnostic distribution and governed by its
license. Please see the LICENSE file that should have been included
as part of this package.
The Binary Alignment Map (BAM) format (defined at https://samtools.github.io/hts-specs/SAMv1.pdf)
allows for indexing. When the user invokes a tool to index a given BAM file, a BAM index (BAI)
file is created. Generally speaking, a BAI contains the all the virtual offsets of clusters of
reads that are associated with specific subsections of the BAM file. When the BAI is produced,
random access to the BAM is available.
This script is for parsing the binary encoded BAI file, inherently making it human readable.
Furthermore, it allows subsections of the BAI to be loaded into memory, reducing the memory
footprint and speeding up queries within a small number of references. Lastly, by parsing it
as such, random access queries directly into the associated BAM file is available to other
tools within bamnostic
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import struct
import os
import sys
import warnings
from array import array
from collections import namedtuple
_PY_VERSION = sys.version_info
if _PY_VERSION[0] == 2:
from io import open
else:
from functools import lru_cache
from bamnostic.utils import *
warnings.formatwarning = format_warnings
# Helper compiled structs
unpack_chunk = struct.Struct('<2Q').unpack
unpack_intervals = struct.Struct('<Q').unpack
unpack_bid_nchunk = struct.Struct('<Ii').unpack
unpack_unmapped = struct.Struct('<4Q').unpack
class conditional_decorator(object):
def __init__(self, dec, condition):
self.decorator = dec
self.condition = condition
def __call__(self, func):
if self.condition:
# Return the function unchanged, not decorated.
return func
return self.decorator(func)
# __slot__ classes for performant named indexing and future-proofing &readability
RefIdx = namedtuple('RefIdx', ('start_offset', 'end_offset', 'n_bins'))
class Chunk(object):
__slots__ = ['voffset_beg', 'voffset_end']
def __init__(self, handle):
self.voffset_beg, self.voffset_end = unpack_chunk(handle.read(16))
def __repr__(self):
return 'Chunk(voffset_beg={}, voffset_end={})'.format(self.voffset_beg, self.voffset_end)
class Ref(object):
__slots__ = ['bins', 'intervals', 'ref_id']
def __init__(self, *args):
self.bins, self.intervals, self.ref_id = args
def __getitem__(self, key):
return self.bins[key]
class Unmapped(object):
__slots__ = ['unmapped_beg', 'unmapped_end', 'n_mapped', 'n_unmapped']
def __init__(self, ubeg, uend, nmap, numap):
self.unmapped_beg = ubeg
self.unmapped_end = uend
self.n_mapped = nmap
self.n_unmapped = numap
def reg2bin(rbeg, rend):
"""Finds the largest superset bin of region. Numeric values taken from hts-specs
Args:
rbeg (int): inclusive beginning position of region
rend (int): exclusive end position of region
Returns:
(int): distinct bin ID for largest superset bin of region
"""
left_shift = 15
for i in range(14, 27, 3):
if rbeg >> i == (rend - 1) >> i:
return int(((1 << left_shift) - 1) / 7 + (rbeg >> i))
left_shift -= 3
else:
return 0
def reg2bins(rbeg, rend):
"""Generates bin ids which overlap the specified region.
Args:
rbeg (int): inclusive beginning position of region
rend (int): exclusive end position of region
Yields:
(int): bin IDs for overlapping bins of region
Raises:
AssertionError (Exception): if the range is malformed or invalid
"""
# Based off the algorithm presented in:
# https://samtools.github.io/hts-specs/SAMv1.pdf
# Bin calculation constants.
BIN_ID_STARTS = (0, 1, 9, 73, 585, 4681)
# Maximum range supported by specifications.
MAX_RNG = (2 ** 29) - 1
assert 0 <= rbeg <= rend <= MAX_RNG, 'Invalid region {}, {}'.format(rbeg, rend)
for start, shift in zip(BIN_ID_STARTS, range(29, 13, -3)):
i = rbeg >> shift if rbeg > 0 else 0
j = rend >> shift if rend < MAX_RNG else MAX_RNG >> shift
for bin_id_offset in range(i, j + 1):
yield start + bin_id_offset
class Bai(object):
""" This class defines the bam index file object and its interface.
The purpose of this class is the binary parsing of the bam index file (BAI) associated with
a given bam file. When queried, the Bai object identifies the bins of data that overlap the
requested region and directs which parts of the bam file contain it.
Virtual offsets are processed using the following method:
Beginning of compressed block = coffset = virtual offset >> 16
Position within uncompressed block = uoffset = virtual offset ^ (coffset << 16)
Attributes:
_io (fileObject): opened BAI file object
_LINEAR_INDEX_WINDOW (int): constant of the linear interval window size
_UNMAP_BIN (int): constant for bin ID of unmapped read stats
magic (bytes): first 4 bytes of file. Must be equal to b'BAI\x01'
n_refs (int): number of references in BAI
unmapped (dict): dictionary of the unmapped read stats by each reference
current_ref (None|dict): dictionary of the current reference loaded into memory.
It contains the a dictionary of bin IDs and their respective
chunks, and a list of linear intervals.
ref_indices (dict): dictionary of reference ids and their start/stop offsets within the BAI file
n_no_coord (None|int): if present in BAI, is the number of reads that have no coordinates
_last_pos (int): used for indexing, the byte position of the file head.
"""
__slots__ = ['_io', '_LINEAR_INDEX_WINDOW', '_UNMAP_BIN', 'BAM_LIDX_SHIFT',
'magic', 'n_refs', 'unmapped', 'current_ref', 'ref_indices',
'n_no_coor', '_last_pos']
def __init__(self, filename):
"""Initialization method
Generates an "index" of the index. This gives us the byte positions of each chromosome
within the index file. Now, when a user queries over a specific chromosome, it pulls
out just the index information for that chromosome--not the whole genome.
Args:
filename (str): '/path/to/bam_file' that automatically adds the '.bai' suffix
Raises:
OSError (Exception): if the BAI file is not found or does not exist
AssertionError (Exception): if BAI magic is not found
"""
if os.path.isfile(filename):
self._io = open(filename, 'rb')
else:
raise OSError('{} not found. Please change check your path or index your BAM file'.format(filename))
# Constant for linear index window size and unmapped bin id
self._LINEAR_INDEX_WINDOW = 16384
self._UNMAP_BIN = 37450
self.BAM_LIDX_SHIFT = 14
self.magic, self.n_refs = unpack("<4sl", self._io)
assert self.magic == b'BAI\x01', 'Wrong BAI magic header'
self.unmapped = {}
self.current_ref = None
# Capture the offsets for each reference within the index
self.ref_indices = {ref: self.get_ref(ref, idx=True) for ref in range(self.n_refs)}
# Get the n_no_coor if it is present
nnc_dat = self._io.read(8)
self.n_no_coor = unpack('<Q', nnc_dat) if nnc_dat else None
self._last_pos = self._io.tell()
def get_chunks(self, n_chunks):
"""Simple generator for unpacking chunk data
Chunks are defined as groupings of reads within a BAM file
that share the same bin. A `Chunk` object in the context of
this function is a `namedtuple` that contains the virtual offsets
for the beginning and end of each of these chunks.
Note: a special case of a chunk is in any Bin labeled as 37450.
These bins always contain 2 chunks that provide the statistics
of the number of reads that are unmapped to that reference.
Args:
n_chunks (int): number of chunks to be unpacked from stream
Returns:
chunks (list): a list of Chunk objects with the attributes of
chunks[i] are .voffset_beg and voffset_end
"""
chunks = [Chunk(self._io) for chunk in range(n_chunks)]
return chunks
# TODO: Add a check for long reads and allow for skipping the linear index on queries
def get_ints(self, n_int):
"""Unpacks `n_int` number of interval virtual offsets from stream
A linear interval is defined as a 16384 bp window along a given reference. The
value stored in the BAI is the virtual offset of the first read within
that given interval. This virtual offset is the byte offset (coffset) of the start of the
BGZF block that contains the beginning of the read and the byte offset (uoffset)
within the uncompressed data of the residing BGZF block to that first read.
Note: a caveat to using linear interval with long reads: A long read can
span multiple linear intervals. As such, the current encoding could potentially shift
the expected region of interest to the left more than expected.
Args:
n_int (int): number of intervals to unpack
Returns:
intervals (list): list of virtual offsets for `n_int` number of linear intervals
"""
intervals = unpack('<{}Q'.format(n_int), self._io)
return intervals if type(intervals) != int else [intervals]
def get_bins(self, n_bins, ref_id=None, idx=False):
"""Simple function that iteratively unpacks the data of a number (`n_bin`)
of bins.
As the function discovers the number of chunks needed for a given
bin, it deletages work to `self.get_chunks(n_chunks)`. A bin is
comprised of 2 parts: 1) the distinct bin ID (within a given reference). If
no reads are associated with that bin, it is left out of the indexing process,
and therefore not represented in the BAI file. Furthermore, while each bin
has a bin ID, the bin IDs are only distinct within a given reference. This means
that 2 or more references can have the same bin IDs. These bin IDs are also
not in any order as they are essentially a hash dump. Lastly, the only reserved
bin ID is 37450. This bin relates to 2 chunks that contain the number of
unmapped and mapped reads for a given reference. 2) the chunk(s) of reads that
are assigned to a given bin.
As a secondary feature, this function will also quickly seek over regions for
the purposes of documenting the start and stop byte offsets of a given reference
block within the file. This is invoked by setting `idx=True`
Args:
n_int (int): number of bins to be unpacked from stream
Returns:
bins (None | dict): None if just indexing the index file or a dictionary
of `bin_id: chunks` pairs
Raises:
AssertionError (Exception): if bin 37450 does not contain 2 chunks exactly
"""
bins = None if idx else {}
for b in range(n_bins):
bin_id, n_chunks = unpack_bid_nchunk(self._io.read(8))
if idx:
if bin_id == self._UNMAP_BIN:
assert n_chunks == 2, 'Bin 3740 is supposed to have 2 chunks. This has {}'.format(n_chunks)
unmapped = Unmapped(*unpack_unmapped(self._io.read(32)))
self.unmapped[ref_id] = unmapped
else:
if not n_chunks == 0:
self._io.seek(16 * n_chunks, 1) # 16 = struct.calcsize('<2Q')
else:
chunks = self.get_chunks(n_chunks)
bins[bin_id] = chunks
else:
return bins
# Cache the references to speed up queries.
# @functools.lru_cache(maxsize=256, typed=True)
# @lru_cache(6)
@conditional_decorator(lambda func: lru_cache(maxsize=6)(func), _PY_VERSION[0] == 2)
def get_ref(self, ref_id=None, idx=False):
"""Interatively unpacks all the bins, linear intervals, and chunks for a given reference
A reference is comprised of 2 things: 1) a series of bins that reference chunks of aligned
reads that are grouped within that bin. 2) a series of virtual offsets of the first read of a
16384 bp window along the given reference.
This function also serves to "index" the BAI file such that, if it is invoked by setting
`ids=True`, will do a single pass through the BAI file and saving the start and stop
offsets of each of the references. This is used for minimizing the memory footprint of
storing the BAI in memory. When queried against, the appropriate reference block will be
loaded. Because of this constant loading, `functools.lru_cache` was applied to cache recently
used reference blocks to speed up computation. It is assumed that when querying is done, most
users are looking and just a few references at a time.
Args:
ref_id (None|int): used for random access or indexing the BAI
idx (bool): Flag for setting whether or not to run an index of the BAI
Returns:
RefIdx: `namedtuple` containing the byte offsets of the reference start, stop, and number of bins
or
Ref: `namedtuple` containing a dictionary of bins and list of linear intervals
Raises:
AssertionError (Exception): if, when random access is used, the current reference offset
does not match indexed reference offset.
"""
if ref_id is not None and not idx:
try:
ref_start, _, _ = self.ref_indices[ref_id]
self._io.seek(ref_start)
except KeyError:
raise KeyError('Reference is not found in header')
ref_start = self._io.tell()
if not idx:
assert ref_start == self.ref_indices[ref_id].start_offset, 'ref not properly aligned'
n_bins = unpack_int32L(self._io.read(4))[0]
bins = self.get_bins(n_bins, ref_id, idx)
n_int = unpack_int32L(self._io.read(4))[0]
if idx:
self._io.seek(8 * n_int, 1) # 8 = struct.calcsize('<Q')
ints = None if idx else self.get_ints(n_int)
self._last_pos = self._io.tell()
if idx:
return RefIdx(ref_start, self._last_pos, n_bins)
else:
return Ref(bins, ints, ref_id)
def query(self, ref_id, start, stop=-1):
""" Main query function for determining seek offset to BAM section that
AlignedRead objects from specified region start
Args:
ref (int): which reference/chromosome TID
start (int): left most bp position of region (zero-based)
stop (int): right most bp position of region (zero-based)
Returns:
(int): the voffset_beg of the first chunk given the chunk's voffset_end
is greater than the voffset of the linear index that overlaps
the region of interest's start offset
"""
if stop < 0:
end_offset = self.current_ref.intervals[-1] + 1
assert start <= stop, 'Malformed region: start should be <= stop, you entered {}, {}'.format(start, stop)
if self.current_ref is None:
self.current_ref = self.get_ref(ref_id)
elif self.current_ref.ref_id != ref_id:
self.current_ref = self.get_ref(ref_id)
# get linear index first
reg_lin_idx = start >> self.BAM_LIDX_SHIFT
l_idx = reg_lin_idx if reg_lin_idx < len(self.current_ref.intervals) else -1
linear_offset = self.current_ref.intervals[l_idx]
for binID in reg2bins(start, stop):
try:
bin_chunks = self.current_ref[binID]
except KeyError:
continue
for chunk in bin_chunks:
if chunk.voffset_beg <= linear_offset <= chunk.voffset_end:
return chunk.voffset_beg
def seek(self, offset=None, whence=0):
"""Simple seek function for binary files
Args:
offset (None|int): byte offset from whence to move the file head to.
whence (int): 0 := from start of file, 1:= from current position, 2:= from end of file
Returns:
(int): new byte position of file head
Raise:
ValueError (Exception): if the offset is not an integer or is not provided
"""
if isinstance(offset, (int, None)):
if offset is None:
raise ValueError('No offset provided')
else:
self._io.seek(offset, whence)
return self._io.tell()
else:
raise ValueError('offset must be an integer or None')
def read(self, size=-1):
"""Simple read function for binary files
Args:
size (int): number of bytes to read in (default: -1 --whole file)
Returns:
(bytes): the number of bytes read from file
"""
if size == 0:
return b''
else:
return self._io.read(size)
def tell(self):
"""Simple tell function for reporting byte position of file head
Returns:
(int): byte position of file head
"""
return self._io.tell()
| 39.172113 | 113 | 0.643826 |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import struct
import os
import sys
import warnings
from array import array
from collections import namedtuple
_PY_VERSION = sys.version_info
if _PY_VERSION[0] == 2:
from io import open
else:
from functools import lru_cache
from bamnostic.utils import *
warnings.formatwarning = format_warnings
unpack_chunk = struct.Struct('<2Q').unpack
unpack_intervals = struct.Struct('<Q').unpack
unpack_bid_nchunk = struct.Struct('<Ii').unpack
unpack_unmapped = struct.Struct('<4Q').unpack
class conditional_decorator(object):
def __init__(self, dec, condition):
self.decorator = dec
self.condition = condition
def __call__(self, func):
if self.condition:
return func
return self.decorator(func)
RefIdx = namedtuple('RefIdx', ('start_offset', 'end_offset', 'n_bins'))
class Chunk(object):
__slots__ = ['voffset_beg', 'voffset_end']
def __init__(self, handle):
self.voffset_beg, self.voffset_end = unpack_chunk(handle.read(16))
def __repr__(self):
return 'Chunk(voffset_beg={}, voffset_end={})'.format(self.voffset_beg, self.voffset_end)
class Ref(object):
__slots__ = ['bins', 'intervals', 'ref_id']
def __init__(self, *args):
self.bins, self.intervals, self.ref_id = args
def __getitem__(self, key):
return self.bins[key]
class Unmapped(object):
__slots__ = ['unmapped_beg', 'unmapped_end', 'n_mapped', 'n_unmapped']
def __init__(self, ubeg, uend, nmap, numap):
self.unmapped_beg = ubeg
self.unmapped_end = uend
self.n_mapped = nmap
self.n_unmapped = numap
def reg2bin(rbeg, rend):
left_shift = 15
for i in range(14, 27, 3):
if rbeg >> i == (rend - 1) >> i:
return int(((1 << left_shift) - 1) / 7 + (rbeg >> i))
left_shift -= 3
else:
return 0
def reg2bins(rbeg, rend):
BIN_ID_STARTS = (0, 1, 9, 73, 585, 4681)
MAX_RNG = (2 ** 29) - 1
assert 0 <= rbeg <= rend <= MAX_RNG, 'Invalid region {}, {}'.format(rbeg, rend)
for start, shift in zip(BIN_ID_STARTS, range(29, 13, -3)):
i = rbeg >> shift if rbeg > 0 else 0
j = rend >> shift if rend < MAX_RNG else MAX_RNG >> shift
for bin_id_offset in range(i, j + 1):
yield start + bin_id_offset
class Bai(object):
__slots__ = ['_io', '_LINEAR_INDEX_WINDOW', '_UNMAP_BIN', 'BAM_LIDX_SHIFT',
'magic', 'n_refs', 'unmapped', 'current_ref', 'ref_indices',
'n_no_coor', '_last_pos']
def __init__(self, filename):
if os.path.isfile(filename):
self._io = open(filename, 'rb')
else:
raise OSError('{} not found. Please change check your path or index your BAM file'.format(filename))
self._LINEAR_INDEX_WINDOW = 16384
self._UNMAP_BIN = 37450
self.BAM_LIDX_SHIFT = 14
self.magic, self.n_refs = unpack("<4sl", self._io)
assert self.magic == b'BAI\x01', 'Wrong BAI magic header'
self.unmapped = {}
self.current_ref = None
self.ref_indices = {ref: self.get_ref(ref, idx=True) for ref in range(self.n_refs)}
nnc_dat = self._io.read(8)
self.n_no_coor = unpack('<Q', nnc_dat) if nnc_dat else None
self._last_pos = self._io.tell()
def get_chunks(self, n_chunks):
chunks = [Chunk(self._io) for chunk in range(n_chunks)]
return chunks
def get_ints(self, n_int):
intervals = unpack('<{}Q'.format(n_int), self._io)
return intervals if type(intervals) != int else [intervals]
def get_bins(self, n_bins, ref_id=None, idx=False):
bins = None if idx else {}
for b in range(n_bins):
bin_id, n_chunks = unpack_bid_nchunk(self._io.read(8))
if idx:
if bin_id == self._UNMAP_BIN:
assert n_chunks == 2, 'Bin 3740 is supposed to have 2 chunks. This has {}'.format(n_chunks)
unmapped = Unmapped(*unpack_unmapped(self._io.read(32)))
self.unmapped[ref_id] = unmapped
else:
if not n_chunks == 0:
self._io.seek(16 * n_chunks, 1)
else:
chunks = self.get_chunks(n_chunks)
bins[bin_id] = chunks
else:
return bins
@conditional_decorator(lambda func: lru_cache(maxsize=6)(func), _PY_VERSION[0] == 2)
def get_ref(self, ref_id=None, idx=False):
if ref_id is not None and not idx:
try:
ref_start, _, _ = self.ref_indices[ref_id]
self._io.seek(ref_start)
except KeyError:
raise KeyError('Reference is not found in header')
ref_start = self._io.tell()
if not idx:
assert ref_start == self.ref_indices[ref_id].start_offset, 'ref not properly aligned'
n_bins = unpack_int32L(self._io.read(4))[0]
bins = self.get_bins(n_bins, ref_id, idx)
n_int = unpack_int32L(self._io.read(4))[0]
if idx:
self._io.seek(8 * n_int, 1)
ints = None if idx else self.get_ints(n_int)
self._last_pos = self._io.tell()
if idx:
return RefIdx(ref_start, self._last_pos, n_bins)
else:
return Ref(bins, ints, ref_id)
def query(self, ref_id, start, stop=-1):
if stop < 0:
end_offset = self.current_ref.intervals[-1] + 1
assert start <= stop, 'Malformed region: start should be <= stop, you entered {}, {}'.format(start, stop)
if self.current_ref is None:
self.current_ref = self.get_ref(ref_id)
elif self.current_ref.ref_id != ref_id:
self.current_ref = self.get_ref(ref_id)
reg_lin_idx = start >> self.BAM_LIDX_SHIFT
l_idx = reg_lin_idx if reg_lin_idx < len(self.current_ref.intervals) else -1
linear_offset = self.current_ref.intervals[l_idx]
for binID in reg2bins(start, stop):
try:
bin_chunks = self.current_ref[binID]
except KeyError:
continue
for chunk in bin_chunks:
if chunk.voffset_beg <= linear_offset <= chunk.voffset_end:
return chunk.voffset_beg
def seek(self, offset=None, whence=0):
if isinstance(offset, (int, None)):
if offset is None:
raise ValueError('No offset provided')
else:
self._io.seek(offset, whence)
return self._io.tell()
else:
raise ValueError('offset must be an integer or None')
def read(self, size=-1):
if size == 0:
return b''
else:
return self._io.read(size)
def tell(self):
return self._io.tell()
| true | true |
1c470a49de9d387d8b037e3f4380dafd7305f1b0 | 97 | py | Python | applications/gestiune/controllers/loguri.py | Vlad-Iliescu/gest | 32fbd3a859316727cd8564029d51b8d3c94cc0a0 | [
"BSD-3-Clause"
] | null | null | null | applications/gestiune/controllers/loguri.py | Vlad-Iliescu/gest | 32fbd3a859316727cd8564029d51b8d3c94cc0a0 | [
"BSD-3-Clause"
] | null | null | null | applications/gestiune/controllers/loguri.py | Vlad-Iliescu/gest | 32fbd3a859316727cd8564029d51b8d3c94cc0a0 | [
"BSD-3-Clause"
] | null | null | null | # coding: utf8
# try something like
def index():
return dict(message="hello from loguri.py")
| 19.4 | 47 | 0.701031 |
def index():
return dict(message="hello from loguri.py")
| true | true |
1c470b3dfa53ba320b1d4c3bc685983b1ace1149 | 2,253 | py | Python | tests/test_agent/test_http_api_config.py | guidow/pyfarm-agent | bb5d464f9f6549a3db3529a93e3d9f388b365586 | [
"Apache-2.0"
] | null | null | null | tests/test_agent/test_http_api_config.py | guidow/pyfarm-agent | bb5d464f9f6549a3db3529a93e3d9f388b365586 | [
"Apache-2.0"
] | null | null | null | tests/test_agent/test_http_api_config.py | guidow/pyfarm-agent | bb5d464f9f6549a3db3529a93e3d9f388b365586 | [
"Apache-2.0"
] | null | null | null | # No shebang line, this module is meant to be imported
#
# Copyright 2014 Oliver Palmer
#
# 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 json import loads
from datetime import datetime
from uuid import UUID
try:
from httplib import OK
except ImportError: # pragma: no cover
from http.client import OK
from twisted.web.server import NOT_DONE_YET
from pyfarm.agent.config import config
from pyfarm.agent.testutil import BaseAPITestCase
from pyfarm.agent.http.api.config import Config
class TestConfig(BaseAPITestCase):
URI = "/config"
CLASS = Config
DEFAULT_HEADERS = {"User-Agent": config["master_user_agent"]}
def test_get_config(self):
request = self.get()
config_ = Config()
response = config_.render(request)
self.assertEqual(response, NOT_DONE_YET)
self.assertTrue(request.finished)
self.assertEqual(request.responseCode, OK)
self.assertEqual(len(request.written), 1)
response = loads(request.written[0])
response.pop("last_master_contact")
current_config = config.copy()
current_config.pop("last_master_contact")
response.pop("agent")
for key in response:
self.assertIn(key, current_config)
# HTTP responses are not automatically
# converted from plain text into UUID
# objects.
if key == "agent_id":
response[key] = UUID(response[key])
self.assertEqual(
response[key], current_config[key],
"Data for key %r %r != %r" % (
key, response[key], current_config[key]))
self.assertDateAlmostEqual(
config.master_contacted(update=False), datetime.utcnow())
| 33.132353 | 74 | 0.678207 |
from json import loads
from datetime import datetime
from uuid import UUID
try:
from httplib import OK
except ImportError:
from http.client import OK
from twisted.web.server import NOT_DONE_YET
from pyfarm.agent.config import config
from pyfarm.agent.testutil import BaseAPITestCase
from pyfarm.agent.http.api.config import Config
class TestConfig(BaseAPITestCase):
URI = "/config"
CLASS = Config
DEFAULT_HEADERS = {"User-Agent": config["master_user_agent"]}
def test_get_config(self):
request = self.get()
config_ = Config()
response = config_.render(request)
self.assertEqual(response, NOT_DONE_YET)
self.assertTrue(request.finished)
self.assertEqual(request.responseCode, OK)
self.assertEqual(len(request.written), 1)
response = loads(request.written[0])
response.pop("last_master_contact")
current_config = config.copy()
current_config.pop("last_master_contact")
response.pop("agent")
for key in response:
self.assertIn(key, current_config)
if key == "agent_id":
response[key] = UUID(response[key])
self.assertEqual(
response[key], current_config[key],
"Data for key %r %r != %r" % (
key, response[key], current_config[key]))
self.assertDateAlmostEqual(
config.master_contacted(update=False), datetime.utcnow())
| true | true |
1c470c59b3b5466b5590486c24d50559f9296408 | 4,658 | py | Python | mpi/mpi4py/simple.py | timkphd/examples | 04c162ec890a1c9ba83498b275fbdc81a4704062 | [
"Unlicense"
] | 5 | 2020-11-01T00:29:22.000Z | 2022-01-24T19:09:47.000Z | mpi/mpi4py/simple.py | timkphd/examples | 04c162ec890a1c9ba83498b275fbdc81a4704062 | [
"Unlicense"
] | 1 | 2022-02-09T01:59:47.000Z | 2022-02-09T01:59:47.000Z | mpi/mpi4py/simple.py | timkphd/examples | 04c162ec890a1c9ba83498b275fbdc81a4704062 | [
"Unlicense"
] | null | null | null | #!/usr/bin/env python3
from mpi4py import MPI
import numpy
global numnodes,myid,mpi_err
global mpi_root
import sys
mpi_root=0
# This is a bag-of-tasks program. We define a manager task
# that distributes work to workers. Actually, the workers
# request input data. The manager sits in a loop calling
# Iprobe waiting for requests for work.
# In this case the manager reads input. The input is a list
# of file names. It will send a entry from the list as
# requested. When the worker is done processing it will
# request a new file name from the manager. This continues
# until the manager runs out of files to process. The
# manager subroutine is just "manager"
# The worker subroutine is "worker". It receives file names
# form the manager.
#
# The files in this case are outputs from an optics program
# tracking a laser beam as it propagates through the atmosphere.
# The workers read in the data and then create an image of the
# data by calling the routine mkview.plotit. This should worker
# with arbitrary 2d files except the size in mkview.plotit is
# currently hard coded to 64 x 64.
# We use the call to "Split" to create a seperate communicator
# for the workers. This is not important in this example but
# could be if you wanted multiple workers to work together.
# To get the data...
# curl http://hpc.mines.edu/examples/laser.tgz | tar -xz
def worker(THE_COMM_WORLD,managerid):
import mkview
x=0
comm=MPI.COMM_WORLD
send_msg = numpy.arange(1, dtype='i')
recv_msg = numpy.zeros_like(send_msg)
ic=0
while(True) :
# send message says I am ready for data #
send_msg[0]=x
comm.Send([send_msg, MPI.INT], dest=managerid, tag=1234)
# get a message from the manager #
buffer=numpy.array((1), dtype=str)
#buffer=numpy.asarray("000000000000000",dtype=str)
buffer=numpy.asarray(" ",dtype=str)
comm.Recv([buffer,MPI.CHAR], source=managerid, tag=2345)
# print(buffer)
x=str(buffer).split()
fname=x[0]
x=int(x[1])
if(x < 0):
return ic
print(THE_COMM_WORLD.Get_rank(),fname,x)
ic=ic+1
mkview.plotit(fname,x)
#
def manager(num_used,TODO):
global numnodes,myid,mpi_err
global mpi_root
comm=MPI.COMM_WORLD
send_msg = numpy.arange(1, dtype='i')
recv_msg = numpy.zeros_like(send_msg)
status = MPI.Status()
# our "data"
# Our worker is expecting a single word followed by a manager appended integer
data=sys.stdin.readlines()
todo=len(data)
# counters
igot=0
isent=0
while(isent < todo):
# wait for a request for work #
flag=comm.Iprobe(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG,status=status)
if(flag):
# where is it comming from #
gotfrom=status.source
sendto=gotfrom
comm.Recv([recv_msg, MPI.INT], source=gotfrom, tag=1234)
x=recv_msg[0]
print("worker %d sent %d" % (gotfrom,x))
if(x > -1):
igot=igot+1
print("igot "+str(igot))
if(isent < TODO):
# send real data #
d=data[isent]
d=d.strip()
send_msg=numpy.array([d+" "+str(isent)], dtype=str)
comm.Send([send_msg, MPI.CHAR], dest=sendto, tag=2345)
isent=isent+1
# tell everyone to quit #
for i in range(1,num_used+1):
send_msg=numpy.array(["stop -1000"], dtype=str)
comm.Send([send_msg, MPI.CHAR], dest=i, tag=2345)
return None
#
#
if __name__ == '__main__':
# do init
global numnodes,myid,mpi_err
comm=MPI.COMM_WORLD
myid=comm.Get_rank()
numnodes=comm.Get_size()
name = MPI.Get_processor_name()
print("hello from %d of %d on %s" % (myid,numnodes,name))
# num_used is the # of processors that are part of the new communicator #
# for this case hardwire to not include 1 processor #
num_used=numnodes-1
mannum=0;
MPI_COMM_WORLD=MPI.COMM_WORLD
if(myid == mannum):
group=0
else:
group=1
# Split will create a set of communicators. All of the
# tasks with the same value of group will be in the same
# communicator. In this case we get two sets one for the
# manager and one for the workers. The manager's version
# of the communicator is not used.
DEFINED_COMM=MPI_COMM_WORLD.Split(group,myid)
#
new_id=DEFINED_COMM.Get_rank()
worker_size=DEFINED_COMM.Get_size()
print("old id = %d new id = %d worker size = %d" %(myid,new_id,worker_size))
#
if(group == 0):
todo=1000
# if not part of the new group do management. #
manager(num_used,todo)
print("manager finished")
#mpi_err = MPI_Barrier(MPI_COMM_WORLD)
MPI_COMM_WORLD.barrier()
MPI.Finalize()
else:
# part of the new group do work. #
mannum=0;
ts=MPI.Wtime()
idid=worker(DEFINED_COMM,mannum)
te=MPI.Wtime()
print("worker (%d,%d) finished did %d tasks in %8.2f seconds" %(myid,new_id,idid,te-ts))
MPI_COMM_WORLD.barrier()
MPI.Finalize()
| 30.847682 | 91 | 0.709747 |
from mpi4py import MPI
import numpy
global numnodes,myid,mpi_err
global mpi_root
import sys
mpi_root=0
def worker(THE_COMM_WORLD,managerid):
import mkview
x=0
comm=MPI.COMM_WORLD
send_msg = numpy.arange(1, dtype='i')
recv_msg = numpy.zeros_like(send_msg)
ic=0
while(True) :
send_msg[0]=x
comm.Send([send_msg, MPI.INT], dest=managerid, tag=1234)
buffer=numpy.array((1), dtype=str)
buffer=numpy.asarray(" ",dtype=str)
comm.Recv([buffer,MPI.CHAR], source=managerid, tag=2345)
x=str(buffer).split()
fname=x[0]
x=int(x[1])
if(x < 0):
return ic
print(THE_COMM_WORLD.Get_rank(),fname,x)
ic=ic+1
mkview.plotit(fname,x)
def manager(num_used,TODO):
global numnodes,myid,mpi_err
global mpi_root
comm=MPI.COMM_WORLD
send_msg = numpy.arange(1, dtype='i')
recv_msg = numpy.zeros_like(send_msg)
status = MPI.Status()
data=sys.stdin.readlines()
todo=len(data)
igot=0
isent=0
while(isent < todo):
flag=comm.Iprobe(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG,status=status)
if(flag):
gotfrom=status.source
sendto=gotfrom
comm.Recv([recv_msg, MPI.INT], source=gotfrom, tag=1234)
x=recv_msg[0]
print("worker %d sent %d" % (gotfrom,x))
if(x > -1):
igot=igot+1
print("igot "+str(igot))
if(isent < TODO):
d=data[isent]
d=d.strip()
send_msg=numpy.array([d+" "+str(isent)], dtype=str)
comm.Send([send_msg, MPI.CHAR], dest=sendto, tag=2345)
isent=isent+1
for i in range(1,num_used+1):
send_msg=numpy.array(["stop -1000"], dtype=str)
comm.Send([send_msg, MPI.CHAR], dest=i, tag=2345)
return None
if __name__ == '__main__':
global numnodes,myid,mpi_err
comm=MPI.COMM_WORLD
myid=comm.Get_rank()
numnodes=comm.Get_size()
name = MPI.Get_processor_name()
print("hello from %d of %d on %s" % (myid,numnodes,name))
M_WORLD
if(myid == mannum):
group=0
else:
group=1
# of the communicator is not used.
DEFINED_COMM=MPI_COMM_WORLD.Split(group,myid)
#
new_id=DEFINED_COMM.Get_rank()
worker_size=DEFINED_COMM.Get_size()
print("old id = %d new id = %d worker size = %d" %(myid,new_id,worker_size))
#
if(group == 0):
todo=1000
# if not part of the new group do management. #
manager(num_used,todo)
print("manager finished")
#mpi_err = MPI_Barrier(MPI_COMM_WORLD)
MPI_COMM_WORLD.barrier()
MPI.Finalize()
else:
# part of the new group do work. #
mannum=0;
ts=MPI.Wtime()
idid=worker(DEFINED_COMM,mannum)
te=MPI.Wtime()
print("worker (%d,%d) finished did %d tasks in %8.2f seconds" %(myid,new_id,idid,te-ts))
MPI_COMM_WORLD.barrier()
MPI.Finalize()
| true | true |
1c470e24690527959feddd87aeb9fdc0e3b2b36e | 152 | py | Python | rtc_app/rtc/doctype/bus_location/test_bus_location.py | VishDroid-dev/rtc | 0feb16165ed06b5ea6aeec181c36253fcc5ad5aa | [
"MIT"
] | null | null | null | rtc_app/rtc/doctype/bus_location/test_bus_location.py | VishDroid-dev/rtc | 0feb16165ed06b5ea6aeec181c36253fcc5ad5aa | [
"MIT"
] | null | null | null | rtc_app/rtc/doctype/bus_location/test_bus_location.py | VishDroid-dev/rtc | 0feb16165ed06b5ea6aeec181c36253fcc5ad5aa | [
"MIT"
] | 1 | 2022-01-19T15:31:21.000Z | 2022-01-19T15:31:21.000Z | # Copyright (c) 2021, Foo Fighters and Contributors
# See license.txt
# import frappe
import unittest
class TestBusLocation(unittest.TestCase):
pass
| 16.888889 | 51 | 0.782895 |
import unittest
class TestBusLocation(unittest.TestCase):
pass
| true | true |
1c470e3760f76e19d9ac14656848fcf3703b18d2 | 6,396 | py | Python | flash/image/embedding/model.py | dmarx/lightning-flash | 4cda031c1f9c8d8754fd36b5720d2a5a7d866765 | [
"Apache-2.0"
] | null | null | null | flash/image/embedding/model.py | dmarx/lightning-flash | 4cda031c1f9c8d8754fd36b5720d2a5a7d866765 | [
"Apache-2.0"
] | null | null | null | flash/image/embedding/model.py | dmarx/lightning-flash | 4cda031c1f9c8d8754fd36b5720d2a5a7d866765 | [
"Apache-2.0"
] | 1 | 2022-02-28T15:59:39.000Z | 2022-02-28T15:59:39.000Z | # Copyright The PyTorch Lightning team.
#
# 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 warnings
from typing import Any, Dict, List, Optional
from flash.core.adapter import AdapterTask
from flash.core.data.io.input import DataKeys
from flash.core.data.states import (
CollateFn,
PerBatchTransform,
PerBatchTransformOnDevice,
PerSampleTransformOnDevice,
PostTensorTransform,
PreTensorTransform,
ToTensorTransform,
)
from flash.core.data.transforms import ApplyToKeys
from flash.core.registry import FlashRegistry
from flash.core.utilities.imports import _VISSL_AVAILABLE, requires
from flash.core.utilities.types import LR_SCHEDULER_TYPE, OPTIMIZER_TYPE
if _VISSL_AVAILABLE:
import classy_vision
import classy_vision.generic.distributed_util
from flash.image.embedding.backbones import IMAGE_EMBEDDER_BACKBONES
from flash.image.embedding.strategies import IMAGE_EMBEDDER_STRATEGIES
from flash.image.embedding.transforms import IMAGE_EMBEDDER_TRANSFORMS
# patch this to avoid classy vision/vissl based distributed training
classy_vision.generic.distributed_util.get_world_size = lambda: 1
else:
IMAGE_EMBEDDER_BACKBONES = FlashRegistry("backbones")
IMAGE_EMBEDDER_STRATEGIES = FlashRegistry("embedder_training_strategies")
IMAGE_EMBEDDER_TRANSFORMS = FlashRegistry("embedder_transforms")
class ImageEmbedder(AdapterTask):
"""The ``ImageEmbedder`` is a :class:`~flash.Task` for obtaining feature vectors (embeddings) from images. For
more details, see :ref:`image_embedder`.
Args:
training_strategy: Training strategy from VISSL,
select between 'simclr', 'swav', 'dino', 'moco', or 'barlow_twins'.
head: projection head used for task, select between
'simclr_head', 'swav_head', 'dino_head', 'moco_head', or 'barlow_twins_head'.
pretraining_transform: transform applied to input image for pre-training SSL model.
Select between 'simclr_transform', 'swav_transform', 'dino_transform',
'moco_transform', or 'barlow_twins_transform'.
backbone: VISSL backbone, defaults to ``resnet``.
pretrained: Use a pretrained backbone, defaults to ``False``.
optimizer: Optimizer to use for training.
lr_scheduler: The LR scheduler to use during training.
learning_rate: Learning rate to use for training, defaults to ``1e-3``.
backbone_kwargs: arguments to be passed to VISSL backbones, i.e. ``vision_transformer`` and ``resnet``.
training_strategy_kwargs: arguments passed to VISSL loss function, projection head and training hooks.
pretraining_transform_kwargs: arguments passed to VISSL transforms.
"""
training_strategies: FlashRegistry = IMAGE_EMBEDDER_STRATEGIES
backbones: FlashRegistry = IMAGE_EMBEDDER_BACKBONES
transforms: FlashRegistry = IMAGE_EMBEDDER_TRANSFORMS
required_extras: List[str] = ["image", "vissl", "fairscale"]
def __init__(
self,
training_strategy: str,
head: str,
pretraining_transform: str,
backbone: str = "resnet",
pretrained: bool = False,
optimizer: OPTIMIZER_TYPE = "Adam",
lr_scheduler: LR_SCHEDULER_TYPE = None,
learning_rate: float = 1e-3,
backbone_kwargs: Optional[Dict[str, Any]] = None,
training_strategy_kwargs: Optional[Dict[str, Any]] = None,
pretraining_transform_kwargs: Optional[Dict[str, Any]] = None,
):
self.save_hyperparameters()
if backbone_kwargs is None:
backbone_kwargs = {}
if training_strategy_kwargs is None:
training_strategy_kwargs = {}
if pretraining_transform_kwargs is None:
pretraining_transform_kwargs = {}
backbone, _ = self.backbones.get(backbone)(pretrained=pretrained, **backbone_kwargs)
metadata = self.training_strategies.get(training_strategy, with_metadata=True)
loss_fn, head, hooks = metadata["fn"](head=head, **training_strategy_kwargs)
adapter = metadata["metadata"]["adapter"].from_task(
self,
loss_fn=loss_fn,
backbone=backbone,
head=head,
hooks=hooks,
)
super().__init__(
adapter=adapter,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
learning_rate=learning_rate,
)
transform, collate_fn = self.transforms.get(pretraining_transform)(**pretraining_transform_kwargs)
to_tensor_transform = ApplyToKeys(
DataKeys.INPUT,
transform,
)
self.adapter.set_state(CollateFn(collate_fn))
self.adapter.set_state(ToTensorTransform(to_tensor_transform))
self.adapter.set_state(PostTensorTransform(None))
self.adapter.set_state(PreTensorTransform(None))
self.adapter.set_state(PerSampleTransformOnDevice(None))
self.adapter.set_state(PerBatchTransform(None))
self.adapter.set_state(PerBatchTransformOnDevice(None))
warnings.warn(
"Warning: VISSL ImageEmbedder overrides any user provided transforms"
" with pre-defined transforms for the training strategy."
)
def on_train_start(self) -> None:
self.adapter.on_train_start()
def on_train_epoch_end(self) -> None:
self.adapter.on_train_epoch_end()
def on_train_batch_end(self, outputs: Any, batch: Any, batch_idx: int, dataloader_idx: int) -> None:
self.adapter.on_train_batch_end(outputs, batch, batch_idx, dataloader_idx)
@classmethod
@requires(["image", "vissl", "fairscale"])
def available_training_strategies(cls) -> List[str]:
registry: Optional[FlashRegistry] = getattr(cls, "training_strategies", None)
if registry is None:
return []
return registry.available_keys()
| 40.738854 | 114 | 0.706848 |
import warnings
from typing import Any, Dict, List, Optional
from flash.core.adapter import AdapterTask
from flash.core.data.io.input import DataKeys
from flash.core.data.states import (
CollateFn,
PerBatchTransform,
PerBatchTransformOnDevice,
PerSampleTransformOnDevice,
PostTensorTransform,
PreTensorTransform,
ToTensorTransform,
)
from flash.core.data.transforms import ApplyToKeys
from flash.core.registry import FlashRegistry
from flash.core.utilities.imports import _VISSL_AVAILABLE, requires
from flash.core.utilities.types import LR_SCHEDULER_TYPE, OPTIMIZER_TYPE
if _VISSL_AVAILABLE:
import classy_vision
import classy_vision.generic.distributed_util
from flash.image.embedding.backbones import IMAGE_EMBEDDER_BACKBONES
from flash.image.embedding.strategies import IMAGE_EMBEDDER_STRATEGIES
from flash.image.embedding.transforms import IMAGE_EMBEDDER_TRANSFORMS
classy_vision.generic.distributed_util.get_world_size = lambda: 1
else:
IMAGE_EMBEDDER_BACKBONES = FlashRegistry("backbones")
IMAGE_EMBEDDER_STRATEGIES = FlashRegistry("embedder_training_strategies")
IMAGE_EMBEDDER_TRANSFORMS = FlashRegistry("embedder_transforms")
class ImageEmbedder(AdapterTask):
training_strategies: FlashRegistry = IMAGE_EMBEDDER_STRATEGIES
backbones: FlashRegistry = IMAGE_EMBEDDER_BACKBONES
transforms: FlashRegistry = IMAGE_EMBEDDER_TRANSFORMS
required_extras: List[str] = ["image", "vissl", "fairscale"]
def __init__(
self,
training_strategy: str,
head: str,
pretraining_transform: str,
backbone: str = "resnet",
pretrained: bool = False,
optimizer: OPTIMIZER_TYPE = "Adam",
lr_scheduler: LR_SCHEDULER_TYPE = None,
learning_rate: float = 1e-3,
backbone_kwargs: Optional[Dict[str, Any]] = None,
training_strategy_kwargs: Optional[Dict[str, Any]] = None,
pretraining_transform_kwargs: Optional[Dict[str, Any]] = None,
):
self.save_hyperparameters()
if backbone_kwargs is None:
backbone_kwargs = {}
if training_strategy_kwargs is None:
training_strategy_kwargs = {}
if pretraining_transform_kwargs is None:
pretraining_transform_kwargs = {}
backbone, _ = self.backbones.get(backbone)(pretrained=pretrained, **backbone_kwargs)
metadata = self.training_strategies.get(training_strategy, with_metadata=True)
loss_fn, head, hooks = metadata["fn"](head=head, **training_strategy_kwargs)
adapter = metadata["metadata"]["adapter"].from_task(
self,
loss_fn=loss_fn,
backbone=backbone,
head=head,
hooks=hooks,
)
super().__init__(
adapter=adapter,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
learning_rate=learning_rate,
)
transform, collate_fn = self.transforms.get(pretraining_transform)(**pretraining_transform_kwargs)
to_tensor_transform = ApplyToKeys(
DataKeys.INPUT,
transform,
)
self.adapter.set_state(CollateFn(collate_fn))
self.adapter.set_state(ToTensorTransform(to_tensor_transform))
self.adapter.set_state(PostTensorTransform(None))
self.adapter.set_state(PreTensorTransform(None))
self.adapter.set_state(PerSampleTransformOnDevice(None))
self.adapter.set_state(PerBatchTransform(None))
self.adapter.set_state(PerBatchTransformOnDevice(None))
warnings.warn(
"Warning: VISSL ImageEmbedder overrides any user provided transforms"
" with pre-defined transforms for the training strategy."
)
def on_train_start(self) -> None:
self.adapter.on_train_start()
def on_train_epoch_end(self) -> None:
self.adapter.on_train_epoch_end()
def on_train_batch_end(self, outputs: Any, batch: Any, batch_idx: int, dataloader_idx: int) -> None:
self.adapter.on_train_batch_end(outputs, batch, batch_idx, dataloader_idx)
@classmethod
@requires(["image", "vissl", "fairscale"])
def available_training_strategies(cls) -> List[str]:
registry: Optional[FlashRegistry] = getattr(cls, "training_strategies", None)
if registry is None:
return []
return registry.available_keys()
| true | true |
1c470f3b148dd13ad815f7979d810003cd90888e | 1,031 | py | Python | tests/datastructures/test_shuffle.py | TristenSeth/campy | 9e726c342d682239e1c19e6f5645c0b2167d7fab | [
"MIT"
] | 5 | 2018-12-03T19:18:50.000Z | 2021-05-31T07:17:06.000Z | tests/datastructures/test_shuffle.py | TristenSeth/campy | 9e726c342d682239e1c19e6f5645c0b2167d7fab | [
"MIT"
] | 1 | 2017-06-07T04:33:46.000Z | 2017-06-07T04:33:46.000Z | tests/datastructures/test_shuffle.py | TristenSeth/campy | 9e726c342d682239e1c19e6f5645c0b2167d7fab | [
"MIT"
] | 1 | 2017-06-06T07:29:07.000Z | 2017-06-06T07:29:07.000Z | """Tests for the :mod:`campy.datastructures.shuffle` module."""
# These reference shuffled values are being generated by Python running
# 3.7.2 (default, Dec 27 2018, 07:35:06) \n[Clang 10.0.0 (clang-1000.11.45.5)]
# on macOS 10.14.2
from campy.datastructures.shuffle import shuffle
import random
def test_shuffle_list():
random.seed(41)
assert shuffle([3, 1, 4, 1, 5, 9]) == [5, 9, 3, 1, 4, 1]
def test_shuffle_tuple():
random.seed(41)
assert shuffle((3, 1, 4, 1, 5, 9)) == (5, 9, 3, 1, 4, 1)
def test_shuffle_string():
random.seed(41)
assert shuffle('abcdefg') == 'afgebcd'
def test_shuffle_bytes():
random.seed(41)
assert shuffle(b'abcdefg') == b'afgebcd'
def test_shuffle_bytearray():
random.seed(41)
assert shuffle(bytearray(b'abcdefg')) == bytearray(b'afgebcd')
# def test_shuffle_dict():
# def test_shuffle_set():
# def test_shuffle_frozenset():
# Other types to test: namedtuple? defaultdict? counter? collections abc subclasses?
# def test_shuffle_noniterable():
| 22.413043 | 84 | 0.681862 |
from campy.datastructures.shuffle import shuffle
import random
def test_shuffle_list():
random.seed(41)
assert shuffle([3, 1, 4, 1, 5, 9]) == [5, 9, 3, 1, 4, 1]
def test_shuffle_tuple():
random.seed(41)
assert shuffle((3, 1, 4, 1, 5, 9)) == (5, 9, 3, 1, 4, 1)
def test_shuffle_string():
random.seed(41)
assert shuffle('abcdefg') == 'afgebcd'
def test_shuffle_bytes():
random.seed(41)
assert shuffle(b'abcdefg') == b'afgebcd'
def test_shuffle_bytearray():
random.seed(41)
assert shuffle(bytearray(b'abcdefg')) == bytearray(b'afgebcd')
| true | true |
1c470fa24ed63d9d3230ed00e5a2d1c9f01fe440 | 140 | py | Python | demos/examples/python_functions.py | pyxll/pylondon-2019 | c00c5ba52807c8d47ad84ffd4c64e1937fe69e98 | [
"MIT"
] | 8 | 2019-04-28T08:48:30.000Z | 2020-06-30T09:32:47.000Z | demos/examples/python_functions.py | pyxll/pylondon-2019 | c00c5ba52807c8d47ad84ffd4c64e1937fe69e98 | [
"MIT"
] | null | null | null | demos/examples/python_functions.py | pyxll/pylondon-2019 | c00c5ba52807c8d47ad84ffd4c64e1937fe69e98 | [
"MIT"
] | 1 | 2019-05-30T08:26:52.000Z | 2019-05-30T08:26:52.000Z | """
Example code showing how to declare a Python function.
"""
from pyxll import xl_func
@xl_func
def simple_test(a, b):
return a + b
| 14 | 54 | 0.7 | from pyxll import xl_func
@xl_func
def simple_test(a, b):
return a + b
| true | true |
1c470fc85b3e9b810c05e6e2be1bdbafde9adc7a | 7,050 | py | Python | qiskit/pulse/cmd_def.py | chowington/qiskit-terra | a782c64c736fedd6a541bb45dbf89737a52b7c39 | [
"Apache-2.0"
] | null | null | null | qiskit/pulse/cmd_def.py | chowington/qiskit-terra | a782c64c736fedd6a541bb45dbf89737a52b7c39 | [
"Apache-2.0"
] | null | null | null | qiskit/pulse/cmd_def.py | chowington/qiskit-terra | a782c64c736fedd6a541bb45dbf89737a52b7c39 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Command definition module. Relates circuit gates to pulse commands.
"""
from typing import List, Tuple, Iterable, Union, Dict
from qiskit.qobj import PulseQobjInstruction
from qiskit.qobj.converters import QobjToInstructionConverter
from .commands import SamplePulse
from .exceptions import PulseError
from .schedule import Schedule, ParameterizedSchedule
# pylint: disable=missing-return-doc
def _to_qubit_tuple(qubit_tuple: Union[int, Iterable[int]]) -> Tuple[int]:
"""Convert argument to tuple.
Args:
qubit_tuple: Qubits to enforce as tuple.
Raises:
PulseError: If qubits are not integers
"""
try:
qubit_tuple = tuple(qubit_tuple)
except TypeError:
qubit_tuple = (qubit_tuple,)
if not all(isinstance(i, int) for i in qubit_tuple):
raise PulseError("All qubits must be integers.")
return qubit_tuple
class CmdDef:
"""Command definition class. Relates `Gate`s to `Schedule`s."""
def __init__(self, schedules: Dict = None):
"""Create command definition from backend.
Args:
schedules: Keys are tuples of (cmd_name, *qubits) and values are
`Schedule` or `ParameterizedSchedule`
"""
self._cmd_dict = {}
if schedules:
for key, schedule in schedules.items():
self.add(key[0], key[1:], schedule)
@classmethod
def from_defaults(cls, flat_cmd_def: List[PulseQobjInstruction],
pulse_library: Dict[str, SamplePulse]) -> 'CmdDef':
"""Create command definition from backend defaults output.
Args:
flat_cmd_def: Command definition list returned by backend
pulse_library: Dictionary of `SamplePulse`s
"""
converter = QobjToInstructionConverter(pulse_library, buffer=0)
cmd_def = cls()
for cmd in flat_cmd_def:
qubits = cmd.qubits
name = cmd.name
instructions = []
for instr in cmd.sequence:
instructions.append(converter(instr))
cmd_def.add(name, qubits, ParameterizedSchedule(*instructions, name=name))
return cmd_def
def add(self, cmd_name: str, qubits: Union[int, Iterable[int]],
schedule: Union[ParameterizedSchedule, Schedule]):
"""Add a command to the `CommandDefinition`
Args:
cmd_name: Name of the command
qubits: Qubits command applies to
schedule: Schedule to be added
"""
qubits = _to_qubit_tuple(qubits)
cmd_dict = self._cmd_dict.setdefault(cmd_name, {})
if isinstance(schedule, Schedule):
schedule = ParameterizedSchedule(schedule, name=schedule.name)
cmd_dict[qubits] = schedule
def has(self, cmd_name: str, qubits: Union[int, Iterable[int]]) -> bool:
"""Has command of name with qubits.
Args:
cmd_name: Name of the command
qubits: Ordered list of qubits command applies to
"""
qubits = _to_qubit_tuple(qubits)
if cmd_name in self._cmd_dict:
if qubits in self._cmd_dict[cmd_name]:
return True
return False
def get(self, cmd_name: str, qubits: Union[int, Iterable[int]],
*params: List[Union[int, float, complex]],
**kwparams: Dict[str, Union[int, float, complex]]) -> Schedule:
"""Get command from command definition.
Args:
cmd_name: Name of the command
qubits: Ordered list of qubits command applies to
*params: Command parameters to be used to generate schedule
**kwparams: Keyworded command parameters to be used to generate schedule
Raises:
PulseError: If command for qubits is not available
"""
qubits = _to_qubit_tuple(qubits)
if self.has(cmd_name, qubits):
schedule = self._cmd_dict[cmd_name][qubits]
if isinstance(schedule, ParameterizedSchedule):
return schedule.bind_parameters(*params, **kwparams)
return schedule.flatten()
else:
raise PulseError('Command {0} for qubits {1} is not present '
'in CmdDef'.format(cmd_name, qubits))
def get_parameters(self, cmd_name: str, qubits: Union[int, Iterable[int]]) -> Tuple[str]:
"""Get command parameters from command definition.
Args:
cmd_name: Name of the command
qubits: Ordered list of qubits command applies to
Raises:
PulseError: If command for qubits is not available
"""
qubits = _to_qubit_tuple(qubits)
if self.has(cmd_name, qubits):
schedule = self._cmd_dict[cmd_name][qubits]
return schedule.parameters
else:
raise PulseError('Command {0} for qubits {1} is not present '
'in CmdDef'.format(cmd_name, qubits))
def pop(self, cmd_name: str, qubits: Union[int, Iterable[int]],
*params: List[Union[int, float, complex]],
**kwparams: Dict[str, Union[int, float, complex]]) -> Schedule:
"""Pop command from command definition.
Args:
cmd_name: Name of the command
qubits: Ordered list of qubits command applies to
*params: Command parameters to be used to generate schedule
**kwparams: Keyworded command parameters to be used to generate schedule
Raises:
PulseError: If command for qubits is not available
"""
qubits = _to_qubit_tuple(qubits)
if self.has(cmd_name, qubits):
cmd_dict = self._cmd_dict[cmd_name]
schedule = cmd_dict.pop(qubits)
if isinstance(schedule, ParameterizedSchedule):
return schedule.bind_parameters(*params, **kwparams)
return schedule
else:
raise PulseError('Command {0} for qubits {1} is not present '
'in CmdDef'.format(cmd_name, qubits))
def cmds(self) -> List[str]:
"""Return all command names available in CmdDef."""
return list(self._cmd_dict.keys())
def cmd_qubits(self, cmd_name: str) -> List[Tuple[int]]:
"""Get all qubit orderings this command exists for."""
if cmd_name in self._cmd_dict:
return list(sorted(self._cmd_dict[cmd_name].keys()))
return []
def __repr__(self):
return repr(self._cmd_dict)
| 34.558824 | 93 | 0.623546 |
from typing import List, Tuple, Iterable, Union, Dict
from qiskit.qobj import PulseQobjInstruction
from qiskit.qobj.converters import QobjToInstructionConverter
from .commands import SamplePulse
from .exceptions import PulseError
from .schedule import Schedule, ParameterizedSchedule
def _to_qubit_tuple(qubit_tuple: Union[int, Iterable[int]]) -> Tuple[int]:
try:
qubit_tuple = tuple(qubit_tuple)
except TypeError:
qubit_tuple = (qubit_tuple,)
if not all(isinstance(i, int) for i in qubit_tuple):
raise PulseError("All qubits must be integers.")
return qubit_tuple
class CmdDef:
def __init__(self, schedules: Dict = None):
self._cmd_dict = {}
if schedules:
for key, schedule in schedules.items():
self.add(key[0], key[1:], schedule)
@classmethod
def from_defaults(cls, flat_cmd_def: List[PulseQobjInstruction],
pulse_library: Dict[str, SamplePulse]) -> 'CmdDef':
converter = QobjToInstructionConverter(pulse_library, buffer=0)
cmd_def = cls()
for cmd in flat_cmd_def:
qubits = cmd.qubits
name = cmd.name
instructions = []
for instr in cmd.sequence:
instructions.append(converter(instr))
cmd_def.add(name, qubits, ParameterizedSchedule(*instructions, name=name))
return cmd_def
def add(self, cmd_name: str, qubits: Union[int, Iterable[int]],
schedule: Union[ParameterizedSchedule, Schedule]):
qubits = _to_qubit_tuple(qubits)
cmd_dict = self._cmd_dict.setdefault(cmd_name, {})
if isinstance(schedule, Schedule):
schedule = ParameterizedSchedule(schedule, name=schedule.name)
cmd_dict[qubits] = schedule
def has(self, cmd_name: str, qubits: Union[int, Iterable[int]]) -> bool:
qubits = _to_qubit_tuple(qubits)
if cmd_name in self._cmd_dict:
if qubits in self._cmd_dict[cmd_name]:
return True
return False
def get(self, cmd_name: str, qubits: Union[int, Iterable[int]],
*params: List[Union[int, float, complex]],
**kwparams: Dict[str, Union[int, float, complex]]) -> Schedule:
qubits = _to_qubit_tuple(qubits)
if self.has(cmd_name, qubits):
schedule = self._cmd_dict[cmd_name][qubits]
if isinstance(schedule, ParameterizedSchedule):
return schedule.bind_parameters(*params, **kwparams)
return schedule.flatten()
else:
raise PulseError('Command {0} for qubits {1} is not present '
'in CmdDef'.format(cmd_name, qubits))
def get_parameters(self, cmd_name: str, qubits: Union[int, Iterable[int]]) -> Tuple[str]:
qubits = _to_qubit_tuple(qubits)
if self.has(cmd_name, qubits):
schedule = self._cmd_dict[cmd_name][qubits]
return schedule.parameters
else:
raise PulseError('Command {0} for qubits {1} is not present '
'in CmdDef'.format(cmd_name, qubits))
def pop(self, cmd_name: str, qubits: Union[int, Iterable[int]],
*params: List[Union[int, float, complex]],
**kwparams: Dict[str, Union[int, float, complex]]) -> Schedule:
qubits = _to_qubit_tuple(qubits)
if self.has(cmd_name, qubits):
cmd_dict = self._cmd_dict[cmd_name]
schedule = cmd_dict.pop(qubits)
if isinstance(schedule, ParameterizedSchedule):
return schedule.bind_parameters(*params, **kwparams)
return schedule
else:
raise PulseError('Command {0} for qubits {1} is not present '
'in CmdDef'.format(cmd_name, qubits))
def cmds(self) -> List[str]:
return list(self._cmd_dict.keys())
def cmd_qubits(self, cmd_name: str) -> List[Tuple[int]]:
if cmd_name in self._cmd_dict:
return list(sorted(self._cmd_dict[cmd_name].keys()))
return []
def __repr__(self):
return repr(self._cmd_dict)
| true | true |
1c4710485744a43033c4782f403ded172a09f64c | 5,256 | py | Python | pysnmp/EPON-EOC-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/EPON-EOC-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/EPON-EOC-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module EPON-EOC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EPON-EOC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:50:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
TimeTicks, Gauge32, ObjectIdentity, NotificationType, MibIdentifier, ModuleIdentity, IpAddress, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Unsigned32, Counter32, Integer32, iso, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Gauge32", "ObjectIdentity", "NotificationType", "MibIdentifier", "ModuleIdentity", "IpAddress", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Unsigned32", "Counter32", "Integer32", "iso", "enterprises")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
eponeoc = ModuleIdentity((1, 3, 6, 1, 4, 1, 34592))
if mibBuilder.loadTexts: eponeoc.setLastUpdated('201005271056Z')
if mibBuilder.loadTexts: eponeoc.setOrganization('epon eoc factory.')
class OperSwitch(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("enable", 1), ("disable", 2))
class DeviceStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))
namedValues = NamedValues(("notPresent", 1), ("offline", 2), ("online", 3), ("normal", 4), ("abnormal", 5))
class DataDirection(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("upstream", 1), ("downstream", 2))
class DeviceOperation(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(2, 3, 4, 5, 6))
namedValues = NamedValues(("reset", 2), ("default", 3), ("saveConfig", 4), ("restore", 5), ("delete", 6))
class LedStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("on", 1), ("off", 2), ("blink", 3))
class DeviceType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(16842752, 16843009, 16843265, 16843521, 16909057, 17105153, 17105409, 17105665, 16974081, 16974082, 16974083, 16974084, 16974085, 16974086, 16974087, 16974088, 16974095, 16974094, 16974089, 16974090, 16974091, 16974092, 16974337, 16974338, 16974593, 16974594, 16974849, 17040129, 16974850, 17039617, 825241960, 825307496, 825307757, 825242728, 825308258, 825308269, 858797160))
namedValues = NamedValues(("EPON", 16842752), ("CHASSIS", 16843009), ("OLT", 16843265), ("PON", 16843521), ("PON", 16909057), ("EPON-1U", 17105153), ("OLT", 17105409), ("PON", 17105665), ("ONU4D-B", 16974081), ("ONU4D-B", 16974082), ("ONU4D-B", 16974083), ("ONU8D-B", 16974084), ("ONU4D", 16974085), ("ONU1D", 16974086), ("ONU1D-G", 16974087), ("ONU2D-G", 16974088), ("ONU2D-GM", 16974095), ("ONU4D-GM", 16974094), ("ONU4D-P", 16974089), ("ONU3D-M", 16974090), ("ONU4D", 16974091), ("ONU2D-M", 16974092), ("ONU4D2P", 16974337), ("ONU4D2P-P", 16974338), ("ONU4D1R", 16974593), ("ONU4D1R-P", 16974594), ("ONU4D2P1R", 16974849), ("ONU4D2P1R", 17040129), ("ONU4D2P1R-P", 16974850), ("ONU24D", 17039617), ("ONU1FE", 825241960), ("ONU1GE", 825307496), ("ONU2GE", 825307757), ("ONU4FE", 825242728), ("ONU4GE", 825308258), ("ONU4GE", 825308269), ("ONU4FE1RF", 858797160))
ipProduct = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1))
if mibBuilder.loadTexts: ipProduct.setStatus('current')
mediaConverter = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1, 1))
if mibBuilder.loadTexts: mediaConverter.setStatus('current')
switch = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1, 2))
if mibBuilder.loadTexts: switch.setStatus('current')
epon = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1, 3))
if mibBuilder.loadTexts: epon.setStatus('current')
eoc = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1, 4))
if mibBuilder.loadTexts: eoc.setStatus('current')
mibBuilder.exportSymbols("EPON-EOC-MIB", epon=epon, DataDirection=DataDirection, DeviceType=DeviceType, eponeoc=eponeoc, DeviceOperation=DeviceOperation, mediaConverter=mediaConverter, PYSNMP_MODULE_ID=eponeoc, DeviceStatus=DeviceStatus, switch=switch, eoc=eoc, ipProduct=ipProduct, LedStatus=LedStatus, OperSwitch=OperSwitch)
| 90.62069 | 867 | 0.737823 |
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
TimeTicks, Gauge32, ObjectIdentity, NotificationType, MibIdentifier, ModuleIdentity, IpAddress, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Unsigned32, Counter32, Integer32, iso, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Gauge32", "ObjectIdentity", "NotificationType", "MibIdentifier", "ModuleIdentity", "IpAddress", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Unsigned32", "Counter32", "Integer32", "iso", "enterprises")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
eponeoc = ModuleIdentity((1, 3, 6, 1, 4, 1, 34592))
if mibBuilder.loadTexts: eponeoc.setLastUpdated('201005271056Z')
if mibBuilder.loadTexts: eponeoc.setOrganization('epon eoc factory.')
class OperSwitch(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("enable", 1), ("disable", 2))
class DeviceStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))
namedValues = NamedValues(("notPresent", 1), ("offline", 2), ("online", 3), ("normal", 4), ("abnormal", 5))
class DataDirection(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("upstream", 1), ("downstream", 2))
class DeviceOperation(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(2, 3, 4, 5, 6))
namedValues = NamedValues(("reset", 2), ("default", 3), ("saveConfig", 4), ("restore", 5), ("delete", 6))
class LedStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("on", 1), ("off", 2), ("blink", 3))
class DeviceType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(16842752, 16843009, 16843265, 16843521, 16909057, 17105153, 17105409, 17105665, 16974081, 16974082, 16974083, 16974084, 16974085, 16974086, 16974087, 16974088, 16974095, 16974094, 16974089, 16974090, 16974091, 16974092, 16974337, 16974338, 16974593, 16974594, 16974849, 17040129, 16974850, 17039617, 825241960, 825307496, 825307757, 825242728, 825308258, 825308269, 858797160))
namedValues = NamedValues(("EPON", 16842752), ("CHASSIS", 16843009), ("OLT", 16843265), ("PON", 16843521), ("PON", 16909057), ("EPON-1U", 17105153), ("OLT", 17105409), ("PON", 17105665), ("ONU4D-B", 16974081), ("ONU4D-B", 16974082), ("ONU4D-B", 16974083), ("ONU8D-B", 16974084), ("ONU4D", 16974085), ("ONU1D", 16974086), ("ONU1D-G", 16974087), ("ONU2D-G", 16974088), ("ONU2D-GM", 16974095), ("ONU4D-GM", 16974094), ("ONU4D-P", 16974089), ("ONU3D-M", 16974090), ("ONU4D", 16974091), ("ONU2D-M", 16974092), ("ONU4D2P", 16974337), ("ONU4D2P-P", 16974338), ("ONU4D1R", 16974593), ("ONU4D1R-P", 16974594), ("ONU4D2P1R", 16974849), ("ONU4D2P1R", 17040129), ("ONU4D2P1R-P", 16974850), ("ONU24D", 17039617), ("ONU1FE", 825241960), ("ONU1GE", 825307496), ("ONU2GE", 825307757), ("ONU4FE", 825242728), ("ONU4GE", 825308258), ("ONU4GE", 825308269), ("ONU4FE1RF", 858797160))
ipProduct = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1))
if mibBuilder.loadTexts: ipProduct.setStatus('current')
mediaConverter = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1, 1))
if mibBuilder.loadTexts: mediaConverter.setStatus('current')
switch = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1, 2))
if mibBuilder.loadTexts: switch.setStatus('current')
epon = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1, 3))
if mibBuilder.loadTexts: epon.setStatus('current')
eoc = ObjectIdentity((1, 3, 6, 1, 4, 1, 34592, 1, 4))
if mibBuilder.loadTexts: eoc.setStatus('current')
mibBuilder.exportSymbols("EPON-EOC-MIB", epon=epon, DataDirection=DataDirection, DeviceType=DeviceType, eponeoc=eponeoc, DeviceOperation=DeviceOperation, mediaConverter=mediaConverter, PYSNMP_MODULE_ID=eponeoc, DeviceStatus=DeviceStatus, switch=switch, eoc=eoc, ipProduct=ipProduct, LedStatus=LedStatus, OperSwitch=OperSwitch)
| true | true |
1c471079d062c1c61307f4ded527f7918ba17b40 | 2,309 | py | Python | tools/pw_ener_vol.py | minyez/mykit | 911413120c081be2cfcaef06d62dc40b2abd2747 | [
"MIT"
] | 4 | 2019-01-02T09:17:54.000Z | 2019-12-26T07:15:59.000Z | tools/pw_ener_vol.py | minyez/mykit | 911413120c081be2cfcaef06d62dc40b2abd2747 | [
"MIT"
] | 6 | 2019-03-06T03:16:12.000Z | 2019-03-14T14:36:01.000Z | tools/pw_ener_vol.py | minyez/mykit | 911413120c081be2cfcaef06d62dc40b2abd2747 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from argparse import ArgumentParser
from pw_anal_utils import w2k_get_casename
import subprocess as sp
import os,sys
description = '''
Read the observable-volume data from an optimize.job execution.
SCF data are supposed to save in a directory named as claimed in the optimize.job script, i.e. save_lapw.
'''
obs_list = ['ENE','GAP','VOL','FER',\
'LAT1','LAT2','LAT3']
loc = [ 9, 6, 7, 10,\
5 , 6 , 7 ]
parser = ArgumentParser(description=description)
parser.add_argument("-o", dest="obs", help="the observable to monitor. Available: %s" % ','.join(obs_list),default="ENE")
parser.add_argument("-D", dest="debug", help="debug mode",action='store_true')
parser.add_argument("-p", dest="save", help="plot data (fitting BM-EOS)",action='store_true')
opts = parser.parse_args()
obs = opts.obs
if not obs in obs_list:
print "Unsupported observable monitor. Exit"
sys.exit(1)
ifile = 'optimize.job'
ofile = 'Ener_Vol'
struct_flag = False
obj_struct = [ ]
casename = w2k_get_casename()
if opts.debug: print casename
with open(ifile,'r') as f:
lines = f.readlines()
for line in lines:
words = line.split()
if len(words) == 0:
continue
if words[0] == ')':
struct_flag = False
if struct_flag:
obj_struct.append(words[0])
if words[0] == 'foreach':
struct_flag = True
if words[0] == 'save_lapw':
dirname = words[words.index('-d')+1]
for x in xrange(len(obj_struct)):
obj_struct[x] = obj_struct[x] + dirname[4:]
if opts.debug: print obj_struct
vol_data = []
obs_data = []
for struct in obj_struct:
try:
os.chdir(struct)
except:
continue
obs1 = sp.check_output("awk '/:%s/ {print $%i}' %s.scf | tail -1" % (obs,loc[obs_list.index(obs)],casename),shell=True).strip()
vol1 = sp.check_output("awk '/:%s/ {print $%i}' %s.scf | tail -1" % ('VOL',loc[obs_list.index('VOL')],casename),shell=True).strip()
vol_data.append(vol1)
obs_data.append(obs1)
if opts.debug: print vol1,obs1
os.chdir('..')
with open(ofile,'w') as fout:
fout.write("# Vol %s\n" %obs)
for i in xrange(len(vol_data)):
fout.write("%3i %s %s\n" % (i+1,vol_data[i],obs_data[i]))
| 29.227848 | 135 | 0.620615 |
from argparse import ArgumentParser
from pw_anal_utils import w2k_get_casename
import subprocess as sp
import os,sys
description = '''
Read the observable-volume data from an optimize.job execution.
SCF data are supposed to save in a directory named as claimed in the optimize.job script, i.e. save_lapw.
'''
obs_list = ['ENE','GAP','VOL','FER',\
'LAT1','LAT2','LAT3']
loc = [ 9, 6, 7, 10,\
5 , 6 , 7 ]
parser = ArgumentParser(description=description)
parser.add_argument("-o", dest="obs", help="the observable to monitor. Available: %s" % ','.join(obs_list),default="ENE")
parser.add_argument("-D", dest="debug", help="debug mode",action='store_true')
parser.add_argument("-p", dest="save", help="plot data (fitting BM-EOS)",action='store_true')
opts = parser.parse_args()
obs = opts.obs
if not obs in obs_list:
print "Unsupported observable monitor. Exit"
sys.exit(1)
ifile = 'optimize.job'
ofile = 'Ener_Vol'
struct_flag = False
obj_struct = [ ]
casename = w2k_get_casename()
if opts.debug: print casename
with open(ifile,'r') as f:
lines = f.readlines()
for line in lines:
words = line.split()
if len(words) == 0:
continue
if words[0] == ')':
struct_flag = False
if struct_flag:
obj_struct.append(words[0])
if words[0] == 'foreach':
struct_flag = True
if words[0] == 'save_lapw':
dirname = words[words.index('-d')+1]
for x in xrange(len(obj_struct)):
obj_struct[x] = obj_struct[x] + dirname[4:]
if opts.debug: print obj_struct
vol_data = []
obs_data = []
for struct in obj_struct:
try:
os.chdir(struct)
except:
continue
obs1 = sp.check_output("awk '/:%s/ {print $%i}' %s.scf | tail -1" % (obs,loc[obs_list.index(obs)],casename),shell=True).strip()
vol1 = sp.check_output("awk '/:%s/ {print $%i}' %s.scf | tail -1" % ('VOL',loc[obs_list.index('VOL')],casename),shell=True).strip()
vol_data.append(vol1)
obs_data.append(obs1)
if opts.debug: print vol1,obs1
os.chdir('..')
with open(ofile,'w') as fout:
fout.write("# Vol %s\n" %obs)
for i in xrange(len(vol_data)):
fout.write("%3i %s %s\n" % (i+1,vol_data[i],obs_data[i]))
| false | true |
1c4710f85890e97c5496e0643181003b678c7b0b | 1,085 | py | Python | longitude/samples/config.py | Rovaro/Longitude | b17b40a7b19edb10c62238ea20d136a3a8147f13 | [
"MIT"
] | 1 | 2020-11-06T11:12:42.000Z | 2020-11-06T11:12:42.000Z | longitude/samples/config.py | Rovaro/Longitude | b17b40a7b19edb10c62238ea20d136a3a8147f13 | [
"MIT"
] | 22 | 2017-11-20T21:18:55.000Z | 2021-07-06T10:22:14.000Z | longitude/samples/config.py | Rovaro/Longitude | b17b40a7b19edb10c62238ea20d136a3a8147f13 | [
"MIT"
] | 4 | 2018-03-22T08:38:03.000Z | 2020-06-14T04:29:15.000Z | """It's a good practice to put all config loading in the same file.
The `environs` library does a good job getting environment variables,
and it's quite straight forward:
@see https://pypi.org/project/environs/
However, if you ever need to change the environment vars by let's say,
a .conf file, or a database-stored config, or whatever, this centralized
approach allows you to change the whole config loading process by only
editing this file :)
As a little example, this is the config object shared by all sample scripts
in this folder:
"""
from environs import Env
env = Env()
config = {
'carto_user': env('CARTO_USER'),
'carto_api_key': env('CARTO_API_KEY'),
'pg_user': env('PG_USER'),
'pg_password': env('PG_PASSWORD'),
'debug': env.bool('DEBUG', False),
'oauth': {
'client_id': env('OAUTH_CLIENT_ID'),
'client_secret': env('OAUTH_CLIENT_SECRET'),
'base_url': env('OAUTH_BASE_URL'),
'scope': env('OAUTH_SCOPE', 'offline'),
'pem_file': env('SSL_PEM_FILE'),
'key_file': env('SSL_KEY_FILE')
}
}
| 29.324324 | 75 | 0.677419 |
from environs import Env
env = Env()
config = {
'carto_user': env('CARTO_USER'),
'carto_api_key': env('CARTO_API_KEY'),
'pg_user': env('PG_USER'),
'pg_password': env('PG_PASSWORD'),
'debug': env.bool('DEBUG', False),
'oauth': {
'client_id': env('OAUTH_CLIENT_ID'),
'client_secret': env('OAUTH_CLIENT_SECRET'),
'base_url': env('OAUTH_BASE_URL'),
'scope': env('OAUTH_SCOPE', 'offline'),
'pem_file': env('SSL_PEM_FILE'),
'key_file': env('SSL_KEY_FILE')
}
}
| true | true |
1c4711edcf7819cbbbc6c78acdca81a52af4983c | 1,393 | py | Python | common/xrd-ui-tests-python/tests/xroad_cs_user_logging/XroadCsUserLogging.py | nordic-institute/X-Road-tests | e030661a0ad8ceab74dd8122b751e88025a3474a | [
"MIT"
] | 1 | 2019-02-09T00:16:54.000Z | 2019-02-09T00:16:54.000Z | common/xrd-ui-tests-python/tests/xroad_cs_user_logging/XroadCsUserLogging.py | nordic-institute/X-Road-tests | e030661a0ad8ceab74dd8122b751e88025a3474a | [
"MIT"
] | 1 | 2018-06-06T08:33:32.000Z | 2018-06-06T08:33:32.000Z | common/xrd-ui-tests-python/tests/xroad_cs_user_logging/XroadCsUserLogging.py | nordic-institute/X-Road-tests | e030661a0ad8ceab74dd8122b751e88025a3474a | [
"MIT"
] | 3 | 2018-07-09T08:51:00.000Z | 2020-07-23T18:40:24.000Z | import unittest
from helpers import ssh_client
from main.maincontroller import MainController
from tests.xroad_cs_user_logging.cs_user_logging import check_logout, check_login
class XroadCsUserLogging(unittest.TestCase):
"""
CS_01 Log In to the Graphical User Interface
CS_02 Log Out of the Graphical User Interface
RIA URL: https://jira.ria.ee/browse/XT-302
RIA URL: https://jira.ria.ee/browse/XT-303
Depends on finishing other test(s):
Requires helper scenarios:
X-Road version: 6.16.0
"""
def __init__(self, methodName='test_cs_user_logging'):
unittest.TestCase.__init__(self, methodName)
def test_cs_user_logging(self):
main = MainController(self)
cs_host = main.config.get('cs.host')
cs_user = main.config.get('cs.user')
cs_pass = main.config.get('cs.pass')
cs_ssh_host = main.config.get('cs.ssh_host')
cs_ssh_user = main.config.get('cs.ssh_user')
cs_ssh_pass = main.config.get('cs.ssh_pass')
sshclient = ssh_client.SSHClient(cs_ssh_host, cs_ssh_user, cs_ssh_pass)
try:
main.reload_webdriver(cs_host, cs_user, cs_pass)
check_logout(main, sshclient, cs_user)
check_login(main, sshclient, cs_user, cs_pass)
except:
main.save_exception_data()
raise
finally:
main.tearDown()
| 34.825 | 81 | 0.674803 | import unittest
from helpers import ssh_client
from main.maincontroller import MainController
from tests.xroad_cs_user_logging.cs_user_logging import check_logout, check_login
class XroadCsUserLogging(unittest.TestCase):
def __init__(self, methodName='test_cs_user_logging'):
unittest.TestCase.__init__(self, methodName)
def test_cs_user_logging(self):
main = MainController(self)
cs_host = main.config.get('cs.host')
cs_user = main.config.get('cs.user')
cs_pass = main.config.get('cs.pass')
cs_ssh_host = main.config.get('cs.ssh_host')
cs_ssh_user = main.config.get('cs.ssh_user')
cs_ssh_pass = main.config.get('cs.ssh_pass')
sshclient = ssh_client.SSHClient(cs_ssh_host, cs_ssh_user, cs_ssh_pass)
try:
main.reload_webdriver(cs_host, cs_user, cs_pass)
check_logout(main, sshclient, cs_user)
check_login(main, sshclient, cs_user, cs_pass)
except:
main.save_exception_data()
raise
finally:
main.tearDown()
| true | true |
1c47124f0e6a2497f3ddc075da4e798d843d5388 | 1,143 | py | Python | src/wrapper/python/wolfssl/src/wolfssl/_memory.py | djp952/prebuilt-wolfssl | b3df82d34af6c71eef47bbd22931b049e13beac4 | [
"AML"
] | 1 | 2022-03-17T13:34:08.000Z | 2022-03-17T13:34:08.000Z | src/wrapper/python/wolfssl/src/wolfssl/_memory.py | djp952/prebuilt-wolfssl | b3df82d34af6c71eef47bbd22931b049e13beac4 | [
"AML"
] | null | null | null | src/wrapper/python/wolfssl/src/wolfssl/_memory.py | djp952/prebuilt-wolfssl | b3df82d34af6c71eef47bbd22931b049e13beac4 | [
"AML"
] | null | null | null | # -*- coding: utf-8 -*-
#
# _memory.py
#
# Copyright (C) 2006-2021 wolfSSL Inc.
#
# This file is part of wolfSSL.
#
# wolfSSL 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.
#
# wolfSSL 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
#/
#/
# pylint: disable=missing-docstring
try:
from wolfssl._ffi import ffi as _ffi
from wolfssl._ffi import lib as _lib
except ImportError:
pass
_DYNAMIC_TYPE_METHOD = 11
def _native_free(native_object, dynamic_type):
_lib.wolfSSL_Free(native_object, _ffi.NULL, dynamic_type)
| 30.891892 | 80 | 0.725284 |
try:
from wolfssl._ffi import ffi as _ffi
from wolfssl._ffi import lib as _lib
except ImportError:
pass
_DYNAMIC_TYPE_METHOD = 11
def _native_free(native_object, dynamic_type):
_lib.wolfSSL_Free(native_object, _ffi.NULL, dynamic_type)
| true | true |
1c47126541db2ea65702874849c90340f8a0942e | 34,556 | py | Python | scripts/competitiond.py | Levilian/codalab-worksheets | f01c72d1e78ef728859b57603eec59e3008a7205 | [
"Apache-2.0"
] | null | null | null | scripts/competitiond.py | Levilian/codalab-worksheets | f01c72d1e78ef728859b57603eec59e3008a7205 | [
"Apache-2.0"
] | null | null | null | scripts/competitiond.py | Levilian/codalab-worksheets | f01c72d1e78ef728859b57603eec59e3008a7205 | [
"Apache-2.0"
] | null | null | null | #!./venv/bin/python
"""
Competition leaderboard evaluation daemon.
1. Find bundles tagged with {submission_tag} and filter them.
2. Run the {predict} command with the submitted bundle to generate
predictions on the test set.
3. Tag the resulting test run bundle with {predict.tag}, untagging
any previous test run bundles for the same submitter.
4. Run {evaluate} command with the test run bundle.
5. Tag the resulting evaluation bundle with {evaluate.tag}, untagging
any previous evaluation bundles for the same submitter.
If in daemon mode, performs the above steps in a loop every
{refresh_period_seconds} seconds. Otherwise, just runs through them once.
All bundles created by this daemon are added to {log_worksheet_uuid}.
Each user will be limited to {max_submissions_per_period} every
{quota_period_seconds}, and {max_submissions_total} ever.
The following string substitutions will be made in the dependency specs:
{predict} => UUID of the resulting test run bundle
Config file keys:
"""
import argparse
import getpass
import json
import logging
import random
import re
import signal
import sys
import time
import traceback
from collections import defaultdict, namedtuple
from marshmallow import Schema, fields, ValidationError, missing
import yaml
sys.path.append('.')
from codalab.bundles import RunBundle
from codalab.common import NotFoundError, PermissionError
from codalab.client.json_api_client import JsonApiClient, JsonApiRelationship, JsonApiException
from codalab.lib.bundle_util import mimic_bundles
from codalab.lib.metadata_util import fill_missing_metadata
from codalab.lib.print_util import pretty_json
from codalab.lib.spec_util import UUID_STR
from codalab.model.tables import GROUP_OBJECT_PERMISSION_READ
from codalab.rest.schemas import BundleDependencySchema, validate_uuid
from codalab.server.auth import RestOAuthHandler
from codalabworker.bundle_state import State
logger = logging.getLogger(__name__)
class JsonApiClientWithRetry(JsonApiClient):
"""
JsonApiClient with a retry block around every request.
"""
def __init__(self, *args, **kwargs):
self.__num_retries = kwargs.pop('num_retries', 4)
self.__wait_seconds = kwargs.pop('wait_seconds', 1)
super(JsonApiClientWithRetry, self).__init__(*args, **kwargs)
def _make_request(self, *args, **kwargs):
num_retries_left = self.__num_retries
wait_seconds = self.__wait_seconds
while True:
try:
return super(JsonApiClientWithRetry, self)._make_request(*args, **kwargs)
except JsonApiException:
if num_retries_left > 0:
num_retries_left -= 1
logger.exception(
'Request failed, retrying in %s second(s)...', self.__wait_seconds
)
time.sleep(wait_seconds)
wait_seconds *= 5 # exponential backoff
wait_seconds += random.uniform(-1, 1) # small jitter
continue
else:
raise
class RunConfigSchema(Schema):
command = fields.String(required=True, metadata='bash command')
dependencies = fields.List(fields.Nested(BundleDependencySchema), required=True)
tag = fields.String(
missing='competition-evaluate', metadata='how to tag new evaluation bundles'
)
metadata = fields.Dict(missing={}, metadata='metadata keys for new evaluation bundles')
class MimicReplacementSchema(Schema):
old = fields.String(
validate=validate_uuid, required=True, metadata='uuid of bundle to swap out'
)
new = fields.String(validate=validate_uuid, required=True, metadata='uuid of bundle to swap in')
class MimicConfigSchema(Schema):
tag = fields.String(missing='competition-predict', metadata='how to tag new prediction bundles')
metadata = fields.Dict(missing={}, metadata='overwrite metadata keys in mimicked bundles')
depth = fields.Integer(
missing=10, metadata='how far up the dependency tree to look for replacements'
)
mimic = fields.List(fields.Nested(MimicReplacementSchema), required=True)
class ScoreSpecSchema(Schema):
name = fields.String(required=True, metadata='name of the score (for convenience)')
key = fields.String(
required=True,
metadata='target path of the score in the evaluate bundle (e.g. \"/results.json:f1_score\")',
)
class ConfigSchema(Schema):
max_submissions_per_period = fields.Integer(
missing=1, metadata='number of submissions allowed per user per quota period'
)
max_submissions_total = fields.Integer(
missing=10000, metadata='number of submissions allowed per user for eternity'
)
refresh_period_seconds = fields.Integer(
missing=60,
metadata='(for daemon mode) number of seconds to wait before checking for new submissions again',
)
max_leaderboard_size = fields.Integer(
missing=10000, metadata='maximum number of bundles you expect to have on the log worksheet'
)
quota_period_seconds = fields.Integer(
missing=24 * 60 * 60, metadata='window size for the user submission quotas in seconds'
)
count_failed_submissions = fields.Boolean(
missing=True, metadata='whether to count failed evaluations toward submission quotas'
)
make_predictions_public = fields.Boolean(
missing=False, metadata='whether to make newly-created prediction bundles publicly readable'
)
allow_orphans = fields.Boolean(
missing=True,
metadata='whether to keep leaderboard entries that no longer have corresponding submission bundles',
)
allow_multiple_models = fields.Boolean(
missing=False, metadata='whether to distinguish multiple models per user by bundle name'
)
host = fields.Url(
missing='https://worksheets.codalab.org',
metadata='address of the CodaLab instance to connect to',
)
username = fields.String(metadata='username for CodaLab account to use')
password = fields.String(metadata='password for CodaLab account to use')
submission_tag = fields.String(required=True, metadata='tag for searching for submissions')
log_worksheet_uuid = fields.String(
validate=validate_uuid, metadata='UUID of worksheet to create new bundles in'
)
predict = fields.Nested(MimicConfigSchema, required=True)
evaluate = fields.Nested(RunConfigSchema, required=True)
# Leaderboard sorted by the first key in this list
score_specs = fields.List(fields.Nested(ScoreSpecSchema), required=True)
# Gets passed directly to the output JSON
metadata = fields.Dict(
missing={}, metadata='additional metadata to include in the leaderboard file'
)
class AuthHelper(object):
REFRESH_BUFFER_SECONDS = 5 * 60
def __init__(self, host, username, password):
self.username = username
self.password = password
self.auth_handler = RestOAuthHandler(host)
self.grant = None
self.expires_at = None
def get_access_token(self):
if not self.grant or time.time() > self.expires_at - self.REFRESH_BUFFER_SECONDS:
self.grant = self.auth_handler.generate_token(
'credentials', self.username, self.password
)
if self.grant is None:
raise PermissionError('Invalid username or password.')
self.expires_at = time.time() + self.grant['expires_in']
return self.grant['access_token']
SubmissionKey = namedtuple('SubmissionKey', 'owner_id bundle_name')
class Competition(object):
"""
Internal data model:
description of bundles hold leaderboard submission metadata serialized as JSON
all prediction bundles are tagged with predict tag
only the latest evaluation bundle for each submitter is tagged with evaluate tag
the prediction bundles maintain the record of all submissions.
"""
def __init__(self, config_path, output_path, leaderboard_only):
self.config = self._load_config(config_path)
self.output_path = output_path
self.leaderboard_only = leaderboard_only
auth = AuthHelper(
self.config['host'],
self.config.get('username') or raw_input('Username: '),
self.config.get('password') or getpass.getpass('Password: '),
)
# Remove credentials from config to prevent them from being copied
# into the leaderboard file.
self.config.pop('username', None)
self.config.pop('password', None)
self.client = JsonApiClientWithRetry(self.config['host'], auth.get_access_token)
self.should_stop = False
@staticmethod
def _load_config(config_path):
with open(config_path, 'r') as fp:
config = yaml.safe_load(fp)
try:
config = ConfigSchema(strict=True).load(config).data
except ValidationError as e:
print >>sys.stderr, 'Invalid config file:', e
sys.exit(1)
return config
@staticmethod
def _get_competition_metadata(bundle):
"""
Load competition-specific metadata from a bundle dict.
Returns metadata dict, or None if no metadata found.
"""
try:
return json.loads(bundle['metadata']['description'])
except ValueError:
return None
def _clear_competition_metadata(self, bundle):
"""
Clears competition-specific metadata from a bundle on the server.
"""
bundle['metadata']['description'] = ''
self.client.update('bundles', {'id': bundle['id'], 'metadata': {'description': ''}})
def ensure_log_worksheet_private(self):
"""
Ensure that the leaderboard worksheet is private, so that all bundles
created on it are automatically private.
"""
if self.config['make_predictions_public']:
return
# Get public group info
public = self.client.fetch('groups', 'public')
# Set permissions
self.client.create(
'worksheet-permissions',
{
'group': JsonApiRelationship('groups', public['id']),
'worksheet': JsonApiRelationship('worksheets', self.config['log_worksheet_uuid']),
'permission': 0,
},
)
def _make_public_readable(self, bundle):
"""
Make the given bundle readable to the public.
"""
# Get public group info
public = self.client.fetch('groups', 'public')
# Set permissions
self.client.create(
'bundle-permissions',
{
'group': JsonApiRelationship('groups', public['id']),
'bundle': JsonApiRelationship('bundles', bundle['id']),
'permission': 1,
},
)
def _untag(self, bundles, tag):
"""
Remove the given `tag` from each of the bundles in `bundles`.
"""
self.client.update(
'bundles',
[
{
'id': b['id'],
'metadata': {'tags': [t for t in b['metadata']['tags'] if t != tag]},
}
for b in bundles
],
)
def _fetch_latest_submissions(self):
# Fetch all submissions
all_submissions = self.client.fetch(
'bundles',
params={
'keywords': [
'tags={submission_tag}'.format(**self.config),
'created=.sort-',
'.limit={max_leaderboard_size}'.format(**self.config),
],
'include': ['owner'],
},
)
# Drop all but the latest submission for each user
# (or for each model, as distinguished by the bundle name)
submissions = {}
for bundle in reversed(all_submissions):
owner_id = bundle['owner']['id']
created = bundle['metadata']['created']
# If multiple models are allowed for each user, subsect by submission bundle name as well
if self.config['allow_multiple_models']:
key = SubmissionKey(owner_id, bundle['metadata']['name'])
else:
key = SubmissionKey(owner_id, None)
if key not in submissions or created > submissions[key]['metadata']['created']:
submissions[key] = bundle
return submissions
def _fetch_submission_history(self):
# Fetch latest evaluation bundles
last_tests = self.client.fetch(
'bundles',
params={
'keywords': [
'.mine', # don't allow others to forge evaluations
'tags={evaluate[tag]}'.format(**self.config),
'.limit={max_leaderboard_size}'.format(**self.config),
]
},
)
# Collect data in preparation for computing submission counts
submission_times = defaultdict(
list
) # map from submitter_user_id -> UNIX timestamps of submissions, sorted
previous_submission_ids = set() # set of submission bundle uuids
for eval_bundle in last_tests:
submit_info = self._get_competition_metadata(eval_bundle)
if submit_info is None:
continue
timestamp = eval_bundle['metadata']['created']
previous_submission_ids.add(submit_info['submit_id'])
# Only count toward quota if not failed or configured to count failed submissions
# if predict_bundle['state'] != State.FAILED or self.config['count_failed_submissions']:
submission_times[submit_info['submitter_id']].append(timestamp)
# Compute submission counts
num_total_submissions = defaultdict(int)
num_period_submissions = defaultdict(int)
now = time.time()
period_start = now - self.config['quota_period_seconds']
for owner_id, timestamps in submission_times.items():
# Count the total number of submissions
num_total_submissions[owner_id] = len(timestamps)
# Count the number of submissions in the past 24 hours
num_period_submissions[owner_id] = sum(t > period_start for t in timestamps)
return previous_submission_ids, num_total_submissions, num_period_submissions
def _filter_submissions(
self, submissions, previous_submission_ids, num_total_submissions, num_period_submissions
):
# Drop submission if user has exceeded their quota
for key, bundle in submissions.items():
# Drop submission if we already ran it before
if bundle['id'] in previous_submission_ids:
logger.debug(
'Already mimicked last submission by ' '{owner[user_name]}.'.format(**bundle)
)
del submissions[key]
continue
if num_total_submissions[key.owner_id] >= self.config['max_submissions_total']:
logger.debug(
"{owner[user_name]} exceeded quota "
"({used}/{allowed} total submissions)".format(
used=num_total_submissions[key.owner_id],
allowed=self.config['max_submissions_total'],
**bundle
)
)
del submissions[key]
continue
if num_period_submissions[key.owner_id] >= self.config['max_submissions_per_period']:
logger.debug(
"{owner[user_name]} exceeded quota "
"({used}/{allowed} submissions per day)".format(
used=num_period_submissions[key.owner_id],
allowed=self.config['max_submissions_per_period'],
**bundle
)
)
del submissions[key]
continue
return submissions
def collect_submissions(self):
"""
Collect all valid submissions, along with the latest quota counts.
"""
logger.debug("Collecting latest submissions")
submissions = self._fetch_latest_submissions()
previous_submission_ids, num_total_submissions, num_period_submissions = (
self._fetch_submission_history()
)
submissions = self._filter_submissions(
submissions, previous_submission_ids, num_total_submissions, num_period_submissions
)
return submissions.values(), num_total_submissions, num_period_submissions
def run_prediction(self, submit_bundle):
"""
Given a bundle tagged for submission, try to mimic the bundle with the
evaluation data according to the prediction run specification.
Returns the mimicked prediction bundle. (If the mimic created multiple
bundles, then the one corresponding to the tagged submission bundle is
returned.)
Returns None if the submission does not meet requirements.
"""
predict_bundle_name = '{owner[user_name]}-{metadata[name]}-predict'.format(**submit_bundle)
predict_config = self.config['predict']
to_be_replaced = [spec['old'] for spec in predict_config['mimic']]
replacements = [spec['new'] for spec in predict_config['mimic']]
def find_mimicked(plan):
for old_info, new_info in plan:
if old_info['uuid'] == submit_bundle['uuid']:
return new_info
return None
metadata = {'tags': [predict_config['tag']]}
metadata.update(predict_config['metadata'])
mimic_args = {
'client': self.client,
'old_inputs': to_be_replaced,
'old_output': submit_bundle['uuid'],
'new_inputs': replacements,
'new_output_name': predict_bundle_name,
'worksheet_uuid': self.config['log_worksheet_uuid'],
'depth': predict_config['depth'],
'shadow': False,
'metadata_override': metadata,
'skip_prelude': True,
}
# Do dry run to check if the submission has the right dependencies.
# If the submission bundle is not mimicked (i.e. not in the mimic plan),
# that means that none of its ancestors are in the set of bundles that
# we are trying to replace.
if find_mimicked(mimic_bundles(dry_run=True, **mimic_args)) is None:
logger.info(
"Submission {uuid} by {owner[user_name]} is missing "
"expected dependencies.".format(**submit_bundle)
)
return None
# Actually perform the mimic now
predict_bundle = find_mimicked(mimic_bundles(dry_run=False, **mimic_args))
assert predict_bundle is not None, "Unexpected error: couldn't find mimicked bundle in plan"
return predict_bundle
def run_evaluation(self, submit_bundle, predict_bundle):
eval_bundle_name = '{owner[user_name]}-{metadata[name]}-results'.format(**submit_bundle)
# Untag any old evaluation run(s) for this submitter
old_evaluations = self.client.fetch(
'bundles',
params={
'keywords': [
'.mine', # don't allow others to forge evaluations
'tags={evaluate[tag]}'.format(**self.config),
'name=' + eval_bundle_name,
]
},
)
if old_evaluations:
self._untag(old_evaluations, self.config['evaluate']['tag'])
# Create evaluation runs on the predictions with leaderboard tag
# Build up metadata
metadata = {
'name': eval_bundle_name,
'tags': [self.config['evaluate']['tag']],
'description': json.dumps(
{
'submit_id': submit_bundle['id'],
'submitter_id': submit_bundle['owner']['id'],
'predict_id': predict_bundle['id'],
}
),
}
metadata.update(self.config['evaluate']['metadata'])
metadata = fill_missing_metadata(RunBundle, argparse.Namespace(), metadata)
# Substitute in the prediction bundle UUID where required
dependencies = []
for dep_spec in self.config['evaluate']['dependencies']:
dep = dep_spec.copy()
dep['parent_uuid'] = dep['parent_uuid'].format(predict=predict_bundle['uuid'])
dependencies.append(dep)
# Create the bundle
eval_bundle = self.client.create(
'bundles',
{
'bundle_type': 'run',
'command': self.config['evaluate']['command'],
'dependencies': dependencies,
'metadata': metadata,
},
params={'worksheet': self.config['log_worksheet_uuid']},
)
self._make_public_readable(eval_bundle)
return eval_bundle
@staticmethod
def _is_publicly_readable(bundle):
for perm in bundle['group_permissions']:
if perm['group_name'] == 'public':
return perm['permission'] >= GROUP_OBJECT_PERMISSION_READ
# No permissions on public group
return False
def _fetch_leaderboard(self):
"""
Fetches the evaluation bundles tagged for the leaderboard, along with
the corresponding submission bundles if they exist.
:return: (eval_bundles, eval2submit) where eval_bundles is a dict mapping
evaluation bundle ids to the evaluation bundles themselves, and
eval2submit is a dict mapping evaluation bundle id to the
original submission bundle. The id will not be a key in
eval2submit if a corresponding submission bundle does not exist.
"""
logger.debug('Fetching the leaderboard')
# Fetch bundles on current leaderboard
eval_bundles = self.client.fetch(
'bundles',
params={
'keywords': [
'.mine', # don't allow others to forge evaluations
'tags={evaluate[tag]}'.format(**self.config),
'.limit={max_leaderboard_size}'.format(**self.config),
]
},
)
eval_bundles = {b['id']: b for b in eval_bundles}
# Build map from submission bundle id => eval bundle
submit2eval = {}
for eval_id, eval_bundle in eval_bundles.items():
meta = self._get_competition_metadata(eval_bundle)
# Eval bundles that are missing competition metadata are simply
# skipped; code downstream must handle the case where eval2submit
# does not contain an entry for a given eval bundle
if meta is not None:
# Allow manual hiding
if meta.get('hide', False):
del eval_bundles[eval_id]
else:
submit2eval[meta['submit_id']] = eval_bundle
# Fetch the original submission bundles.
# A NotFoundError will be thrown if a bundle no longer exists.
# We will remove that submission from the leaderboard, and keep
# trying until there are no more deleted bundles.
logger.debug('Fetching corresponding original submission bundles')
while True:
if len(eval_bundles) == 0:
submit_bundles = {}
break
try:
uuids = submit2eval.keys()
submit_bundles = []
for start in range(0, len(uuids), 50):
end = start + 50
submit_bundles.extend(
self.client.fetch(
'bundles',
params={
'specs': uuids[start:end],
'worksheet': self.config['log_worksheet_uuid'],
'include': ['owner', 'group_permissions'],
},
)
)
break
except NotFoundError as e:
missing_submit_uuid = re.search(UUID_STR, e.message).group(0)
eval_uuid = submit2eval[missing_submit_uuid]['id']
# If a submission bundle (missing_uuid) has been deleted...
if self.config['allow_orphans']:
# Just clear the competition metadata on the eval bundle,
# thus removing the reference to the original submit bundle
logger.info("Clearing reference to deleted submission %s", missing_submit_uuid)
self._clear_competition_metadata(eval_bundles[eval_uuid])
pass
else:
# Untag and remove entry from the leaderboard entirely
logger.info("Removing submission %s", missing_submit_uuid)
self._untag([submit2eval[missing_submit_uuid]], self.config['evaluate']['tag'])
del eval_bundles[eval_uuid]
# Drop from list of submit bundles and try fetching batch again
del submit2eval[missing_submit_uuid]
continue
# Build map from eval bundle id => submission bundle
eval2submit = {}
for submit_bundle in submit_bundles:
eval_bundle = submit2eval[submit_bundle['id']]
eval2submit[eval_bundle['id']] = submit_bundle
return eval_bundles, eval2submit
def _fetch_scores(self, eval_bundles):
"""
Fetch scores from server.
Returns dict with (bundle_id, score_spec_name) as the key and the score
value as the value.
"""
# Extract score specs
scores = {}
queries = []
keys = []
for bundle in eval_bundles.itervalues():
if bundle['state'] == State.READY:
for spec in self.config['score_specs']:
queries.append((bundle['id'], spec['key'], None))
keys.append((bundle['id'], spec['name']))
else:
# All scores are None if the bundle failed
scores[bundle['id']] = {spec['name']: None for spec in self.config['score_specs']}
# Actually fetch score values
results = self.client.interpret_file_genpaths(queries)
for (bundle_id, spec_name), value in zip(keys, results):
if bundle_id not in scores:
scores[bundle_id] = {}
scores[bundle_id][spec_name] = value
return scores
def generate_leaderboard(self, num_total_submissions, num_period_submissions):
eval_bundles, eval2submit = self._fetch_leaderboard()
scores = self._fetch_scores(eval_bundles)
# Build leaderboard table
logger.debug('Fetching scores and building leaderboard table')
leaderboard = []
for eval_bundle in eval_bundles.itervalues():
meta = self._get_competition_metadata(eval_bundle)
if eval_bundle['id'] in eval2submit:
submit_bundle = eval2submit[eval_bundle['id']]
submission_info = {
# Can include any information we want from the submission
# within bounds of reason (since submitter may want to
# keep some of the metadata private).
'description': meta.get('description', None)
or submit_bundle['metadata']['description'], # Allow description override
'public': self._is_publicly_readable(submit_bundle),
'user_name': submit_bundle['owner']['user_name'],
'num_total_submissions': num_total_submissions[submit_bundle['owner']['id']],
'num_period_submissions': num_period_submissions[submit_bundle['owner']['id']],
'created': submit_bundle['metadata']['created'],
}
else:
# If there isn't a corresponding submit bundle, use some sane
# defaults based on just the eval bundle.
submission_info = {
'description': eval_bundle['metadata']['description'],
'public': None,
'user_name': None,
'num_total_submissions': 0,
'num_period_submissions': 0,
'created': eval_bundle['metadata']['created'],
}
leaderboard.append(
{
'bundle': eval_bundle,
'scores': scores[eval_bundle['id']],
'submission': submission_info,
}
)
# Sort by the scores, descending
leaderboard.sort(
key=lambda e: tuple(e['scores'][spec['name']] for spec in self.config['score_specs']),
reverse=True,
)
# Write table to JSON file along with other data
output = {'leaderboard': leaderboard, 'config': self.config, 'updated': time.time()}
with open(self.output_path, 'w') as fp:
fp.write(pretty_json(output))
logger.debug('Wrote leaderboard at {.output_path}'.format(self))
def run_once(self):
submissions, num_total_submissions, num_period_submissions = self.collect_submissions()
if not submissions:
logger.debug('No new submissions.')
if not self.leaderboard_only:
for submit_bundle in submissions:
logger.info(
"Mimicking submission for " "{owner[user_name]}".format(**submit_bundle)
)
predict_bundle = self.run_prediction(submit_bundle)
if predict_bundle is None:
logger.info(
"Aborting submission for " "{owner[user_name]}".format(**submit_bundle)
)
continue
self.run_evaluation(submit_bundle, predict_bundle)
logger.info(
"Finished mimicking submission for "
"{owner[user_name]}".format(**submit_bundle)
)
# Update local counts for the leaderboard
owner_id = submit_bundle['owner']['id']
num_total_submissions[owner_id] += 1
num_period_submissions[owner_id] += 1
self.generate_leaderboard(num_total_submissions, num_period_submissions)
def run(self):
self.ensure_log_worksheet_private()
logger.info('Starting competition daemon...')
while not self.should_stop:
try:
self.run_once()
except:
traceback.print_exc()
if self.should_stop:
break
time.sleep(self.config['refresh_period_seconds'])
def stop(self):
logger.info('Stopping competition daemon...')
self.should_stop = True
def generate_description():
def display_schema(schema, doc, indent, first_indent=None):
saved_indent = indent
if first_indent is not None:
indent = first_indent
for field_name, field in schema._declared_fields.items():
field_help = field.metadata.get('metadata', '')
field_class = field.__class__
if field_class is fields.Nested:
doc += indent + '%s:\n' % field_name
doc = display_schema(field.nested, doc, (indent + ' '))
elif field_class is fields.List:
doc += indent + '%s:\n' % field_name
doc = display_schema(
field.container.nested, doc, (indent + ' '), first_indent=(indent + ' - ')
)
doc += indent + ' - ...\n'
else:
field_type = field.__class__.__name__.lower()
if field.missing is missing and field.required:
doc += indent + '%s: %s, %s [required]\n' % (field_name, field_type, field_help)
elif field.missing is missing and not field.required:
doc += indent + '%s: %s, %s\n' % (field_name, field_type, field_help)
else:
doc += indent + '%s: %s, %s [default: %s]\n' % (
field_name,
field_type,
field_help,
json.dumps(field.missing).strip(),
)
indent = saved_indent
return doc
return display_schema(ConfigSchema, __doc__, ' ' * 4)
def main():
# Support all configs as command line arguments too
parser = argparse.ArgumentParser(
description=generate_description(), formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument('config_file', help='YAML/JSON file containing configurations.')
parser.add_argument('output_path', help='path to write JSON file containing leaderboard.')
parser.add_argument(
'-l',
'--leaderboard-only',
action='store_true',
help='Generate a new leaderboard but without creating any new runs.',
)
parser.add_argument(
'-d', '--daemon', action='store_true', help='Run as a daemon. (By default only runs once.)'
)
parser.add_argument('-v', '--verbose', action='store_true', help='Output verbose log messages.')
args = parser.parse_args()
logging.basicConfig(
format='[%(levelname)s] %(asctime)s: %(message)s',
level=(logging.DEBUG if args.verbose else logging.INFO),
)
comp = Competition(args.config_file, args.output_path, args.leaderboard_only)
if args.daemon:
# Catch interrupt signals so that eval loop doesn't get interrupted in the
# middle of a series of actions and leave things in an inconsistent state.
for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP]:
signal.signal(sig, lambda signup, frame: comp.stop())
comp.run()
else:
logger.info('Running batch competition evaluation')
comp.ensure_log_worksheet_private()
comp.run_once()
if __name__ == '__main__':
main()
| 40.943128 | 108 | 0.60059 |
import argparse
import getpass
import json
import logging
import random
import re
import signal
import sys
import time
import traceback
from collections import defaultdict, namedtuple
from marshmallow import Schema, fields, ValidationError, missing
import yaml
sys.path.append('.')
from codalab.bundles import RunBundle
from codalab.common import NotFoundError, PermissionError
from codalab.client.json_api_client import JsonApiClient, JsonApiRelationship, JsonApiException
from codalab.lib.bundle_util import mimic_bundles
from codalab.lib.metadata_util import fill_missing_metadata
from codalab.lib.print_util import pretty_json
from codalab.lib.spec_util import UUID_STR
from codalab.model.tables import GROUP_OBJECT_PERMISSION_READ
from codalab.rest.schemas import BundleDependencySchema, validate_uuid
from codalab.server.auth import RestOAuthHandler
from codalabworker.bundle_state import State
logger = logging.getLogger(__name__)
class JsonApiClientWithRetry(JsonApiClient):
def __init__(self, *args, **kwargs):
self.__num_retries = kwargs.pop('num_retries', 4)
self.__wait_seconds = kwargs.pop('wait_seconds', 1)
super(JsonApiClientWithRetry, self).__init__(*args, **kwargs)
def _make_request(self, *args, **kwargs):
num_retries_left = self.__num_retries
wait_seconds = self.__wait_seconds
while True:
try:
return super(JsonApiClientWithRetry, self)._make_request(*args, **kwargs)
except JsonApiException:
if num_retries_left > 0:
num_retries_left -= 1
logger.exception(
'Request failed, retrying in %s second(s)...', self.__wait_seconds
)
time.sleep(wait_seconds)
wait_seconds *= 5
wait_seconds += random.uniform(-1, 1)
continue
else:
raise
class RunConfigSchema(Schema):
command = fields.String(required=True, metadata='bash command')
dependencies = fields.List(fields.Nested(BundleDependencySchema), required=True)
tag = fields.String(
missing='competition-evaluate', metadata='how to tag new evaluation bundles'
)
metadata = fields.Dict(missing={}, metadata='metadata keys for new evaluation bundles')
class MimicReplacementSchema(Schema):
old = fields.String(
validate=validate_uuid, required=True, metadata='uuid of bundle to swap out'
)
new = fields.String(validate=validate_uuid, required=True, metadata='uuid of bundle to swap in')
class MimicConfigSchema(Schema):
tag = fields.String(missing='competition-predict', metadata='how to tag new prediction bundles')
metadata = fields.Dict(missing={}, metadata='overwrite metadata keys in mimicked bundles')
depth = fields.Integer(
missing=10, metadata='how far up the dependency tree to look for replacements'
)
mimic = fields.List(fields.Nested(MimicReplacementSchema), required=True)
class ScoreSpecSchema(Schema):
name = fields.String(required=True, metadata='name of the score (for convenience)')
key = fields.String(
required=True,
metadata='target path of the score in the evaluate bundle (e.g. \"/results.json:f1_score\")',
)
class ConfigSchema(Schema):
max_submissions_per_period = fields.Integer(
missing=1, metadata='number of submissions allowed per user per quota period'
)
max_submissions_total = fields.Integer(
missing=10000, metadata='number of submissions allowed per user for eternity'
)
refresh_period_seconds = fields.Integer(
missing=60,
metadata='(for daemon mode) number of seconds to wait before checking for new submissions again',
)
max_leaderboard_size = fields.Integer(
missing=10000, metadata='maximum number of bundles you expect to have on the log worksheet'
)
quota_period_seconds = fields.Integer(
missing=24 * 60 * 60, metadata='window size for the user submission quotas in seconds'
)
count_failed_submissions = fields.Boolean(
missing=True, metadata='whether to count failed evaluations toward submission quotas'
)
make_predictions_public = fields.Boolean(
missing=False, metadata='whether to make newly-created prediction bundles publicly readable'
)
allow_orphans = fields.Boolean(
missing=True,
metadata='whether to keep leaderboard entries that no longer have corresponding submission bundles',
)
allow_multiple_models = fields.Boolean(
missing=False, metadata='whether to distinguish multiple models per user by bundle name'
)
host = fields.Url(
missing='https://worksheets.codalab.org',
metadata='address of the CodaLab instance to connect to',
)
username = fields.String(metadata='username for CodaLab account to use')
password = fields.String(metadata='password for CodaLab account to use')
submission_tag = fields.String(required=True, metadata='tag for searching for submissions')
log_worksheet_uuid = fields.String(
validate=validate_uuid, metadata='UUID of worksheet to create new bundles in'
)
predict = fields.Nested(MimicConfigSchema, required=True)
evaluate = fields.Nested(RunConfigSchema, required=True)
score_specs = fields.List(fields.Nested(ScoreSpecSchema), required=True)
metadata = fields.Dict(
missing={}, metadata='additional metadata to include in the leaderboard file'
)
class AuthHelper(object):
REFRESH_BUFFER_SECONDS = 5 * 60
def __init__(self, host, username, password):
self.username = username
self.password = password
self.auth_handler = RestOAuthHandler(host)
self.grant = None
self.expires_at = None
def get_access_token(self):
if not self.grant or time.time() > self.expires_at - self.REFRESH_BUFFER_SECONDS:
self.grant = self.auth_handler.generate_token(
'credentials', self.username, self.password
)
if self.grant is None:
raise PermissionError('Invalid username or password.')
self.expires_at = time.time() + self.grant['expires_in']
return self.grant['access_token']
SubmissionKey = namedtuple('SubmissionKey', 'owner_id bundle_name')
class Competition(object):
def __init__(self, config_path, output_path, leaderboard_only):
self.config = self._load_config(config_path)
self.output_path = output_path
self.leaderboard_only = leaderboard_only
auth = AuthHelper(
self.config['host'],
self.config.get('username') or raw_input('Username: '),
self.config.get('password') or getpass.getpass('Password: '),
)
self.config.pop('username', None)
self.config.pop('password', None)
self.client = JsonApiClientWithRetry(self.config['host'], auth.get_access_token)
self.should_stop = False
@staticmethod
def _load_config(config_path):
with open(config_path, 'r') as fp:
config = yaml.safe_load(fp)
try:
config = ConfigSchema(strict=True).load(config).data
except ValidationError as e:
print >>sys.stderr, 'Invalid config file:', e
sys.exit(1)
return config
@staticmethod
def _get_competition_metadata(bundle):
try:
return json.loads(bundle['metadata']['description'])
except ValueError:
return None
def _clear_competition_metadata(self, bundle):
bundle['metadata']['description'] = ''
self.client.update('bundles', {'id': bundle['id'], 'metadata': {'description': ''}})
def ensure_log_worksheet_private(self):
if self.config['make_predictions_public']:
return
public = self.client.fetch('groups', 'public')
self.client.create(
'worksheet-permissions',
{
'group': JsonApiRelationship('groups', public['id']),
'worksheet': JsonApiRelationship('worksheets', self.config['log_worksheet_uuid']),
'permission': 0,
},
)
def _make_public_readable(self, bundle):
public = self.client.fetch('groups', 'public')
self.client.create(
'bundle-permissions',
{
'group': JsonApiRelationship('groups', public['id']),
'bundle': JsonApiRelationship('bundles', bundle['id']),
'permission': 1,
},
)
def _untag(self, bundles, tag):
self.client.update(
'bundles',
[
{
'id': b['id'],
'metadata': {'tags': [t for t in b['metadata']['tags'] if t != tag]},
}
for b in bundles
],
)
def _fetch_latest_submissions(self):
all_submissions = self.client.fetch(
'bundles',
params={
'keywords': [
'tags={submission_tag}'.format(**self.config),
'created=.sort-',
'.limit={max_leaderboard_size}'.format(**self.config),
],
'include': ['owner'],
},
)
submissions = {}
for bundle in reversed(all_submissions):
owner_id = bundle['owner']['id']
created = bundle['metadata']['created']
if self.config['allow_multiple_models']:
key = SubmissionKey(owner_id, bundle['metadata']['name'])
else:
key = SubmissionKey(owner_id, None)
if key not in submissions or created > submissions[key]['metadata']['created']:
submissions[key] = bundle
return submissions
def _fetch_submission_history(self):
last_tests = self.client.fetch(
'bundles',
params={
'keywords': [
'.mine',
'tags={evaluate[tag]}'.format(**self.config),
'.limit={max_leaderboard_size}'.format(**self.config),
]
},
)
# Collect data in preparation for computing submission counts
submission_times = defaultdict(
list
) # map from submitter_user_id -> UNIX timestamps of submissions, sorted
previous_submission_ids = set() # set of submission bundle uuids
for eval_bundle in last_tests:
submit_info = self._get_competition_metadata(eval_bundle)
if submit_info is None:
continue
timestamp = eval_bundle['metadata']['created']
previous_submission_ids.add(submit_info['submit_id'])
# Only count toward quota if not failed or configured to count failed submissions
# if predict_bundle['state'] != State.FAILED or self.config['count_failed_submissions']:
submission_times[submit_info['submitter_id']].append(timestamp)
# Compute submission counts
num_total_submissions = defaultdict(int)
num_period_submissions = defaultdict(int)
now = time.time()
period_start = now - self.config['quota_period_seconds']
for owner_id, timestamps in submission_times.items():
# Count the total number of submissions
num_total_submissions[owner_id] = len(timestamps)
# Count the number of submissions in the past 24 hours
num_period_submissions[owner_id] = sum(t > period_start for t in timestamps)
return previous_submission_ids, num_total_submissions, num_period_submissions
def _filter_submissions(
self, submissions, previous_submission_ids, num_total_submissions, num_period_submissions
):
# Drop submission if user has exceeded their quota
for key, bundle in submissions.items():
# Drop submission if we already ran it before
if bundle['id'] in previous_submission_ids:
logger.debug(
'Already mimicked last submission by ' '{owner[user_name]}.'.format(**bundle)
)
del submissions[key]
continue
if num_total_submissions[key.owner_id] >= self.config['max_submissions_total']:
logger.debug(
"{owner[user_name]} exceeded quota "
"({used}/{allowed} total submissions)".format(
used=num_total_submissions[key.owner_id],
allowed=self.config['max_submissions_total'],
**bundle
)
)
del submissions[key]
continue
if num_period_submissions[key.owner_id] >= self.config['max_submissions_per_period']:
logger.debug(
"{owner[user_name]} exceeded quota "
"({used}/{allowed} submissions per day)".format(
used=num_period_submissions[key.owner_id],
allowed=self.config['max_submissions_per_period'],
**bundle
)
)
del submissions[key]
continue
return submissions
def collect_submissions(self):
logger.debug("Collecting latest submissions")
submissions = self._fetch_latest_submissions()
previous_submission_ids, num_total_submissions, num_period_submissions = (
self._fetch_submission_history()
)
submissions = self._filter_submissions(
submissions, previous_submission_ids, num_total_submissions, num_period_submissions
)
return submissions.values(), num_total_submissions, num_period_submissions
def run_prediction(self, submit_bundle):
predict_bundle_name = '{owner[user_name]}-{metadata[name]}-predict'.format(**submit_bundle)
predict_config = self.config['predict']
to_be_replaced = [spec['old'] for spec in predict_config['mimic']]
replacements = [spec['new'] for spec in predict_config['mimic']]
def find_mimicked(plan):
for old_info, new_info in plan:
if old_info['uuid'] == submit_bundle['uuid']:
return new_info
return None
metadata = {'tags': [predict_config['tag']]}
metadata.update(predict_config['metadata'])
mimic_args = {
'client': self.client,
'old_inputs': to_be_replaced,
'old_output': submit_bundle['uuid'],
'new_inputs': replacements,
'new_output_name': predict_bundle_name,
'worksheet_uuid': self.config['log_worksheet_uuid'],
'depth': predict_config['depth'],
'shadow': False,
'metadata_override': metadata,
'skip_prelude': True,
}
# Do dry run to check if the submission has the right dependencies.
# If the submission bundle is not mimicked (i.e. not in the mimic plan),
# that means that none of its ancestors are in the set of bundles that
# we are trying to replace.
if find_mimicked(mimic_bundles(dry_run=True, **mimic_args)) is None:
logger.info(
"Submission {uuid} by {owner[user_name]} is missing "
"expected dependencies.".format(**submit_bundle)
)
return None
# Actually perform the mimic now
predict_bundle = find_mimicked(mimic_bundles(dry_run=False, **mimic_args))
assert predict_bundle is not None, "Unexpected error: couldn't find mimicked bundle in plan"
return predict_bundle
def run_evaluation(self, submit_bundle, predict_bundle):
eval_bundle_name = '{owner[user_name]}-{metadata[name]}-results'.format(**submit_bundle)
old_evaluations = self.client.fetch(
'bundles',
params={
'keywords': [
'.mine',
'tags={evaluate[tag]}'.format(**self.config),
'name=' + eval_bundle_name,
]
},
)
if old_evaluations:
self._untag(old_evaluations, self.config['evaluate']['tag'])
# Create evaluation runs on the predictions with leaderboard tag
# Build up metadata
metadata = {
'name': eval_bundle_name,
'tags': [self.config['evaluate']['tag']],
'description': json.dumps(
{
'submit_id': submit_bundle['id'],
'submitter_id': submit_bundle['owner']['id'],
'predict_id': predict_bundle['id'],
}
),
}
metadata.update(self.config['evaluate']['metadata'])
metadata = fill_missing_metadata(RunBundle, argparse.Namespace(), metadata)
# Substitute in the prediction bundle UUID where required
dependencies = []
for dep_spec in self.config['evaluate']['dependencies']:
dep = dep_spec.copy()
dep['parent_uuid'] = dep['parent_uuid'].format(predict=predict_bundle['uuid'])
dependencies.append(dep)
# Create the bundle
eval_bundle = self.client.create(
'bundles',
{
'bundle_type': 'run',
'command': self.config['evaluate']['command'],
'dependencies': dependencies,
'metadata': metadata,
},
params={'worksheet': self.config['log_worksheet_uuid']},
)
self._make_public_readable(eval_bundle)
return eval_bundle
@staticmethod
def _is_publicly_readable(bundle):
for perm in bundle['group_permissions']:
if perm['group_name'] == 'public':
return perm['permission'] >= GROUP_OBJECT_PERMISSION_READ
# No permissions on public group
return False
def _fetch_leaderboard(self):
logger.debug('Fetching the leaderboard')
# Fetch bundles on current leaderboard
eval_bundles = self.client.fetch(
'bundles',
params={
'keywords': [
'.mine', # don't allow others to forge evaluations
'tags={evaluate[tag]}'.format(**self.config),
'.limit={max_leaderboard_size}'.format(**self.config),
]
},
)
eval_bundles = {b['id']: b for b in eval_bundles}
submit2eval = {}
for eval_id, eval_bundle in eval_bundles.items():
meta = self._get_competition_metadata(eval_bundle)
if meta is not None:
if meta.get('hide', False):
del eval_bundles[eval_id]
else:
submit2eval[meta['submit_id']] = eval_bundle
logger.debug('Fetching corresponding original submission bundles')
while True:
if len(eval_bundles) == 0:
submit_bundles = {}
break
try:
uuids = submit2eval.keys()
submit_bundles = []
for start in range(0, len(uuids), 50):
end = start + 50
submit_bundles.extend(
self.client.fetch(
'bundles',
params={
'specs': uuids[start:end],
'worksheet': self.config['log_worksheet_uuid'],
'include': ['owner', 'group_permissions'],
},
)
)
break
except NotFoundError as e:
missing_submit_uuid = re.search(UUID_STR, e.message).group(0)
eval_uuid = submit2eval[missing_submit_uuid]['id']
if self.config['allow_orphans']:
logger.info("Clearing reference to deleted submission %s", missing_submit_uuid)
self._clear_competition_metadata(eval_bundles[eval_uuid])
pass
else:
logger.info("Removing submission %s", missing_submit_uuid)
self._untag([submit2eval[missing_submit_uuid]], self.config['evaluate']['tag'])
del eval_bundles[eval_uuid]
del submit2eval[missing_submit_uuid]
continue
eval2submit = {}
for submit_bundle in submit_bundles:
eval_bundle = submit2eval[submit_bundle['id']]
eval2submit[eval_bundle['id']] = submit_bundle
return eval_bundles, eval2submit
def _fetch_scores(self, eval_bundles):
scores = {}
queries = []
keys = []
for bundle in eval_bundles.itervalues():
if bundle['state'] == State.READY:
for spec in self.config['score_specs']:
queries.append((bundle['id'], spec['key'], None))
keys.append((bundle['id'], spec['name']))
else:
scores[bundle['id']] = {spec['name']: None for spec in self.config['score_specs']}
results = self.client.interpret_file_genpaths(queries)
for (bundle_id, spec_name), value in zip(keys, results):
if bundle_id not in scores:
scores[bundle_id] = {}
scores[bundle_id][spec_name] = value
return scores
def generate_leaderboard(self, num_total_submissions, num_period_submissions):
eval_bundles, eval2submit = self._fetch_leaderboard()
scores = self._fetch_scores(eval_bundles)
logger.debug('Fetching scores and building leaderboard table')
leaderboard = []
for eval_bundle in eval_bundles.itervalues():
meta = self._get_competition_metadata(eval_bundle)
if eval_bundle['id'] in eval2submit:
submit_bundle = eval2submit[eval_bundle['id']]
submission_info = {
'description': meta.get('description', None)
or submit_bundle['metadata']['description'],
'public': self._is_publicly_readable(submit_bundle),
'user_name': submit_bundle['owner']['user_name'],
'num_total_submissions': num_total_submissions[submit_bundle['owner']['id']],
'num_period_submissions': num_period_submissions[submit_bundle['owner']['id']],
'created': submit_bundle['metadata']['created'],
}
else:
# defaults based on just the eval bundle.
submission_info = {
'description': eval_bundle['metadata']['description'],
'public': None,
'user_name': None,
'num_total_submissions': 0,
'num_period_submissions': 0,
'created': eval_bundle['metadata']['created'],
}
leaderboard.append(
{
'bundle': eval_bundle,
'scores': scores[eval_bundle['id']],
'submission': submission_info,
}
)
# Sort by the scores, descending
leaderboard.sort(
key=lambda e: tuple(e['scores'][spec['name']] for spec in self.config['score_specs']),
reverse=True,
)
# Write table to JSON file along with other data
output = {'leaderboard': leaderboard, 'config': self.config, 'updated': time.time()}
with open(self.output_path, 'w') as fp:
fp.write(pretty_json(output))
logger.debug('Wrote leaderboard at {.output_path}'.format(self))
def run_once(self):
submissions, num_total_submissions, num_period_submissions = self.collect_submissions()
if not submissions:
logger.debug('No new submissions.')
if not self.leaderboard_only:
for submit_bundle in submissions:
logger.info(
"Mimicking submission for " "{owner[user_name]}".format(**submit_bundle)
)
predict_bundle = self.run_prediction(submit_bundle)
if predict_bundle is None:
logger.info(
"Aborting submission for " "{owner[user_name]}".format(**submit_bundle)
)
continue
self.run_evaluation(submit_bundle, predict_bundle)
logger.info(
"Finished mimicking submission for "
"{owner[user_name]}".format(**submit_bundle)
)
# Update local counts for the leaderboard
owner_id = submit_bundle['owner']['id']
num_total_submissions[owner_id] += 1
num_period_submissions[owner_id] += 1
self.generate_leaderboard(num_total_submissions, num_period_submissions)
def run(self):
self.ensure_log_worksheet_private()
logger.info('Starting competition daemon...')
while not self.should_stop:
try:
self.run_once()
except:
traceback.print_exc()
if self.should_stop:
break
time.sleep(self.config['refresh_period_seconds'])
def stop(self):
logger.info('Stopping competition daemon...')
self.should_stop = True
def generate_description():
def display_schema(schema, doc, indent, first_indent=None):
saved_indent = indent
if first_indent is not None:
indent = first_indent
for field_name, field in schema._declared_fields.items():
field_help = field.metadata.get('metadata', '')
field_class = field.__class__
if field_class is fields.Nested:
doc += indent + '%s:\n' % field_name
doc = display_schema(field.nested, doc, (indent + ' '))
elif field_class is fields.List:
doc += indent + '%s:\n' % field_name
doc = display_schema(
field.container.nested, doc, (indent + ' '), first_indent=(indent + ' - ')
)
doc += indent + ' - ...\n'
else:
field_type = field.__class__.__name__.lower()
if field.missing is missing and field.required:
doc += indent + '%s: %s, %s [required]\n' % (field_name, field_type, field_help)
elif field.missing is missing and not field.required:
doc += indent + '%s: %s, %s\n' % (field_name, field_type, field_help)
else:
doc += indent + '%s: %s, %s [default: %s]\n' % (
field_name,
field_type,
field_help,
json.dumps(field.missing).strip(),
)
indent = saved_indent
return doc
return display_schema(ConfigSchema, __doc__, ' ' * 4)
def main():
# Support all configs as command line arguments too
parser = argparse.ArgumentParser(
description=generate_description(), formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument('config_file', help='YAML/JSON file containing configurations.')
parser.add_argument('output_path', help='path to write JSON file containing leaderboard.')
parser.add_argument(
'-l',
'--leaderboard-only',
action='store_true',
help='Generate a new leaderboard but without creating any new runs.',
)
parser.add_argument(
'-d', '--daemon', action='store_true', help='Run as a daemon. (By default only runs once.)'
)
parser.add_argument('-v', '--verbose', action='store_true', help='Output verbose log messages.')
args = parser.parse_args()
logging.basicConfig(
format='[%(levelname)s] %(asctime)s: %(message)s',
level=(logging.DEBUG if args.verbose else logging.INFO),
)
comp = Competition(args.config_file, args.output_path, args.leaderboard_only)
if args.daemon:
# Catch interrupt signals so that eval loop doesn't get interrupted in the
for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP]:
signal.signal(sig, lambda signup, frame: comp.stop())
comp.run()
else:
logger.info('Running batch competition evaluation')
comp.ensure_log_worksheet_private()
comp.run_once()
if __name__ == '__main__':
main()
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.