hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f710e3fc0e09880ad2d7a75f9ac3339aa1d05698
3,765
py
Python
StandardDataSets/collada/library_effects/effect/image/singleImage/singleImage.py
KhronosGroup/COLLADA-CTS
61f2a560cbb2a06ee62da8025241f6b08d06bfd9
[ "MIT" ]
20
2015-03-19T08:02:57.000Z
2020-10-16T15:16:11.000Z
StandardDataSets/collada/library_effects/effect/profile_COMMON/image/oneImageDiffDir/oneImageDiffDir.py
Acidburn0zzz/COLLADA-CTS
39a36188cf8710bbc003df43ed70b965eb4386bd
[ "MIT" ]
4
2017-04-19T18:42:05.000Z
2017-06-17T03:03:28.000Z
StandardDataSets/collada/library_effects/effect/profile_COMMON/image/oneImageDiffDir/oneImageDiffDir.py
Acidburn0zzz/COLLADA-CTS
39a36188cf8710bbc003df43ed70b965eb4386bd
[ "MIT" ]
10
2015-03-26T02:52:24.000Z
2022-02-24T08:43:48.000Z
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials, and to permit persons to whom the Materials are 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 Materials. # THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. # See Core.Logic.FJudgementContext for the information # of the 'context' parameter. # This sample judging object does the following: # # JudgeBaseline: just verifies that the standard steps did not crash. # JudgeSuperior: also verifies that the validation steps are not in error. # JudgeExemplary: same as intermediate badge. # We import an assistant script that includes the common verifications # methods. The assistant buffers its checks, so that running them again # does not incurs an unnecessary performance hint. from StandardDataSets.scripts import JudgeAssistant # Please feed your node list here: tagLst = [] attrName = '' attrVal = '' dataToCheck = '' class SimpleJudgingObject: def __init__(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst self.attrName = _attrName self.attrVal = _attrVal self.dataToCheck = _data self.status_baseline = False self.status_superior = False self.status_exemplary = False self.__assistant = JudgeAssistant.JudgeAssistant() def JudgeBaseline(self, context): # No step should not crash self.__assistant.CheckCrashes(context) # Import/export/validate must exist and pass, while Render must only exist. self.__assistant.CheckSteps(context, ["Import", "Export", "Validate"], ["Render"]) # Compare the rendered images between import and export, and if passed, # compare images against reference test if ( self.__assistant.CompareRenderedImages(context) ): self.__assistant.CompareImagesAgainst(context, "_reference_oneImage") self.status_baseline = self.__assistant.DeferJudgement(context) return self.status_baseline # To pass intermediate you need to pass basic, this object could also include additional # tests that were specific to the intermediate badge. def JudgeSuperior(self, context): self.status_superior = self.status_baseline return self.status_superior # To pass advanced you need to pass intermediate, this object could also include additional # tests that were specific to the advanced badge def JudgeExemplary(self, context): self.status_exemplary = self.status_superior return self.status_exemplary # This is where all the work occurs: "judgingObject" is an absolutely necessary token. # The dynamic loader looks very specifically for a class instance named "judgingObject". # judgingObject = SimpleJudgingObject(tagLst, attrName, attrVal, dataToCheck);
53.785714
467
0.728818
from StandardDataSets.scripts import JudgeAssistant tagLst = [] attrName = '' attrVal = '' dataToCheck = '' class SimpleJudgingObject: def __init__(self, _tagLst, _attrName, _attrVal, _data): self.tagList = _tagLst self.attrName = _attrName self.attrVal = _attrVal self.dataToCheck = _data self.status_baseline = False self.status_superior = False self.status_exemplary = False self.__assistant = JudgeAssistant.JudgeAssistant() def JudgeBaseline(self, context): self.__assistant.CheckCrashes(context) self.__assistant.CheckSteps(context, ["Import", "Export", "Validate"], ["Render"]) if ( self.__assistant.CompareRenderedImages(context) ): self.__assistant.CompareImagesAgainst(context, "_reference_oneImage") self.status_baseline = self.__assistant.DeferJudgement(context) return self.status_baseline def JudgeSuperior(self, context): self.status_superior = self.status_baseline return self.status_superior def JudgeExemplary(self, context): self.status_exemplary = self.status_superior return self.status_exemplary judgingObject = SimpleJudgingObject(tagLst, attrName, attrVal, dataToCheck);
true
true
f710e48f87b066661c04bad6f9ccc2417d946d9c
10,349
py
Python
matmul.py
peterwauligmann/sparse_mm
344c06c183854f72224c1e88ad2ced2e092d4efb
[ "BSD-3-Clause" ]
null
null
null
matmul.py
peterwauligmann/sparse_mm
344c06c183854f72224c1e88ad2ced2e092d4efb
[ "BSD-3-Clause" ]
null
null
null
matmul.py
peterwauligmann/sparse_mm
344c06c183854f72224c1e88ad2ced2e092d4efb
[ "BSD-3-Clause" ]
2
2020-12-09T12:46:58.000Z
2021-07-13T10:56:44.000Z
from typing import Tuple from codegen.ast import * from codegen.sugar import * from codegen.forms import * from codegen.precision import * import scripts.old_arm import scripts.max_bn_knl from cursors import * import architecture import numpy def decompose_pattern(k, n, pattern:Matrix[bool], bk:int, bn:int) -> Tuple[Matrix[int], List[Matrix[bool]]]: Bk,Bn = k//bk, n//bn patterns = [] x = 0 n_overhead = n % bn k_overhead = k % bk if n_overhead > 0: Bn += 1 if k_overhead > 0: Bk += 1 blocks = Matrix.full(Bk,Bn,-1) for Bni in range(Bn): for Bki in range(Bk): if Bni + 1 == Bn and n_overhead > 0 and Bki + 1 == Bk and k_overhead > 0: block = pattern[(Bki*bk):((Bki+1)*bk+k_overhead), (Bni*bn):((Bni)*bn+n_overhead)] elif Bni + 1 == Bn and n_overhead > 0: block = pattern[(Bki*bk):((Bki+1)*bk), (Bni*bn):((Bni)*bn+n_overhead)] elif Bki + 1 == Bk and k_overhead > 0: block = pattern[(Bki*bk):((Bki+1)*bk+k_overhead), (Bni*bn):((Bni+1)*bn)] else: block = pattern[(Bki*bk):((Bki+1)*bk), (Bni*bn):((Bni+1)*bn)] blocks[Bki,Bni] = x x += 1 patterns.append(block) mtx_overhead = [0] * n for i in range(n): for j in range(k, pattern.rows): if pattern[j, i]: mtx_overhead[i] += 1 return blocks, patterns, mtx_overhead class MatMul: def __init__(self, m: int, n: int, k: int, lda: int, ldb: int, ldc: int, alpha: str, beta: str, mtx_filename: str, mtx_format: str = 'any', output_funcname: str = None, output_filename: str = None, output_overwrite: bool = False, bm: int = None, bn: int = None, bk: int = None, arch: str = 'knl', precision: str = 'd', prefetching: str = None, **kwargs # Accept and ignore args which don't belong ) -> None: self.m = m self.n = n self.k = k self.lda = lda self.ldb = ldb self.ldc = ldc try: self.alpha = float(alpha) except: self.alpha = 'generic' try: self.beta = float(beta) except: self.beta = 'generic' if arch == 'skx': arch = 'knl' self.arch = arch assert precision.lower() in ['s', 'd'] self.precision = Precision.DOUBLE if precision.lower() == 'd' else Precision.SINGLE architecture.init() architecture.arch = arch architecture.Generator = architecture.get_class("codegen.architectures." + arch + ".generator.Generator") architecture.operands = architecture.get_class("codegen.architectures." + arch + ".operands") self.generator = architecture.Generator(self.precision) self.v_size = self.generator.get_v_size() if bk == None: bk = 2 if arch == 'knl' else 1 if bm == None or bn == None: if arch == 'knl': (self.bm, self.bn) = scripts.max_bn_knl.getBlocksize(m, n, bk, self.v_size) elif arch == 'arm': (self.bm, self.bn) = scripts.old_arm.getBlocksize(m, n, bk, self.v_size) else: self.bm = bm self.bn = bn self.bk = bk self.prefetching = prefetching self.mtx_filename = mtx_filename self.mtx_format = mtx_format self.output_funcname = output_funcname self.output_filename = output_filename self.output_overwrite = output_overwrite if ldb == 0: pattern = Matrix.load(mtx_filename) else: mtx = numpy.zeros((k, n)) for i in range(k): for j in range(n): mtx[i, j] = 1 pattern = Matrix(mtx) blocks,patterns,mtx_overhead = decompose_pattern(self.k, self.n, pattern, self.bk, self.bn) self.nnz = 0 self.flop = 0 if ldb == 0: for i in range(n): for j in range(k): if pattern[j,i]: self.nnz += 1 self.flop = self.nnz * m * 2 self.nnz += sum(mtx_overhead) else: self.nnz = ldb * self.n self.flop = m * n * k * 2 prefetchReg = self.generator.init_prefetching(self.prefetching) assert(self.m % self.v_size == 0) self.A_regs, self.B_regs, self.C_regs, self.starting_regs, self.alpha_reg, self.beta_reg, self.loop_reg, self.additional_regs = self.generator.make_reg_blocks(self.bm, self.bn, self.bk, self.v_size, self.nnz, self.m, self.n, self.k) self.A = DenseCursor("A", self.starting_regs[0], self.m, self.k, self.lda, self.bm, self.bk, self.precision.value) self.B = BlockCursor("B", self.starting_regs[1], self.k, self.n, self.ldb, self.bk, self.bn, self.precision.value, blocks, patterns,mtx_overhead) self.C = DenseCursor("C", self.starting_regs[2], self.m, self.n, self.ldc, self.bm, self.bn, self.precision.value) self.C_pf = DenseCursor("C_pf", prefetchReg, self.m, self.n, self.ldc, self.bm, self.bn, self.precision.value) if prefetchReg else None def make_nk_unroll(self): asm = block("Unrolling over bn and bk") A_ptr = CursorLocation() B_ptr = self.B.start() C_ptr = CursorLocation() C_pf_ptr = CursorLocation() Bn = self.n // self.bn Bk = self.k // self.bk vm = self.bm // self.v_size n_overhead = self.n % self.bn k_overhead = self.k % self.bk if n_overhead > 0: Bn += 1 if k_overhead > 0: Bk += 1 asm.add(self.generator.make_b_pointers(self.starting_regs[1], self.additional_regs, self.nnz)) for Bni in range(0,Bn): regs = self.C_regs if Bni + 1 == Bn and n_overhead > 0: regs = self.C_regs[0:vm, 0:n_overhead] if self.alpha == 1.0 and self.beta != 0.0: asm.add(self.generator.move_register_block(self.C, C_ptr, Coords(), regs, self.v_size, self.additional_regs, None, False)) if self.beta != 1.0: for ic in range(regs.shape[1]): for ir in range(regs.shape[0]): asm.add(mul(regs[ir,ic], self.beta_reg[1], regs[ir,ic])) else: asm.add(self.generator.make_zero_block(regs, self.additional_regs)) for Bki in range(0,Bk): to_A = Coords(right=Bki) to_B = Coords(right=Bni, down=Bki, absolute=True) if self.B.has_nonzero_block(B_ptr, to_B): asm.add(self.generator.make_microkernel(self.A, self.B, A_ptr, B_ptr, self.A_regs, self.B_regs, regs, self.v_size, self.additional_regs, to_A, to_B)) if self.alpha != 1.0: store_block = block("") for x in range(0, regs.shape[1], self.A_regs.shape[1]): A_regs_cut = self.A_regs[0:min(self.A_regs.shape[0], regs.shape[0]), 0:regs.shape[1]-x] if self.beta != 0.0: store_block.add(self.generator.move_register_block(self.C, C_ptr, Coords(), A_regs_cut, self.v_size, self.additional_regs, None, False, None, self.ldc * x)) for ir in range(A_regs_cut.shape[0]): for ic in range(A_regs_cut.shape[1]): if self.beta != 0.0 and self.beta != 1.0: store_block.add(mul(A_regs_cut[ir,ic], self.beta_reg[1], A_regs_cut[ir,ic])) if self.beta == 0.0: store_block.add(mul(regs[ir, x + ic], self.alpha_reg[1], A_regs_cut[ir, ic], "C = C + alpha * AB")) else: store_block.add(fma(regs[ir, x + ic], self.alpha_reg[1], A_regs_cut[ir, ic], "C = C + alpha * AB", False)) store_block.add(self.generator.move_register_block(self.C, C_ptr, Coords(), A_regs_cut, self.v_size, self.additional_regs, None, True, self.prefetching, self.ldc * x)) asm.add(store_block) else: asm.add(self.generator.move_register_block(self.C, C_ptr, Coords(), regs, self.v_size, self.additional_regs, None, True, self.prefetching)) if (Bni != Bn-1): move_C, C_ptr = self.C.move(C_ptr, Coords(right=1)) asm.add(move_C) if self.C_pf: move_C_pf, C_pf_ptr = self.C_pf.move(C_pf_ptr, Coords(right=1)) asm.add(move_C_pf) return asm def make(self): A_ptr = CursorLocation() C_ptr = CursorLocation() C_pf_ptr = CursorLocation() Bm = self.m // self.bm Bn = self.n // self.bn Bk = self.k // self.bk if self.n % self.bn != 0: Bn += 1 loopBody = [ self.make_nk_unroll(), self.A.move(A_ptr, Coords(down=1))[0], self.C.move(C_ptr, Coords(down=1, right=1-Bn))[0] ] if self.C_pf: loopBody.append(self.C_pf.move(C_pf_ptr, Coords(down=1, right=1-Bn))[0]) asm = block("unrolled_{}x{}x{}".format(self.m,self.n,self.k), self.generator.bcst_alpha_beta(self.alpha_reg, self.beta_reg), self.generator.make_scaling_offsets(self.additional_regs, self.nnz), loop(self.loop_reg, 0, Bm, 1).body(*loopBody) ) vm_overhead = (self.m % self.bm) // self.v_size if vm_overhead > 0: self.m = self.m % self.bm self.bm = self.m % self.bm self.A_regs = self.A_regs[0:self.bm // self.v_size, 0:self.bk] self.C_regs = self.C_regs[0:self.bm // self.v_size, 0:self.bn] self.A.r = self.m asm.add(self.make_nk_unroll()) return asm
35.320819
240
0.527684
from typing import Tuple from codegen.ast import * from codegen.sugar import * from codegen.forms import * from codegen.precision import * import scripts.old_arm import scripts.max_bn_knl from cursors import * import architecture import numpy def decompose_pattern(k, n, pattern:Matrix[bool], bk:int, bn:int) -> Tuple[Matrix[int], List[Matrix[bool]]]: Bk,Bn = k//bk, n//bn patterns = [] x = 0 n_overhead = n % bn k_overhead = k % bk if n_overhead > 0: Bn += 1 if k_overhead > 0: Bk += 1 blocks = Matrix.full(Bk,Bn,-1) for Bni in range(Bn): for Bki in range(Bk): if Bni + 1 == Bn and n_overhead > 0 and Bki + 1 == Bk and k_overhead > 0: block = pattern[(Bki*bk):((Bki+1)*bk+k_overhead), (Bni*bn):((Bni)*bn+n_overhead)] elif Bni + 1 == Bn and n_overhead > 0: block = pattern[(Bki*bk):((Bki+1)*bk), (Bni*bn):((Bni)*bn+n_overhead)] elif Bki + 1 == Bk and k_overhead > 0: block = pattern[(Bki*bk):((Bki+1)*bk+k_overhead), (Bni*bn):((Bni+1)*bn)] else: block = pattern[(Bki*bk):((Bki+1)*bk), (Bni*bn):((Bni+1)*bn)] blocks[Bki,Bni] = x x += 1 patterns.append(block) mtx_overhead = [0] * n for i in range(n): for j in range(k, pattern.rows): if pattern[j, i]: mtx_overhead[i] += 1 return blocks, patterns, mtx_overhead class MatMul: def __init__(self, m: int, n: int, k: int, lda: int, ldb: int, ldc: int, alpha: str, beta: str, mtx_filename: str, mtx_format: str = 'any', output_funcname: str = None, output_filename: str = None, output_overwrite: bool = False, bm: int = None, bn: int = None, bk: int = None, arch: str = 'knl', precision: str = 'd', prefetching: str = None, **kwargs ) -> None: self.m = m self.n = n self.k = k self.lda = lda self.ldb = ldb self.ldc = ldc try: self.alpha = float(alpha) except: self.alpha = 'generic' try: self.beta = float(beta) except: self.beta = 'generic' if arch == 'skx': arch = 'knl' self.arch = arch assert precision.lower() in ['s', 'd'] self.precision = Precision.DOUBLE if precision.lower() == 'd' else Precision.SINGLE architecture.init() architecture.arch = arch architecture.Generator = architecture.get_class("codegen.architectures." + arch + ".generator.Generator") architecture.operands = architecture.get_class("codegen.architectures." + arch + ".operands") self.generator = architecture.Generator(self.precision) self.v_size = self.generator.get_v_size() if bk == None: bk = 2 if arch == 'knl' else 1 if bm == None or bn == None: if arch == 'knl': (self.bm, self.bn) = scripts.max_bn_knl.getBlocksize(m, n, bk, self.v_size) elif arch == 'arm': (self.bm, self.bn) = scripts.old_arm.getBlocksize(m, n, bk, self.v_size) else: self.bm = bm self.bn = bn self.bk = bk self.prefetching = prefetching self.mtx_filename = mtx_filename self.mtx_format = mtx_format self.output_funcname = output_funcname self.output_filename = output_filename self.output_overwrite = output_overwrite if ldb == 0: pattern = Matrix.load(mtx_filename) else: mtx = numpy.zeros((k, n)) for i in range(k): for j in range(n): mtx[i, j] = 1 pattern = Matrix(mtx) blocks,patterns,mtx_overhead = decompose_pattern(self.k, self.n, pattern, self.bk, self.bn) self.nnz = 0 self.flop = 0 if ldb == 0: for i in range(n): for j in range(k): if pattern[j,i]: self.nnz += 1 self.flop = self.nnz * m * 2 self.nnz += sum(mtx_overhead) else: self.nnz = ldb * self.n self.flop = m * n * k * 2 prefetchReg = self.generator.init_prefetching(self.prefetching) assert(self.m % self.v_size == 0) self.A_regs, self.B_regs, self.C_regs, self.starting_regs, self.alpha_reg, self.beta_reg, self.loop_reg, self.additional_regs = self.generator.make_reg_blocks(self.bm, self.bn, self.bk, self.v_size, self.nnz, self.m, self.n, self.k) self.A = DenseCursor("A", self.starting_regs[0], self.m, self.k, self.lda, self.bm, self.bk, self.precision.value) self.B = BlockCursor("B", self.starting_regs[1], self.k, self.n, self.ldb, self.bk, self.bn, self.precision.value, blocks, patterns,mtx_overhead) self.C = DenseCursor("C", self.starting_regs[2], self.m, self.n, self.ldc, self.bm, self.bn, self.precision.value) self.C_pf = DenseCursor("C_pf", prefetchReg, self.m, self.n, self.ldc, self.bm, self.bn, self.precision.value) if prefetchReg else None def make_nk_unroll(self): asm = block("Unrolling over bn and bk") A_ptr = CursorLocation() B_ptr = self.B.start() C_ptr = CursorLocation() C_pf_ptr = CursorLocation() Bn = self.n // self.bn Bk = self.k // self.bk vm = self.bm // self.v_size n_overhead = self.n % self.bn k_overhead = self.k % self.bk if n_overhead > 0: Bn += 1 if k_overhead > 0: Bk += 1 asm.add(self.generator.make_b_pointers(self.starting_regs[1], self.additional_regs, self.nnz)) for Bni in range(0,Bn): regs = self.C_regs if Bni + 1 == Bn and n_overhead > 0: regs = self.C_regs[0:vm, 0:n_overhead] if self.alpha == 1.0 and self.beta != 0.0: asm.add(self.generator.move_register_block(self.C, C_ptr, Coords(), regs, self.v_size, self.additional_regs, None, False)) if self.beta != 1.0: for ic in range(regs.shape[1]): for ir in range(regs.shape[0]): asm.add(mul(regs[ir,ic], self.beta_reg[1], regs[ir,ic])) else: asm.add(self.generator.make_zero_block(regs, self.additional_regs)) for Bki in range(0,Bk): to_A = Coords(right=Bki) to_B = Coords(right=Bni, down=Bki, absolute=True) if self.B.has_nonzero_block(B_ptr, to_B): asm.add(self.generator.make_microkernel(self.A, self.B, A_ptr, B_ptr, self.A_regs, self.B_regs, regs, self.v_size, self.additional_regs, to_A, to_B)) if self.alpha != 1.0: store_block = block("") for x in range(0, regs.shape[1], self.A_regs.shape[1]): A_regs_cut = self.A_regs[0:min(self.A_regs.shape[0], regs.shape[0]), 0:regs.shape[1]-x] if self.beta != 0.0: store_block.add(self.generator.move_register_block(self.C, C_ptr, Coords(), A_regs_cut, self.v_size, self.additional_regs, None, False, None, self.ldc * x)) for ir in range(A_regs_cut.shape[0]): for ic in range(A_regs_cut.shape[1]): if self.beta != 0.0 and self.beta != 1.0: store_block.add(mul(A_regs_cut[ir,ic], self.beta_reg[1], A_regs_cut[ir,ic])) if self.beta == 0.0: store_block.add(mul(regs[ir, x + ic], self.alpha_reg[1], A_regs_cut[ir, ic], "C = C + alpha * AB")) else: store_block.add(fma(regs[ir, x + ic], self.alpha_reg[1], A_regs_cut[ir, ic], "C = C + alpha * AB", False)) store_block.add(self.generator.move_register_block(self.C, C_ptr, Coords(), A_regs_cut, self.v_size, self.additional_regs, None, True, self.prefetching, self.ldc * x)) asm.add(store_block) else: asm.add(self.generator.move_register_block(self.C, C_ptr, Coords(), regs, self.v_size, self.additional_regs, None, True, self.prefetching)) if (Bni != Bn-1): move_C, C_ptr = self.C.move(C_ptr, Coords(right=1)) asm.add(move_C) if self.C_pf: move_C_pf, C_pf_ptr = self.C_pf.move(C_pf_ptr, Coords(right=1)) asm.add(move_C_pf) return asm def make(self): A_ptr = CursorLocation() C_ptr = CursorLocation() C_pf_ptr = CursorLocation() Bm = self.m // self.bm Bn = self.n // self.bn Bk = self.k // self.bk if self.n % self.bn != 0: Bn += 1 loopBody = [ self.make_nk_unroll(), self.A.move(A_ptr, Coords(down=1))[0], self.C.move(C_ptr, Coords(down=1, right=1-Bn))[0] ] if self.C_pf: loopBody.append(self.C_pf.move(C_pf_ptr, Coords(down=1, right=1-Bn))[0]) asm = block("unrolled_{}x{}x{}".format(self.m,self.n,self.k), self.generator.bcst_alpha_beta(self.alpha_reg, self.beta_reg), self.generator.make_scaling_offsets(self.additional_regs, self.nnz), loop(self.loop_reg, 0, Bm, 1).body(*loopBody) ) vm_overhead = (self.m % self.bm) // self.v_size if vm_overhead > 0: self.m = self.m % self.bm self.bm = self.m % self.bm self.A_regs = self.A_regs[0:self.bm // self.v_size, 0:self.bk] self.C_regs = self.C_regs[0:self.bm // self.v_size, 0:self.bn] self.A.r = self.m asm.add(self.make_nk_unroll()) return asm
true
true
f710e546a33ec5507341c5a48dd231538f0e973b
3,393
py
Python
sdk/communication/azure-communication-administration/tests/test_communication_identity_client_async.py
ljos/azure-sdk-for-python
f64b1e269fc4f05a5a2ca68dda3c8f8b4ed0301e
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/communication/azure-communication-administration/tests/test_communication_identity_client_async.py
ljos/azure-sdk-for-python
f64b1e269fc4f05a5a2ca68dda3c8f8b4ed0301e
[ "MIT" ]
null
null
null
sdk/communication/azure-communication-administration/tests/test_communication_identity_client_async.py
ljos/azure-sdk-for-python
f64b1e269fc4f05a5a2ca68dda3c8f8b4ed0301e
[ "MIT" ]
null
null
null
# 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. # -------------------------------------------------------------------------- import pytest from azure.communication.administration.aio import CommunicationIdentityClient from azure_devtools.scenario_tests import RecordingProcessor from devtools_testutils import ResourceGroupPreparer from _shared.helper import URIIdentityReplacer from _shared.asynctestcase import AsyncCommunicationTestCase from _shared.testcase import BodyReplacerProcessor from _shared.communication_service_preparer import CommunicationServicePreparer class CommunicationIdentityClientTestAsync(AsyncCommunicationTestCase): def setUp(self): super(CommunicationIdentityClientTestAsync, self).setUp() self.recording_processors.extend([ BodyReplacerProcessor(keys=["id", "token"]), URIIdentityReplacer()]) @ResourceGroupPreparer(random_name_enabled=True) @CommunicationServicePreparer() @pytest.mark.live_test_only @pytest.mark.asyncio @AsyncCommunicationTestCase.await_prepared_test async def test_create_user(self, connection_string): identity_client = CommunicationIdentityClient.from_connection_string(connection_string) async with identity_client: user = await identity_client.create_user() assert user.identifier is not None @ResourceGroupPreparer(random_name_enabled=True) @CommunicationServicePreparer() @pytest.mark.live_test_only @pytest.mark.asyncio @AsyncCommunicationTestCase.await_prepared_test async def test_issue_token(self, connection_string): identity_client = CommunicationIdentityClient.from_connection_string(connection_string) async with identity_client: user = await identity_client.create_user() token_response = await identity_client.issue_token(user, scopes=["chat"]) assert user.identifier is not None assert token_response.token is not None @ResourceGroupPreparer(random_name_enabled=True) @CommunicationServicePreparer() @pytest.mark.live_test_only @pytest.mark.asyncio @AsyncCommunicationTestCase.await_prepared_test async def test_revoke_tokens(self, connection_string): identity_client = CommunicationIdentityClient.from_connection_string(connection_string) async with identity_client: user = await identity_client.create_user() token_response = await identity_client.issue_token(user, scopes=["chat"]) await identity_client.revoke_tokens(user) assert user.identifier is not None assert token_response.token is not None @ResourceGroupPreparer(random_name_enabled=True) @CommunicationServicePreparer() @pytest.mark.live_test_only @pytest.mark.asyncio @AsyncCommunicationTestCase.await_prepared_test async def test_delete_user(self, connection_string): identity_client = CommunicationIdentityClient.from_connection_string(connection_string) async with identity_client: user = await identity_client.create_user() await identity_client.delete_user(user) assert user.identifier is not None
44.644737
95
0.736516
import pytest from azure.communication.administration.aio import CommunicationIdentityClient from azure_devtools.scenario_tests import RecordingProcessor from devtools_testutils import ResourceGroupPreparer from _shared.helper import URIIdentityReplacer from _shared.asynctestcase import AsyncCommunicationTestCase from _shared.testcase import BodyReplacerProcessor from _shared.communication_service_preparer import CommunicationServicePreparer class CommunicationIdentityClientTestAsync(AsyncCommunicationTestCase): def setUp(self): super(CommunicationIdentityClientTestAsync, self).setUp() self.recording_processors.extend([ BodyReplacerProcessor(keys=["id", "token"]), URIIdentityReplacer()]) @ResourceGroupPreparer(random_name_enabled=True) @CommunicationServicePreparer() @pytest.mark.live_test_only @pytest.mark.asyncio @AsyncCommunicationTestCase.await_prepared_test async def test_create_user(self, connection_string): identity_client = CommunicationIdentityClient.from_connection_string(connection_string) async with identity_client: user = await identity_client.create_user() assert user.identifier is not None @ResourceGroupPreparer(random_name_enabled=True) @CommunicationServicePreparer() @pytest.mark.live_test_only @pytest.mark.asyncio @AsyncCommunicationTestCase.await_prepared_test async def test_issue_token(self, connection_string): identity_client = CommunicationIdentityClient.from_connection_string(connection_string) async with identity_client: user = await identity_client.create_user() token_response = await identity_client.issue_token(user, scopes=["chat"]) assert user.identifier is not None assert token_response.token is not None @ResourceGroupPreparer(random_name_enabled=True) @CommunicationServicePreparer() @pytest.mark.live_test_only @pytest.mark.asyncio @AsyncCommunicationTestCase.await_prepared_test async def test_revoke_tokens(self, connection_string): identity_client = CommunicationIdentityClient.from_connection_string(connection_string) async with identity_client: user = await identity_client.create_user() token_response = await identity_client.issue_token(user, scopes=["chat"]) await identity_client.revoke_tokens(user) assert user.identifier is not None assert token_response.token is not None @ResourceGroupPreparer(random_name_enabled=True) @CommunicationServicePreparer() @pytest.mark.live_test_only @pytest.mark.asyncio @AsyncCommunicationTestCase.await_prepared_test async def test_delete_user(self, connection_string): identity_client = CommunicationIdentityClient.from_connection_string(connection_string) async with identity_client: user = await identity_client.create_user() await identity_client.delete_user(user) assert user.identifier is not None
true
true
f710e55ac5e0fd15213c1588668531cca7d3d44b
3,815
py
Python
dy-get.py
1A2553E/dy-get
fd66a9132e592b5c8f033e37e57ed2ad3dc9207c
[ "Apache-2.0" ]
null
null
null
dy-get.py
1A2553E/dy-get
fd66a9132e592b5c8f033e37e57ed2ad3dc9207c
[ "Apache-2.0" ]
null
null
null
dy-get.py
1A2553E/dy-get
fd66a9132e592b5c8f033e37e57ed2ad3dc9207c
[ "Apache-2.0" ]
null
null
null
from moviepy.editor import * from os import chdir, getcwd, mkdir from random import randint import sys import requests from concurrent.futures import ThreadPoolExecutor from requests import get, head import time # 自定义 THREAD_NUM=12 # 线程数,默认为12个 HEADER=" "# 请求头,默认为一个空格 class downloader: def __init__(self, url, num, name): self.url = url self.num = num self.name = name self.getsize = 0 r = head(self.url, allow_redirects=True) self.size = int(r.headers['Content-Length']) def down(self, start, end, chunk_size=10240): headers = {'range': f'bytes={start}-{end}'} r = get(self.url, headers=headers, stream=True) with open(self.name, "rb+") as f: f.seek(start) for chunk in r.iter_content(chunk_size): f.write(chunk) self.getsize += chunk_size def main(self): start_time = time.time() f = open(self.name, 'wb') f.truncate(self.size) f.close() tp = ThreadPoolExecutor(max_workers=self.num) futures = [] start = 0 for i in range(self.num): end = int((i+1)/self.num*self.size) future = tp.submit(self.down, start, end) futures.append(future) start = end+1 while True: process = self.getsize/self.size*100 last = self.getsize time.sleep(1) curr = self.getsize down = (curr-last)/1024 if down > 1024: speed = f'{down/1024:6.2f}MB/s' else: speed = f'{down:6.2f}KB/s' print(f'process: {process:6.2f}% | speed: {speed}', end='\r') if process >= 100: print(f'process: {100.00:6}% | speed: 00.00KB/s', end=' | ') break tp.shutdown() end_time = time.time() total_time = end_time-start_time average_speed = self.size/total_time/1024/1024 print( f'total-time: {total_time:.0f}s | average-speed: {average_speed:.2f}MB/s') DOWNMUSIC = True url = input("url:") video_id = url.split("/") # 切割链接,获取视频id # 获得视频id 例如https://www.douyin.com/video/7058986650088607012 video_id = video_id[len(video_id)-1] try: int(video_id) except: print("dy-get [error] 获取video_id失败!") sys.exit(1) response = requests.get('https://www.douyin.com/web/api/v2/aweme/iteminfo/?item_ids='+str(video_id), headers='') # 可填入自己的headers try: video_json = response.json() # 读取json except: print("dy-get [error] 获取json失败!") sys.exit(1) try: get_id = video_json["item_list"][0]["video"]["vid"] except: print("dy-get [error] 获取vid失败!") sys.exit(1) picture = video_json["item_list"][0]["video"]["ratio"] width = video_json["item_list"][0]["video"]["width"] height = video_json["item_list"][0]["video"]["height"] music_url = video_json["item_list"][0]["music"]["play_url"]["uri"] url = "https://aweme.snssdk.com/aweme/v1/play/?video_id="+get_id+"&line=0" response = requests.get(url, headers='') # 可填入自己的headers url = response.url random_value = str(int(time.time())) mkdir(str(get_id)+"_"+random_value) chdir(str(get_id)+"_"+random_value) mkdir("video") chdir("video") save = str(get_id)+".mp4" down = downloader(url, 12, save) down.main() chdir("../") mkdir("music") chdir("music") url = music_url response = requests.get(url, headers='') # 可填入自己的headers url = response.url save = str(get_id)+".mp3" down = downloader(url, 12, save) down.main() chdir("../") chdir("video") old_video = get_id+".mp4" new_video = get_id+"_nosound.mp4" video = VideoFileClip(old_video) video = video.without_audio() # 删除声音,返回新的视频对象,原有对象不更改 video.write_videofile(new_video)
28.470149
100
0.597641
from moviepy.editor import * from os import chdir, getcwd, mkdir from random import randint import sys import requests from concurrent.futures import ThreadPoolExecutor from requests import get, head import time THREAD_NUM=12 HEADER=" " class downloader: def __init__(self, url, num, name): self.url = url self.num = num self.name = name self.getsize = 0 r = head(self.url, allow_redirects=True) self.size = int(r.headers['Content-Length']) def down(self, start, end, chunk_size=10240): headers = {'range': f'bytes={start}-{end}'} r = get(self.url, headers=headers, stream=True) with open(self.name, "rb+") as f: f.seek(start) for chunk in r.iter_content(chunk_size): f.write(chunk) self.getsize += chunk_size def main(self): start_time = time.time() f = open(self.name, 'wb') f.truncate(self.size) f.close() tp = ThreadPoolExecutor(max_workers=self.num) futures = [] start = 0 for i in range(self.num): end = int((i+1)/self.num*self.size) future = tp.submit(self.down, start, end) futures.append(future) start = end+1 while True: process = self.getsize/self.size*100 last = self.getsize time.sleep(1) curr = self.getsize down = (curr-last)/1024 if down > 1024: speed = f'{down/1024:6.2f}MB/s' else: speed = f'{down:6.2f}KB/s' print(f'process: {process:6.2f}% | speed: {speed}', end='\r') if process >= 100: print(f'process: {100.00:6}% | speed: 00.00KB/s', end=' | ') break tp.shutdown() end_time = time.time() total_time = end_time-start_time average_speed = self.size/total_time/1024/1024 print( f'total-time: {total_time:.0f}s | average-speed: {average_speed:.2f}MB/s') DOWNMUSIC = True url = input("url:") video_id = url.split("/") video_id = video_id[len(video_id)-1] try: int(video_id) except: print("dy-get [error] 获取video_id失败!") sys.exit(1) response = requests.get('https://www.douyin.com/web/api/v2/aweme/iteminfo/?item_ids='+str(video_id), headers='') try: video_json = response.json() except: print("dy-get [error] 获取json失败!") sys.exit(1) try: get_id = video_json["item_list"][0]["video"]["vid"] except: print("dy-get [error] 获取vid失败!") sys.exit(1) picture = video_json["item_list"][0]["video"]["ratio"] width = video_json["item_list"][0]["video"]["width"] height = video_json["item_list"][0]["video"]["height"] music_url = video_json["item_list"][0]["music"]["play_url"]["uri"] url = "https://aweme.snssdk.com/aweme/v1/play/?video_id="+get_id+"&line=0" response = requests.get(url, headers='') url = response.url random_value = str(int(time.time())) mkdir(str(get_id)+"_"+random_value) chdir(str(get_id)+"_"+random_value) mkdir("video") chdir("video") save = str(get_id)+".mp4" down = downloader(url, 12, save) down.main() chdir("../") mkdir("music") chdir("music") url = music_url response = requests.get(url, headers='') url = response.url save = str(get_id)+".mp3" down = downloader(url, 12, save) down.main() chdir("../") chdir("video") old_video = get_id+".mp4" new_video = get_id+"_nosound.mp4" video = VideoFileClip(old_video) video = video.without_audio() video.write_videofile(new_video)
true
true
f710e59b79ce144a6b83f278253f4474c45ed44c
1,067
py
Python
piquasso/_math/permanent.py
antalszava/piquasso
7ebff83145cfab44929114437c250852dff5f9a5
[ "Apache-2.0" ]
12
2021-09-12T15:51:45.000Z
2022-03-05T22:25:47.000Z
piquasso/_math/permanent.py
antalszava/piquasso
7ebff83145cfab44929114437c250852dff5f9a5
[ "Apache-2.0" ]
36
2021-09-13T08:01:27.000Z
2022-03-21T11:53:30.000Z
piquasso/_math/permanent.py
antalszava/piquasso
7ebff83145cfab44929114437c250852dff5f9a5
[ "Apache-2.0" ]
null
null
null
# # Copyright 2021 Budapest Quantum Computing Group # # 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 theboss.boson_sampling_utilities.permanent_calculators.glynn_gray_permanent_calculator import ( # noqa: E501 GlynnGrayPermanentCalculator, ) def _permanent(matrix, rows, columns, calculator_class): calculator = calculator_class(matrix, rows, columns) return calculator.compute_permanent() def glynn_gray_permanent(matrix, rows, columns): return _permanent( matrix, rows, columns, calculator_class=GlynnGrayPermanentCalculator )
33.34375
114
0.774133
from theboss.boson_sampling_utilities.permanent_calculators.glynn_gray_permanent_calculator import ( GlynnGrayPermanentCalculator, ) def _permanent(matrix, rows, columns, calculator_class): calculator = calculator_class(matrix, rows, columns) return calculator.compute_permanent() def glynn_gray_permanent(matrix, rows, columns): return _permanent( matrix, rows, columns, calculator_class=GlynnGrayPermanentCalculator )
true
true
f710e5daa7c9cafa194bdd85305f0273e762ebd7
5,647
py
Python
pipeline/recon/helpers.py
ponderng/recon-pipeline
11d09902c54969af47731b8e235e447806246004
[ "MIT" ]
null
null
null
pipeline/recon/helpers.py
ponderng/recon-pipeline
11d09902c54969af47731b8e235e447806246004
[ "MIT" ]
null
null
null
pipeline/recon/helpers.py
ponderng/recon-pipeline
11d09902c54969af47731b8e235e447806246004
[ "MIT" ]
null
null
null
import sys import pickle import typing import inspect import pkgutil import importlib import ipaddress import json import re from pathlib import Path from cmd2.ansi import style from collections import defaultdict from ..recon.config import defaults def meets_requirements(requirements, exception): """ Determine if tools required to perform task are installed. """ tools = get_tool_state() for tool in requirements: if not tools.get(tool).get("installed"): if exception: raise RuntimeError( style(f"[!!] {tool} is not installed, and is required to run this scan", fg="bright_red") ) else: return False return True def get_tool_state() -> typing.Union[dict, None]: """ Load current tool state from disk. """ tools = Path(defaults.get("tools-dir")) / ".tool-dict.pkl" if tools.exists(): return pickle.loads(tools.read_bytes()) def get_scans(): """ Iterates over the recon package and its modules to find all of the classes that end in [Ss]can. **A contract exists here that says any scans need to end with the word scan in order to be found by this function.** Example: ``defaultdict(<class 'list'>, {'AmassScan': ['pipeline.recon.amass'], 'MasscanScan': ['pipeline.recon.masscan'], ... })`` Returns: dict containing mapping of ``classname -> [modulename, ...]`` for all potential recon-pipeline commands """ scans = defaultdict(list) file = Path(__file__).expanduser().resolve() web = file.parent / "web" recon = file.parents[1] / "recon" lib_paths = [str(web), str(recon)] # recursively walk packages; import each module in each package # walk_packages yields ModuleInfo objects for all modules recursively on path # prefix is a string to output on the front of every module name on output. for loader, module_name, is_pkg in pkgutil.walk_packages(path=lib_paths, prefix=f"{__package__}."): try: importlib.import_module(module_name) except ModuleNotFoundError: # skipping things like recon.aquatone, not entirely sure why they're showing up... pass # walk all modules, grabbing classes that we've written and add them to the classlist defaultdict # getmembers returns all members of an object in a list of tuples (name, value) for name, obj in inspect.getmembers(sys.modules[__package__]): if inspect.ismodule(obj) and not name.startswith("_"): # we're only interested in modules that don't begin with _ i.e. magic methods __len__ etc... for sub_name, sub_obj in inspect.getmembers(obj): # now we only care about classes that end in [Ss]can if inspect.isclass(sub_obj) and sub_name.lower().endswith("scan"): # final check, this ensures that the tools necessary to AT LEAST run this scan are present # does not consider upstream dependencies try: requirements = sub_obj.requirements exception = False # let meets_req know we want boolean result if not meets_requirements(requirements, exception): continue except AttributeError: # some scan's haven't implemented meets_requirements yet, silently allow them through pass scans[sub_name].append(f"{__package__}.{name}") return scans def is_ip_address(ipaddr): """ Simple helper to determine if given string is an ip address or subnet """ try: ipaddress.ip_interface(ipaddr) return True except ValueError: return False def get_ip_address_version(ipaddr): """ Simple helper to determine whether a given ip address is ipv4 or ipv6 """ if is_ip_address(ipaddr): if isinstance(ipaddress.ip_address(ipaddr), ipaddress.IPv4Address): # ipv4 addr return "4" elif isinstance(ipaddress.ip_address(ipaddr), ipaddress.IPv6Address): # ipv6 return "6" def is_inscope(hostname, scope_file): """ Check given hostname against scope file and return True if it is """ # Use an default-allow rule, # so if there is no match in "include" or "exclude", it is within scope in_scope = True if scope_file == "": return in_scope # Load Scope file with open(scope_file, "r") as f: scope = json.load(f) # parse json data for block in scope['target']['scope']['exclude']: # Does URL match an excluded hostname? if re.search(block['host'], hostname): # If so, check for a more specific allow entry for allow in scope['target']['scope']['include']: # remove special chars in allow entry to make a domain name allow_n = allow['host'].replace('\\', '').replace('^', '').replace('$', '') # test the block entry against the normalized domain name if re.search(block['host'], allow_n): # if the allowed domain name fits in the block domain entry # , then it must be more specific. # Test URL against the allow entry if re.search(allow['host'], hostname): # If it matches, mark as true in_scope = True else: in_scope = False else: in_scope = False return in_scope
38.155405
129
0.613777
import sys import pickle import typing import inspect import pkgutil import importlib import ipaddress import json import re from pathlib import Path from cmd2.ansi import style from collections import defaultdict from ..recon.config import defaults def meets_requirements(requirements, exception): tools = get_tool_state() for tool in requirements: if not tools.get(tool).get("installed"): if exception: raise RuntimeError( style(f"[!!] {tool} is not installed, and is required to run this scan", fg="bright_red") ) else: return False return True def get_tool_state() -> typing.Union[dict, None]: tools = Path(defaults.get("tools-dir")) / ".tool-dict.pkl" if tools.exists(): return pickle.loads(tools.read_bytes()) def get_scans(): scans = defaultdict(list) file = Path(__file__).expanduser().resolve() web = file.parent / "web" recon = file.parents[1] / "recon" lib_paths = [str(web), str(recon)] for loader, module_name, is_pkg in pkgutil.walk_packages(path=lib_paths, prefix=f"{__package__}."): try: importlib.import_module(module_name) except ModuleNotFoundError: pass # walk all modules, grabbing classes that we've written and add them to the classlist defaultdict for name, obj in inspect.getmembers(sys.modules[__package__]): if inspect.ismodule(obj) and not name.startswith("_"): for sub_name, sub_obj in inspect.getmembers(obj): if inspect.isclass(sub_obj) and sub_name.lower().endswith("scan"): try: requirements = sub_obj.requirements exception = False if not meets_requirements(requirements, exception): continue except AttributeError: pass scans[sub_name].append(f"{__package__}.{name}") return scans def is_ip_address(ipaddr): try: ipaddress.ip_interface(ipaddr) return True except ValueError: return False def get_ip_address_version(ipaddr): if is_ip_address(ipaddr): if isinstance(ipaddress.ip_address(ipaddr), ipaddress.IPv4Address): return "4" elif isinstance(ipaddress.ip_address(ipaddr), ipaddress.IPv6Address): return "6" def is_inscope(hostname, scope_file): in_scope = True if scope_file == "": return in_scope with open(scope_file, "r") as f: scope = json.load(f) for block in scope['target']['scope']['exclude']: if re.search(block['host'], hostname): for allow in scope['target']['scope']['include']: allow_n = allow['host'].replace('\\', '').replace('^', '').replace('$', '') if re.search(block['host'], allow_n): if re.search(allow['host'], hostname): in_scope = True else: in_scope = False else: in_scope = False return in_scope
true
true
f710e627aa4d7866c5fe99d277395b7e63de88da
2,126
py
Python
tests/test_decorators.py
matibek/request_limiter
56d8208d48a7d4a825de170c79b58ae5006101dc
[ "MIT" ]
1
2020-01-21T08:46:37.000Z
2020-01-21T08:46:37.000Z
tests/test_decorators.py
matibek/request_limiter
56d8208d48a7d4a825de170c79b58ae5006101dc
[ "MIT" ]
5
2020-06-05T20:29:43.000Z
2021-06-04T22:17:55.000Z
tests/test_decorators.py
matibek/request_limiter
56d8208d48a7d4a825de170c79b58ae5006101dc
[ "MIT" ]
null
null
null
import os import unittest from typing import Optional from django.http import HttpResponse from django.test import RequestFactory from request_limiter import request_limiter, LimitedIntervalStrategy, \ LimitStrategy, LimitException, django_request_limiter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_settings') req_factory = RequestFactory() class MockStrategy(LimitStrategy): def __init__(self, allow: bool): self._allow = allow def allow(self, key: Optional[str] = None) -> bool: return self._allow def get_remaining(self, key: Optional[str] = None) -> float: return 1 def clean(self): pass class TestRequestLimiterDecorator(unittest.TestCase): def test_when_strategy_not_given_uses_limited_interval_strategy(self): limiter = request_limiter() self.assertTrue(isinstance(limiter.strategy, LimitedIntervalStrategy)) def test_when_strategy_allows_invokes_function(self): @request_limiter(strategy=MockStrategy(allow=True)) def test_func() -> bool: return True self.assertTrue(test_func()) def test_when_strategy_denies_raises_exception(self): @request_limiter(strategy=MockStrategy(allow=False)) def test_func() -> bool: return True self.assertRaises(LimitException, test_func) class TestDjangoRequestLimiter(unittest.TestCase): def test_limits_based_on_ip(self): @django_request_limiter @request_limiter(strategy=LimitedIntervalStrategy(requests=1)) def test_view(request): return True res1 = test_view(req_factory.post('/test/', REMOTE_ADDR='127.0.0.1')) assert res1, 'Expected first request to work' res2 = test_view(req_factory.post('/test/', REMOTE_ADDR='127.0.0.1')) assert isinstance(res2, HttpResponse), 'Expected limit http response' assert res2.status_code == 429, 'Expected 429 response code' # change Ip res3 = test_view(req_factory.post('/test/', REMOTE_ADDR='127.0.0.2')) assert res3, 'Expected different ip request to work'
31.264706
78
0.707902
import os import unittest from typing import Optional from django.http import HttpResponse from django.test import RequestFactory from request_limiter import request_limiter, LimitedIntervalStrategy, \ LimitStrategy, LimitException, django_request_limiter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_settings') req_factory = RequestFactory() class MockStrategy(LimitStrategy): def __init__(self, allow: bool): self._allow = allow def allow(self, key: Optional[str] = None) -> bool: return self._allow def get_remaining(self, key: Optional[str] = None) -> float: return 1 def clean(self): pass class TestRequestLimiterDecorator(unittest.TestCase): def test_when_strategy_not_given_uses_limited_interval_strategy(self): limiter = request_limiter() self.assertTrue(isinstance(limiter.strategy, LimitedIntervalStrategy)) def test_when_strategy_allows_invokes_function(self): @request_limiter(strategy=MockStrategy(allow=True)) def test_func() -> bool: return True self.assertTrue(test_func()) def test_when_strategy_denies_raises_exception(self): @request_limiter(strategy=MockStrategy(allow=False)) def test_func() -> bool: return True self.assertRaises(LimitException, test_func) class TestDjangoRequestLimiter(unittest.TestCase): def test_limits_based_on_ip(self): @django_request_limiter @request_limiter(strategy=LimitedIntervalStrategy(requests=1)) def test_view(request): return True res1 = test_view(req_factory.post('/test/', REMOTE_ADDR='127.0.0.1')) assert res1, 'Expected first request to work' res2 = test_view(req_factory.post('/test/', REMOTE_ADDR='127.0.0.1')) assert isinstance(res2, HttpResponse), 'Expected limit http response' assert res2.status_code == 429, 'Expected 429 response code' res3 = test_view(req_factory.post('/test/', REMOTE_ADDR='127.0.0.2')) assert res3, 'Expected different ip request to work'
true
true
f710e635254e2e0650c360f0940bd529576ce4a8
2,098
py
Python
siliconcompiler/targets/freepdk45_demo.py
siliconcompiler/siliconcompiler
6aa2b53441608f228bd520b68c0324fc9cf96377
[ "Apache-2.0" ]
424
2021-12-04T15:45:12.000Z
2022-03-31T20:27:55.000Z
siliconcompiler/targets/freepdk45_demo.py
siliconcompiler/siliconcompiler
6aa2b53441608f228bd520b68c0324fc9cf96377
[ "Apache-2.0" ]
105
2021-12-03T21:25:29.000Z
2022-03-31T22:36:59.000Z
siliconcompiler/targets/freepdk45_demo.py
siliconcompiler/siliconcompiler
6aa2b53441608f228bd520b68c0324fc9cf96377
[ "Apache-2.0" ]
38
2021-12-04T21:26:20.000Z
2022-03-21T02:39:29.000Z
import siliconcompiler ############################################################################ # DOCS ############################################################################ def make_docs(): ''' Demonstration target for compiling ASICs with FreePDK45 and the open-source asicflow. ''' chip = siliconcompiler.Chip('<design>') setup(chip) return chip #################################################### # PDK Setup #################################################### def setup(chip): ''' Target setup ''' #0. Defining the project chip.set('option', 'target', 'freepdk45_demo') #1. Setting to ASIC mode chip.set('option', 'mode','asic') #2. Load PDK, flow, libs combo chip.load_pdk('freepdk45') chip.load_flow('lintflow') chip.load_flow('asicflow') chip.load_flow('asictopflow') chip.load_lib('nangate45') #3. Set flow and pdk chip.set('option', 'flow', 'asicflow', clobber=False) chip.set('option', 'pdk', 'freepdk45') #4. Select libraries chip.set('asic', 'logiclib', 'nangate45') #5. Set project specific design choices chip.set('asic', 'stackup', '10M') chip.set('asic', 'delaymodel', 'nldm') chip.set('asic', 'minlayer', "m1") chip.set('asic', 'maxlayer', "m10") chip.set('asic', 'maxfanout', 64) chip.set('asic', 'maxlength', 1000) chip.set('asic', 'maxslew', 0.2e-9) chip.set('asic', 'maxcap', 0.2e-12) chip.set('asic', 'rclayer', 'clk', "m5") chip.set('asic', 'rclayer', 'data',"m3") chip.set('asic', 'hpinlayer', "m3") chip.set('asic', 'vpinlayer', "m2") chip.set('asic', 'density', 10) chip.set('asic', 'aspectratio', 1) chip.set('asic', 'coremargin', 1.9) #6. Timing corners corner = 'typical' chip.set('constraint','worst','libcorner', corner) chip.set('constraint','worst','pexcorner', corner) chip.set('constraint','worst','mode', 'func') chip.set('constraint','worst','check', ['setup','hold']) ######################### if __name__ == "__main__": chip = make_docs()
27.973333
79
0.521926
import siliconcompiler
true
true
f710e6c669d322132e2dcb4843a6941ea5ad37e6
692
py
Python
docs/src/path_operation_configuration/tutorial005.py
kabirkhan/fastapi
9ca72f4ea1fc6f04b7d8d4e2f3c4d7da5f6c322e
[ "MIT" ]
3
2019-03-15T02:44:48.000Z
2020-03-14T15:42:52.000Z
docs/src/path_operation_configuration/tutorial005.py
kabirkhan/fastapi
9ca72f4ea1fc6f04b7d8d4e2f3c4d7da5f6c322e
[ "MIT" ]
null
null
null
docs/src/path_operation_configuration/tutorial005.py
kabirkhan/fastapi
9ca72f4ea1fc6f04b7d8d4e2f3c4d7da5f6c322e
[ "MIT" ]
null
null
null
from typing import Set from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str = None price: float tax: float = None tags: Set[str] = [] @app.post( "/items/", response_model=Item, summary="Create an item", response_description="The created item", ) async def create_item(*, item: Item): """ Create an item with all the information: * name: each item must have a name * description: a long description * price: required * tax: if the item doesn't have tax, you can omit this * tags: a set of unique tag strings for this item """ return item
20.352941
58
0.648844
from typing import Set from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str = None price: float tax: float = None tags: Set[str] = [] @app.post( "/items/", response_model=Item, summary="Create an item", response_description="The created item", ) async def create_item(*, item: Item): return item
true
true
f710e71139bfd217a3c3797b5fac1bf60fb7b9ba
2,446
py
Python
util/flowerapiclient.py
E-ARK-Software/earkweb
6b30abf776950bbfffcf4a5a75d10d869a386941
[ "MIT" ]
4
2019-12-19T17:17:42.000Z
2021-12-11T23:12:45.000Z
util/flowerapiclient.py
E-ARK-Software/earkweb
6b30abf776950bbfffcf4a5a75d10d869a386941
[ "MIT" ]
32
2020-03-19T15:56:05.000Z
2021-12-23T12:46:06.000Z
util/flowerapiclient.py
E-ARK-Software/earkweb
6b30abf776950bbfffcf4a5a75d10d869a386941
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding=UTF-8 import requests import json import datetime from config.configuration import flower_path, flower_port, flower_server_external, verify_certificate, \ flower_server_internal def get_task_info(task_id): flower_request_url = 'http://%s:%s%sapi/tasks' % (flower_server_internal, flower_port, flower_path) print(flower_request_url) response = requests.get(flower_request_url, verify=verify_certificate, headers={'Connection': 'close'}) tasks_json = json.loads(response.text) print(tasks_json) task_json = tasks_json[task_id] task_name = task_json['name'] task_runtime = None if 'runtime' in task_json and isinstance(task_json['runtime'], int): task_runtime = round(task_json['runtime'], 2) process_id = None if 'args' in task_json: from ast import literal_eval tpl = literal_eval(task_json["args"]) if isinstance(tpl[0], dict): js = tpl[0] else: js = json.loads(tpl[0]) process_id = js["process_id"] task_received = datetime.datetime.fromtimestamp(int(task_json['received'])).strftime('%Y-%m-%d %H:%M:%S') task_info = { "name": task_name, "received": task_received, } if task_runtime: task_info["runtime"] = task_runtime if process_id: task_info["process_id"] = process_id return task_info def get_task_list(task_id, exclude_tasks:list=None): flower_request_url = 'http://%s:%s%sapi/tasks' % (flower_server_internal, flower_port, flower_path) response = requests.get(flower_request_url, verify=verify_certificate, headers={'Connection': 'close'}) tasks_json = json.loads(response.text) task_ids = [] if task_id in tasks_json: def find_tasks(t_id): t_info = tasks_json[t_id] if 'children' in t_info: for child_task in t_info['children']: if exclude_tasks and tasks_json[child_task]['name'] not in exclude_tasks: task_ids.append(child_task) find_tasks(child_task) find_tasks(task_id) else: raise ValueError("Task not found: %s" % task_id) return [tasks_json[tid] for tid in task_ids] if __name__ == '__main__': tl = get_task_list('b6791fd7-d7df-41c3-916b-ec046fe15a59', ['file_migration']) print(len(tl)) for t in tl: print(t)
34.450704
109
0.650859
import requests import json import datetime from config.configuration import flower_path, flower_port, flower_server_external, verify_certificate, \ flower_server_internal def get_task_info(task_id): flower_request_url = 'http://%s:%s%sapi/tasks' % (flower_server_internal, flower_port, flower_path) print(flower_request_url) response = requests.get(flower_request_url, verify=verify_certificate, headers={'Connection': 'close'}) tasks_json = json.loads(response.text) print(tasks_json) task_json = tasks_json[task_id] task_name = task_json['name'] task_runtime = None if 'runtime' in task_json and isinstance(task_json['runtime'], int): task_runtime = round(task_json['runtime'], 2) process_id = None if 'args' in task_json: from ast import literal_eval tpl = literal_eval(task_json["args"]) if isinstance(tpl[0], dict): js = tpl[0] else: js = json.loads(tpl[0]) process_id = js["process_id"] task_received = datetime.datetime.fromtimestamp(int(task_json['received'])).strftime('%Y-%m-%d %H:%M:%S') task_info = { "name": task_name, "received": task_received, } if task_runtime: task_info["runtime"] = task_runtime if process_id: task_info["process_id"] = process_id return task_info def get_task_list(task_id, exclude_tasks:list=None): flower_request_url = 'http://%s:%s%sapi/tasks' % (flower_server_internal, flower_port, flower_path) response = requests.get(flower_request_url, verify=verify_certificate, headers={'Connection': 'close'}) tasks_json = json.loads(response.text) task_ids = [] if task_id in tasks_json: def find_tasks(t_id): t_info = tasks_json[t_id] if 'children' in t_info: for child_task in t_info['children']: if exclude_tasks and tasks_json[child_task]['name'] not in exclude_tasks: task_ids.append(child_task) find_tasks(child_task) find_tasks(task_id) else: raise ValueError("Task not found: %s" % task_id) return [tasks_json[tid] for tid in task_ids] if __name__ == '__main__': tl = get_task_list('b6791fd7-d7df-41c3-916b-ec046fe15a59', ['file_migration']) print(len(tl)) for t in tl: print(t)
true
true
f710e73434b5020f06243314999148df6c19f73a
6,783
py
Python
celery/tests/test_app/test_log.py
amplify-education/celery
3ea8824d9bdb6c5928701cf8466287d4259aa0e0
[ "BSD-3-Clause" ]
null
null
null
celery/tests/test_app/test_log.py
amplify-education/celery
3ea8824d9bdb6c5928701cf8466287d4259aa0e0
[ "BSD-3-Clause" ]
null
null
null
celery/tests/test_app/test_log.py
amplify-education/celery
3ea8824d9bdb6c5928701cf8466287d4259aa0e0
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from __future__ import with_statement import sys import logging from tempfile import mktemp from celery import log from celery.log import (setup_logger, setup_task_logger, get_default_logger, get_task_logger, redirect_stdouts_to_logger, LoggingProxy, setup_logging_subsystem) from celery.utils import uuid from celery.utils.compat import _CompatLoggerAdapter from celery.tests.utils import unittest from celery.tests.utils import (override_stdouts, wrap_logger, get_handlers, set_handlers) class test_default_logger(unittest.TestCase): def setUp(self): self.setup_logger = setup_logger self.get_logger = get_default_logger log._setup = False def test_setup_logging_subsystem_colorize(self): setup_logging_subsystem(colorize=None) setup_logging_subsystem(colorize=True) def test_setup_logging_subsystem_no_mputil(self): mputil, log.mputil = log.mputil, None log.mputil try: log.setup_logging_subsystem() finally: log.mputil = mputil def _assertLog(self, logger, logmsg, loglevel=logging.ERROR): with wrap_logger(logger, loglevel=loglevel) as sio: logger.log(loglevel, logmsg) return sio.getvalue().strip() def assertDidLogTrue(self, logger, logmsg, reason, loglevel=None): val = self._assertLog(logger, logmsg, loglevel=loglevel) return self.assertEqual(val, logmsg, reason) def assertDidLogFalse(self, logger, logmsg, reason, loglevel=None): val = self._assertLog(logger, logmsg, loglevel=loglevel) return self.assertFalse(val, reason) def test_setup_logger(self): logger = self.setup_logger(loglevel=logging.ERROR, logfile=None, root=False, colorize=True) set_handlers(logger, []) logger = self.setup_logger(loglevel=logging.ERROR, logfile=None, root=False, colorize=None) self.assertIs(get_handlers(logger)[0].stream, sys.__stderr__, "setup_logger logs to stderr without logfile argument.") self.assertDidLogFalse(logger, "Logging something", "Logger doesn't info when loglevel is ERROR", loglevel=logging.INFO) def test_setup_logger_no_handlers_stream(self): l = self.get_logger() set_handlers(l, []) with override_stdouts() as outs: stdout, stderr = outs l = self.setup_logger(logfile=stderr, loglevel=logging.INFO, root=False) l.info("The quick brown fox...") self.assertIn("The quick brown fox...", stderr.getvalue()) def test_setup_logger_no_handlers_file(self): l = self.get_logger() set_handlers(l, []) tempfile = mktemp(suffix="unittest", prefix="celery") l = self.setup_logger(logfile=tempfile, loglevel=0, root=False) self.assertIsInstance(get_handlers(l)[0], logging.FileHandler) def test_redirect_stdouts(self): logger = self.setup_logger(loglevel=logging.ERROR, logfile=None, root=False) try: with wrap_logger(logger) as sio: redirect_stdouts_to_logger(logger, loglevel=logging.ERROR) logger.error("foo") self.assertIn("foo", sio.getvalue()) finally: sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__ def test_logging_proxy(self): logger = self.setup_logger(loglevel=logging.ERROR, logfile=None, root=False) with wrap_logger(logger) as sio: p = LoggingProxy(logger, loglevel=logging.ERROR) p.close() p.write("foo") self.assertNotIn("foo", sio.getvalue()) p.closed = False p.write("foo") self.assertIn("foo", sio.getvalue()) lines = ["baz", "xuzzy"] p.writelines(lines) for line in lines: self.assertIn(line, sio.getvalue()) p.flush() p.close() self.assertFalse(p.isatty()) self.assertIsNone(p.fileno()) class test_task_logger(test_default_logger): def setUp(self): logger = get_task_logger() logger.handlers = [] logging.root.manager.loggerDict.pop(logger.name, None) self.uid = uuid() def setup_logger(self, *args, **kwargs): return setup_task_logger(*args, **dict(kwargs, task_name=self.uid, task_id=self.uid)) def get_logger(self, *args, **kwargs): return get_task_logger(*args, **dict(kwargs, name=self.uid)) class MockLogger(logging.Logger): _records = None def __init__(self, *args, **kwargs): self._records = [] logging.Logger.__init__(self, *args, **kwargs) def handle(self, record): self._records.append(record) def isEnabledFor(self, level): return True class test_CompatLoggerAdapter(unittest.TestCase): levels = ("debug", "info", "warn", "warning", "error", "fatal", "critical") def setUp(self): self.logger, self.adapter = self.createAdapter() def createAdapter(self, name=None, extra={"foo": "bar"}): logger = MockLogger(name=name or uuid()) return logger, _CompatLoggerAdapter(logger, extra) def test_levels(self): for level in self.levels: msg = "foo bar %s" % (level, ) logger, adapter = self.createAdapter() getattr(adapter, level)(msg) self.assertEqual(logger._records[0].msg, msg) def test_exception(self): try: raise KeyError("foo") except KeyError: self.adapter.exception("foo bar exception") self.assertEqual(self.logger._records[0].msg, "foo bar exception") def test_setLevel(self): self.adapter.setLevel(logging.INFO) self.assertEqual(self.logger.level, logging.INFO) def test_process(self): msg, kwargs = self.adapter.process("foo bar baz", {"exc_info": 1}) self.assertDictEqual(kwargs, {"exc_info": 1, "extra": {"foo": "bar"}}) def test_add_remove_handlers(self): handler = logging.StreamHandler() self.adapter.addHandler(handler) self.assertIs(self.logger.handlers[0], handler) self.adapter.removeHandler(handler) self.assertListEqual(self.logger.handlers, [])
35.7
74
0.606959
from __future__ import absolute_import from __future__ import with_statement import sys import logging from tempfile import mktemp from celery import log from celery.log import (setup_logger, setup_task_logger, get_default_logger, get_task_logger, redirect_stdouts_to_logger, LoggingProxy, setup_logging_subsystem) from celery.utils import uuid from celery.utils.compat import _CompatLoggerAdapter from celery.tests.utils import unittest from celery.tests.utils import (override_stdouts, wrap_logger, get_handlers, set_handlers) class test_default_logger(unittest.TestCase): def setUp(self): self.setup_logger = setup_logger self.get_logger = get_default_logger log._setup = False def test_setup_logging_subsystem_colorize(self): setup_logging_subsystem(colorize=None) setup_logging_subsystem(colorize=True) def test_setup_logging_subsystem_no_mputil(self): mputil, log.mputil = log.mputil, None log.mputil try: log.setup_logging_subsystem() finally: log.mputil = mputil def _assertLog(self, logger, logmsg, loglevel=logging.ERROR): with wrap_logger(logger, loglevel=loglevel) as sio: logger.log(loglevel, logmsg) return sio.getvalue().strip() def assertDidLogTrue(self, logger, logmsg, reason, loglevel=None): val = self._assertLog(logger, logmsg, loglevel=loglevel) return self.assertEqual(val, logmsg, reason) def assertDidLogFalse(self, logger, logmsg, reason, loglevel=None): val = self._assertLog(logger, logmsg, loglevel=loglevel) return self.assertFalse(val, reason) def test_setup_logger(self): logger = self.setup_logger(loglevel=logging.ERROR, logfile=None, root=False, colorize=True) set_handlers(logger, []) logger = self.setup_logger(loglevel=logging.ERROR, logfile=None, root=False, colorize=None) self.assertIs(get_handlers(logger)[0].stream, sys.__stderr__, "setup_logger logs to stderr without logfile argument.") self.assertDidLogFalse(logger, "Logging something", "Logger doesn't info when loglevel is ERROR", loglevel=logging.INFO) def test_setup_logger_no_handlers_stream(self): l = self.get_logger() set_handlers(l, []) with override_stdouts() as outs: stdout, stderr = outs l = self.setup_logger(logfile=stderr, loglevel=logging.INFO, root=False) l.info("The quick brown fox...") self.assertIn("The quick brown fox...", stderr.getvalue()) def test_setup_logger_no_handlers_file(self): l = self.get_logger() set_handlers(l, []) tempfile = mktemp(suffix="unittest", prefix="celery") l = self.setup_logger(logfile=tempfile, loglevel=0, root=False) self.assertIsInstance(get_handlers(l)[0], logging.FileHandler) def test_redirect_stdouts(self): logger = self.setup_logger(loglevel=logging.ERROR, logfile=None, root=False) try: with wrap_logger(logger) as sio: redirect_stdouts_to_logger(logger, loglevel=logging.ERROR) logger.error("foo") self.assertIn("foo", sio.getvalue()) finally: sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__ def test_logging_proxy(self): logger = self.setup_logger(loglevel=logging.ERROR, logfile=None, root=False) with wrap_logger(logger) as sio: p = LoggingProxy(logger, loglevel=logging.ERROR) p.close() p.write("foo") self.assertNotIn("foo", sio.getvalue()) p.closed = False p.write("foo") self.assertIn("foo", sio.getvalue()) lines = ["baz", "xuzzy"] p.writelines(lines) for line in lines: self.assertIn(line, sio.getvalue()) p.flush() p.close() self.assertFalse(p.isatty()) self.assertIsNone(p.fileno()) class test_task_logger(test_default_logger): def setUp(self): logger = get_task_logger() logger.handlers = [] logging.root.manager.loggerDict.pop(logger.name, None) self.uid = uuid() def setup_logger(self, *args, **kwargs): return setup_task_logger(*args, **dict(kwargs, task_name=self.uid, task_id=self.uid)) def get_logger(self, *args, **kwargs): return get_task_logger(*args, **dict(kwargs, name=self.uid)) class MockLogger(logging.Logger): _records = None def __init__(self, *args, **kwargs): self._records = [] logging.Logger.__init__(self, *args, **kwargs) def handle(self, record): self._records.append(record) def isEnabledFor(self, level): return True class test_CompatLoggerAdapter(unittest.TestCase): levels = ("debug", "info", "warn", "warning", "error", "fatal", "critical") def setUp(self): self.logger, self.adapter = self.createAdapter() def createAdapter(self, name=None, extra={"foo": "bar"}): logger = MockLogger(name=name or uuid()) return logger, _CompatLoggerAdapter(logger, extra) def test_levels(self): for level in self.levels: msg = "foo bar %s" % (level, ) logger, adapter = self.createAdapter() getattr(adapter, level)(msg) self.assertEqual(logger._records[0].msg, msg) def test_exception(self): try: raise KeyError("foo") except KeyError: self.adapter.exception("foo bar exception") self.assertEqual(self.logger._records[0].msg, "foo bar exception") def test_setLevel(self): self.adapter.setLevel(logging.INFO) self.assertEqual(self.logger.level, logging.INFO) def test_process(self): msg, kwargs = self.adapter.process("foo bar baz", {"exc_info": 1}) self.assertDictEqual(kwargs, {"exc_info": 1, "extra": {"foo": "bar"}}) def test_add_remove_handlers(self): handler = logging.StreamHandler() self.adapter.addHandler(handler) self.assertIs(self.logger.handlers[0], handler) self.adapter.removeHandler(handler) self.assertListEqual(self.logger.handlers, [])
true
true
f710e7cc0a55f576ed3976d40a305404c5bb7c1a
290
py
Python
app/handlers/housekeeping/edit_group.py
jamestiotio/wthslack
4ada5e2354bfd9ffd46731abe35b65ef8a09d4f1
[ "MIT" ]
2
2020-07-10T21:06:53.000Z
2020-10-27T17:05:05.000Z
app/handlers/housekeeping/edit_group.py
wthdevelopers/wthslack
f6566e35b5455fcdfb12d9b33d65843b67aff17c
[ "MIT" ]
7
2020-02-09T12:08:00.000Z
2021-06-27T16:51:29.000Z
app/handlers/housekeeping/edit_group.py
jamestiotio/wthslack
4ada5e2354bfd9ffd46731abe35b65ef8a09d4f1
[ "MIT" ]
2
2020-02-07T15:35:24.000Z
2020-02-07T17:28:50.000Z
# coding: utf-8 # Modify a specific group entry in database # Created by James Raphael Tiovalen (2021) import slack import ast import settings import config from slackers.hooks import commands conv_db = config.conv_handler @commands.on("editgroup") def editgroup(payload): return
15.263158
43
0.772414
import slack import ast import settings import config from slackers.hooks import commands conv_db = config.conv_handler @commands.on("editgroup") def editgroup(payload): return
true
true
f710e823f2a52468b6bf8b0468de4cc58fdfd2fd
2,720
py
Python
demo_odometry.py
SimonsRoad/UnDeepVO
956598958e0dba4729a8af70ee7a4cdcc10f09ec
[ "MIT" ]
1
2018-07-16T12:15:29.000Z
2018-07-16T12:15:29.000Z
demo_odometry.py
SimonsRoad/UnDeepVO
956598958e0dba4729a8af70ee7a4cdcc10f09ec
[ "MIT" ]
null
null
null
demo_odometry.py
SimonsRoad/UnDeepVO
956598958e0dba4729a8af70ee7a4cdcc10f09ec
[ "MIT" ]
1
2018-10-15T12:39:51.000Z
2018-10-15T12:39:51.000Z
"""Example of pykitti.odometry usage.""" import itertools import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D import pykitti __author__ = "Lee Clement" __email__ = "lee.clement@robotics.utias.utoronto.ca" # Change this to the directory where you store KITTI data basedir = './data/dataset' # Specify the dataset to load sequence = '01' # Load the data. Optionally, specify the frame range to load. # Passing imformat='cv2' will convert images to uint8 and BGR for # easy use with OpenCV. # dataset = pykitti.odometry(basedir, sequence) dataset = pykitti.odometry(basedir, sequence, frames=range(0, 20, 5)) # dataset.calib: Calibration data are accessible as a named tuple # dataset.timestamps: Timestamps are parsed into a list of timedelta objects # dataset.poses: Generator to load ground truth poses T_w_cam0 # dataset.camN: Generator to load individual images from camera N # dataset.gray: Generator to load monochrome stereo pairs (cam0, cam1) # dataset.rgb: Generator to load RGB stereo pairs (cam2, cam3) # dataset.velo: Generator to load velodyne scans as [x,y,z,reflectance] # Grab some data second_pose = next(iter(itertools.islice(dataset.poses, 1, None))) first_gray = next(iter(dataset.gray)) first_cam1 = next(iter(dataset.cam1)) first_rgb = next(iter(dataset.rgb)) first_cam2 = next(iter(dataset.cam2)) third_velo = next(iter(itertools.islice(dataset.velo, 2, None))) # Display some of the data np.set_printoptions(precision=4, suppress=True) print('\nSequence: ' + str(dataset.sequence)) print('\nFrame range: ' + str(dataset.frames)) # print('\nGray stereo pair baseline [m]: ' + str(dataset.calib.b_gray)) print('\nRGB stereo pair baseline [m]: ' + str(dataset.calib.b_rgb)) print('\nFirst timestamp: ' + str(dataset.timestamps[0])) print('\nSecond ground truth pose:\n' + str(second_pose)) f, ax = plt.subplots(2, 2, figsize=(15, 5)) ax[0, 0].imshow(first_gray[0], cmap='gray') ax[0, 0].set_title('Left Gray Image (cam0)') ax[0, 1].imshow(first_cam1, cmap='gray') ax[0, 1].set_title('Right Gray Image (cam1)') ax[1, 0].imshow(first_cam2) ax[1, 0].set_title('Left RGB Image (cam2)') ax[1, 1].imshow(first_rgb[1]) ax[1, 1].set_title('Right RGB Image (cam3)') f2 = plt.figure() ax2 = f2.add_subplot(111, projection='3d') # Plot every 100th point so things don't get too bogged down velo_range = range(0, third_velo.shape[0], 10) ax2.scatter(third_velo[velo_range, 0], third_velo[velo_range, 1], third_velo[velo_range, 2], c=third_velo[velo_range, 3], cmap='gray', s=0.1) ax2.axis('equal') ax2.set_title('Third Velodyne scan (subsampled)') plt.show()
33.170732
77
0.711397
import itertools import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D import pykitti __author__ = "Lee Clement" __email__ = "lee.clement@robotics.utias.utoronto.ca" basedir = './data/dataset' sequence = '01' dataset = pykitti.odometry(basedir, sequence, frames=range(0, 20, 5)) second_pose = next(iter(itertools.islice(dataset.poses, 1, None))) first_gray = next(iter(dataset.gray)) first_cam1 = next(iter(dataset.cam1)) first_rgb = next(iter(dataset.rgb)) first_cam2 = next(iter(dataset.cam2)) third_velo = next(iter(itertools.islice(dataset.velo, 2, None))) np.set_printoptions(precision=4, suppress=True) print('\nSequence: ' + str(dataset.sequence)) print('\nFrame range: ' + str(dataset.frames)) print('\nRGB stereo pair baseline [m]: ' + str(dataset.calib.b_rgb)) print('\nFirst timestamp: ' + str(dataset.timestamps[0])) print('\nSecond ground truth pose:\n' + str(second_pose)) f, ax = plt.subplots(2, 2, figsize=(15, 5)) ax[0, 0].imshow(first_gray[0], cmap='gray') ax[0, 0].set_title('Left Gray Image (cam0)') ax[0, 1].imshow(first_cam1, cmap='gray') ax[0, 1].set_title('Right Gray Image (cam1)') ax[1, 0].imshow(first_cam2) ax[1, 0].set_title('Left RGB Image (cam2)') ax[1, 1].imshow(first_rgb[1]) ax[1, 1].set_title('Right RGB Image (cam3)') f2 = plt.figure() ax2 = f2.add_subplot(111, projection='3d') velo_range = range(0, third_velo.shape[0], 10) ax2.scatter(third_velo[velo_range, 0], third_velo[velo_range, 1], third_velo[velo_range, 2], c=third_velo[velo_range, 3], cmap='gray', s=0.1) ax2.axis('equal') ax2.set_title('Third Velodyne scan (subsampled)') plt.show()
true
true
f710e91c291039791cd1d0ecd77934ed50435b77
3,460
py
Python
gaussian_detection/data/dataset/CurrentDateset.py
PKQ1688/text_detection
e306b003f2e8eb9f8d07fc95d2d9def14fa8b38c
[ "Apache-2.0" ]
null
null
null
gaussian_detection/data/dataset/CurrentDateset.py
PKQ1688/text_detection
e306b003f2e8eb9f8d07fc95d2d9def14fa8b38c
[ "Apache-2.0" ]
null
null
null
gaussian_detection/data/dataset/CurrentDateset.py
PKQ1688/text_detection
e306b003f2e8eb9f8d07fc95d2d9def14fa8b38c
[ "Apache-2.0" ]
null
null
null
# -*- coding:utf-8 -*- # @author :adolf import os from data.data_utils import order_points_clockwise from data.data_aug import * from data.make_labels import * class CurrentOcrData(object): def __init__(self, root, pre_processes=None, transforms=None, filter_keys=None, ignore_tags=None, is_training=True): self.is_training = is_training self.root = root self.transforms = transforms self.pre_processes = pre_processes self.filter_key = filter_keys self.ignore_tags = ignore_tags self.aug = list() self.imgs = list(sorted(os.listdir(os.path.join(root, "imgs")))) self.gts = list(sorted(os.listdir(os.path.join(root, "gts")))) self.init_pre_process() def __len__(self): return len(self.imgs) # - 1 def __getitem__(self, item): img_path = os.path.join(self.root, 'imgs', self.imgs[item]) gt_path = os.path.join(self.root, 'gts', self.gts[item]) img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) targets = self.get_annotation(gt_path) targets['img'] = img targets['shape'] = [img.shape[0], img.shape[1]] targets = self.apply_pre_process(targets) if self.transforms is not None: targets['img'] = self.transforms(targets['img']) targets['text_polys'] = targets['text_polys'].tolist() if self.filter_key is not None and self.is_training: targets_dict = dict() for k, v in targets.items(): if k not in self.filter_key: targets_dict[k] = v return targets['img'], targets_dict else: return targets['img'], targets def get_annotation(self, gt_path): boxes = list() texts = list() ignores = list() with open(gt_path, encoding='utf-8', mode='r') as f: for line in f.readlines(): params = line.strip().strip('\ufeff').strip('\xef\xbb\xbf').split(',') # print(params) try: box = order_points_clockwise(np.array(list(map(float, params[:8]))).reshape(-1, 2)) # print(box) if cv2.contourArea(box) > 0: boxes.append(box) texts.append(params[8]) ignores.append(params[8] in self.ignore_tags) except Exception as e: print(e) print('get annotation is failed {}'.format(gt_path)) data = {'text_polys': np.array(boxes), 'texts': texts, 'ignore_tags': ignores} return data def init_pre_process(self): if self.pre_processes is not None: for aug in self.pre_processes: if 'args' not in aug: args = {} else: args = aug['args'] if isinstance(args, dict): cls = eval(aug['type'])(**args) else: cls = eval(aug['type'])(args) self.aug.append(cls) def apply_pre_process(self, data): for aug in self.aug: data = aug(data) return data if __name__ == '__main__': dataset = CurrentOcrData('/home/shizai/data2/ocr_data/rctw') dataset.get_annotation('/home/shizai/data2/ocr_data/rctw/gts/rctw_image_3629.txt')
34.257426
120
0.551156
import os from data.data_utils import order_points_clockwise from data.data_aug import * from data.make_labels import * class CurrentOcrData(object): def __init__(self, root, pre_processes=None, transforms=None, filter_keys=None, ignore_tags=None, is_training=True): self.is_training = is_training self.root = root self.transforms = transforms self.pre_processes = pre_processes self.filter_key = filter_keys self.ignore_tags = ignore_tags self.aug = list() self.imgs = list(sorted(os.listdir(os.path.join(root, "imgs")))) self.gts = list(sorted(os.listdir(os.path.join(root, "gts")))) self.init_pre_process() def __len__(self): return len(self.imgs) def __getitem__(self, item): img_path = os.path.join(self.root, 'imgs', self.imgs[item]) gt_path = os.path.join(self.root, 'gts', self.gts[item]) img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) targets = self.get_annotation(gt_path) targets['img'] = img targets['shape'] = [img.shape[0], img.shape[1]] targets = self.apply_pre_process(targets) if self.transforms is not None: targets['img'] = self.transforms(targets['img']) targets['text_polys'] = targets['text_polys'].tolist() if self.filter_key is not None and self.is_training: targets_dict = dict() for k, v in targets.items(): if k not in self.filter_key: targets_dict[k] = v return targets['img'], targets_dict else: return targets['img'], targets def get_annotation(self, gt_path): boxes = list() texts = list() ignores = list() with open(gt_path, encoding='utf-8', mode='r') as f: for line in f.readlines(): params = line.strip().strip('\ufeff').strip('\xef\xbb\xbf').split(',') try: box = order_points_clockwise(np.array(list(map(float, params[:8]))).reshape(-1, 2)) if cv2.contourArea(box) > 0: boxes.append(box) texts.append(params[8]) ignores.append(params[8] in self.ignore_tags) except Exception as e: print(e) print('get annotation is failed {}'.format(gt_path)) data = {'text_polys': np.array(boxes), 'texts': texts, 'ignore_tags': ignores} return data def init_pre_process(self): if self.pre_processes is not None: for aug in self.pre_processes: if 'args' not in aug: args = {} else: args = aug['args'] if isinstance(args, dict): cls = eval(aug['type'])(**args) else: cls = eval(aug['type'])(args) self.aug.append(cls) def apply_pre_process(self, data): for aug in self.aug: data = aug(data) return data if __name__ == '__main__': dataset = CurrentOcrData('/home/shizai/data2/ocr_data/rctw') dataset.get_annotation('/home/shizai/data2/ocr_data/rctw/gts/rctw_image_3629.txt')
true
true
f710e9b2e374ff122b8766f60cdbc6d0288bae13
3,156
py
Python
leetcode/117_populate_next_right_pointer_in_each_node_2.py
yatao91/learning_road
e88dc43de98e35922bfc71c222ec71766851e618
[ "MIT" ]
3
2021-05-25T16:58:52.000Z
2022-02-05T09:37:17.000Z
leetcode/117_populate_next_right_pointer_in_each_node_2.py
yataosu/learning_road
e88dc43de98e35922bfc71c222ec71766851e618
[ "MIT" ]
null
null
null
leetcode/117_populate_next_right_pointer_in_each_node_2.py
yataosu/learning_road
e88dc43de98e35922bfc71c222ec71766851e618
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ 二叉树:填充每个节点的下一个右侧节点指针2 https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/ """ class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next class Solution: def processChild(self, childNode: 'Node', prev: 'Node', leftmost: 'Node') -> tuple: # 孩子节点存在 if childNode: # prev指针已经设置,如果有至少一个节点在下一层则设置prev的next指针指向 if prev: prev.next = childNode # prev指针不存在,则表示孩子节点为下一层的第一个节点,所以设置为下一层最左节点leftmost else: leftmost = childNode # prev指向当前孩子节点 prev = childNode # 孩子节点不存在,则不对prev和leftmost进行更新 return prev, leftmost def connect(self, root: 'Node') -> 'Node': """ 思路:使用已建立的next指针:第N层建立next指针后,再建立第N+1层节点的next指针 1.leftmost:每层最左节点.每层最左节点作为链表首部,从该节点开始访问该层所有节点 2.curr:用来遍历当前层的所有节点.从该层的最左节点一直移动到该层最后一个节点 3.prev:指向下一层的节点.使用prev来指向下一层节点,来做next指针连接 hardware.prev指针初始化.每层遍历开始时,prev指针置为空,找到下一层最左节点时,将该节点赋予prev指针 b.当前节点没有左子节点时,将prev指向当前节点的右子节点 c.下一个节点没有孩子节点,则不对prev指针进行更新 d.下一个节点同时拥有左孩子和右孩子,首先prev指向左孩子,处理完后,指向右孩子. 时间复杂度:O(n),每个节点均处理一次 空间复杂度:O(1),不需要额外空间 :param root: 原二叉树 :return: 填充next指针后二叉树 """ if not root: return root # 第一层仅存在一个根节点,初始化最左节点为root节点 leftmost = root # 循环遍历每一层,最左节点为空时退出循环. while leftmost: # 初始化每层prev和curr指针,prev指针初始化None,curr指针初始化为当前层最左节点,用来从该层首部通过next指针进行遍历 prev, curr = None, leftmost # 初始化下一层最左节点leftmost为None leftmost = None # 根据next指针对当前层节点进行遍历 while curr: # 处理当前节点的孩子节点并更新prev和leftmost指针 prev, leftmost = self.processChild(curr.left, prev, leftmost) prev, leftmost = self.processChild(curr.right, prev, leftmost) # 移动到当前层的下一个节点 curr = curr.next return root def connect2(self, root: 'Node') -> 'Node': """ 思路:在当前层,把下一层的第一个节点用哨兵节点记录下来;然后遍历当前层的时候,把下面一层串起来(next指针),当前层遍历完,通过哨兵节点可以开始 下一层的遍历.(重复上述过程,将哨兵节点记录下下层第一个节点,然后遍历该层,并把下面一层串起来) 时间复杂度:O(n),每个节点均需处理一次 空间复杂度:O(1),没有占用额外空间 :param root: 原二叉树 :return: 填充next指针后的二叉树 """ # curr初始化为根节点 curr = root # 当前curr为下一层第一个节点,代表将遍历下一层. while curr: # 实例化哨兵节点 dummy = Node() # tail初始化为哨兵节点(尾插法) tail = dummy # 遍历当前层的节点,并借助tail逐步后移串联起下一层 while curr: if curr.left: tail.next = curr.left tail = tail.next if curr.right: tail.next = curr.right tail = tail.next # 当前层下一个节点,通过next指针获取(实际当前层遍历等价于链表遍历) curr = curr.next # 哨兵节点持有的next即为下一层第一个节点 curr = dummy.next return root
30.057143
101
0.560837
class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next class Solution: def processChild(self, childNode: 'Node', prev: 'Node', leftmost: 'Node') -> tuple: if childNode: if prev: prev.next = childNode else: leftmost = childNode prev = childNode return prev, leftmost def connect(self, root: 'Node') -> 'Node': if not root: return root leftmost = root while leftmost: prev, curr = None, leftmost leftmost = None while curr: prev, leftmost = self.processChild(curr.left, prev, leftmost) prev, leftmost = self.processChild(curr.right, prev, leftmost) curr = curr.next return root def connect2(self, root: 'Node') -> 'Node': curr = root while curr: dummy = Node() tail = dummy while curr: if curr.left: tail.next = curr.left tail = tail.next if curr.right: tail.next = curr.right tail = tail.next curr = curr.next curr = dummy.next return root
true
true
f710e9f366623389796c8dc337338647dd2f4046
1,251
py
Python
tests/test_list.py
turbocat2001/tinypy
843b45b3675bc290d27cf50fedc05373ff2ae62e
[ "PSF-2.0" ]
17
2019-10-07T15:54:01.000Z
2022-01-20T06:33:16.000Z
tests/test_list.py
turbocat2001/tinypy
843b45b3675bc290d27cf50fedc05373ff2ae62e
[ "PSF-2.0" ]
24
2019-02-16T07:49:31.000Z
2021-05-31T07:16:45.000Z
tests/test_list.py
turbocat2001/tinypy
843b45b3675bc290d27cf50fedc05373ff2ae62e
[ "PSF-2.0" ]
4
2020-11-24T23:03:02.000Z
2021-05-30T03:34:02.000Z
from tinypy.runtime.testing import UnitTest class MyTest(UnitTest): def test_lessthan(self): assert [1, 2] < [2] assert [1, 2] <= [2] assert [1] < [2] assert [1] <= [2] assert [] < [1] def test_greaterthan(self): assert [2] > [1] assert [1, 2] > [1] assert [1, 2] >= [1] assert [1, 2] >= [1, 2] assert [2] > [] def test_equal(self): assert [1] == [1] assert [1, 2] == [1, 2] assert [] == [] # FIXME: # As we don't have an iterable type, there is not much point # to define min and max. # We shall probably remove min and max from builtins. def test_max(self): assert max(1, 2, 3) == 3 assert max(3, 1, 2) == 3 assert max(3, 1, 3) == 3 def test_min(self): assert min(1, 2, 3) == 1 assert min(3, 1, 2) == 1 assert min(2, 1, 1) == 1 def test_slice(self): # FIXME: support 1:2 and 1:2:1 assert [0, 1, 2, 3][1, 2] == [1] assert [0, 1, 2, 3][1, None] == [1, 2, 3] assert [0, 1, 2, 3][None, None] == [0, 1, 2, 3] assert [0, 1, 2, 3][None, 1] == [0] assert [0, 1, 2, 3][None, 2] == [0, 1] t = MyTest() t.run()
25.530612
64
0.460432
from tinypy.runtime.testing import UnitTest class MyTest(UnitTest): def test_lessthan(self): assert [1, 2] < [2] assert [1, 2] <= [2] assert [1] < [2] assert [1] <= [2] assert [] < [1] def test_greaterthan(self): assert [2] > [1] assert [1, 2] > [1] assert [1, 2] >= [1] assert [1, 2] >= [1, 2] assert [2] > [] def test_equal(self): assert [1] == [1] assert [1, 2] == [1, 2] assert [] == [] # to define min and max. # We shall probably remove min and max from builtins. def test_max(self): assert max(1, 2, 3) == 3 assert max(3, 1, 2) == 3 assert max(3, 1, 3) == 3 def test_min(self): assert min(1, 2, 3) == 1 assert min(3, 1, 2) == 1 assert min(2, 1, 1) == 1 def test_slice(self): # FIXME: support 1:2 and 1:2:1 assert [0, 1, 2, 3][1, 2] == [1] assert [0, 1, 2, 3][1, None] == [1, 2, 3] assert [0, 1, 2, 3][None, None] == [0, 1, 2, 3] assert [0, 1, 2, 3][None, 1] == [0] assert [0, 1, 2, 3][None, 2] == [0, 1] t = MyTest() t.run()
true
true
f710ea07fd04d18c044bb23dbadb145eeb1689c0
420
py
Python
store/migrations/0009_alter_product_images.py
falconsoft3d/clientportal_shop
bc09eda46cb42bbc490dfc6d958250ec000073b5
[ "MIT" ]
5
2022-03-14T21:15:20.000Z
2022-03-22T10:11:58.000Z
store/migrations/0009_alter_product_images.py
falconsoft3d/clientportal_shop
bc09eda46cb42bbc490dfc6d958250ec000073b5
[ "MIT" ]
null
null
null
store/migrations/0009_alter_product_images.py
falconsoft3d/clientportal_shop
bc09eda46cb42bbc490dfc6d958250ec000073b5
[ "MIT" ]
null
null
null
# Generated by Django 3.2.5 on 2022-03-24 15:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0008_alter_product_product_name'), ] operations = [ migrations.AlterField( model_name='product', name='images', field=models.ImageField(blank=True, upload_to='photos/products'), ), ]
22.105263
77
0.616667
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0008_alter_product_product_name'), ] operations = [ migrations.AlterField( model_name='product', name='images', field=models.ImageField(blank=True, upload_to='photos/products'), ), ]
true
true
f710eb511746bae3875a98aa7276b03dcf488041
1,523
py
Python
django_extensions/management/commands/clean_pyc.py
KazakovDenis/django-extensions
ef3b3abe3c3d6563b73633bd25e3ff3ac9716661
[ "MIT" ]
4,057
2015-01-01T17:56:25.000Z
2022-03-31T16:32:40.000Z
django_extensions/management/commands/clean_pyc.py
KazakovDenis/django-extensions
ef3b3abe3c3d6563b73633bd25e3ff3ac9716661
[ "MIT" ]
1,115
2015-01-01T14:59:38.000Z
2022-03-28T22:05:55.000Z
django_extensions/management/commands/clean_pyc.py
KazakovDenis/django-extensions
ef3b3abe3c3d6563b73633bd25e3ff3ac9716661
[ "MIT" ]
951
2015-01-02T16:57:26.000Z
2022-03-28T21:42:22.000Z
# -*- coding: utf-8 -*- import fnmatch import os from os.path import join as _j from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django_extensions.management.utils import signalcommand class Command(BaseCommand): help = "Removes all python bytecode compiled files from the project." requires_system_checks = False def add_arguments(self, parser): parser.add_argument( '--optimize', '-o', '-O', action='store_true', dest='optimize', default=False, help='Remove optimized python bytecode files' ) parser.add_argument( '--path', '-p', action='store', dest='path', help='Specify path to recurse into' ) @signalcommand def handle(self, *args, **options): project_root = options.get("path", getattr(settings, 'BASE_DIR', None)) if not project_root: project_root = getattr(settings, 'BASE_DIR', None) verbosity = options["verbosity"] if not project_root: raise CommandError("No --path specified and settings.py does not contain BASE_DIR") exts = options["optimize"] and "*.py[co]" or "*.pyc" for root, dirs, filenames in os.walk(project_root): for filename in fnmatch.filter(filenames, exts): full_path = _j(root, filename) if verbosity > 1: self.stdout.write("%s\n" % full_path) os.remove(full_path)
33.108696
95
0.620486
import fnmatch import os from os.path import join as _j from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django_extensions.management.utils import signalcommand class Command(BaseCommand): help = "Removes all python bytecode compiled files from the project." requires_system_checks = False def add_arguments(self, parser): parser.add_argument( '--optimize', '-o', '-O', action='store_true', dest='optimize', default=False, help='Remove optimized python bytecode files' ) parser.add_argument( '--path', '-p', action='store', dest='path', help='Specify path to recurse into' ) @signalcommand def handle(self, *args, **options): project_root = options.get("path", getattr(settings, 'BASE_DIR', None)) if not project_root: project_root = getattr(settings, 'BASE_DIR', None) verbosity = options["verbosity"] if not project_root: raise CommandError("No --path specified and settings.py does not contain BASE_DIR") exts = options["optimize"] and "*.py[co]" or "*.pyc" for root, dirs, filenames in os.walk(project_root): for filename in fnmatch.filter(filenames, exts): full_path = _j(root, filename) if verbosity > 1: self.stdout.write("%s\n" % full_path) os.remove(full_path)
true
true
f710ebce031db7b1fee12609e6116bfb2c72f855
411
py
Python
dcctools/freqs_of_matching_projs.py
NACHC-CAD/linkage-agent-tools
324299e534bc55bd652eb670feb195ce5646f13e
[ "Apache-2.0" ]
null
null
null
dcctools/freqs_of_matching_projs.py
NACHC-CAD/linkage-agent-tools
324299e534bc55bd652eb670feb195ce5646f13e
[ "Apache-2.0" ]
1
2021-10-01T15:13:15.000Z
2021-10-01T15:13:15.000Z
dcctools/freqs_of_matching_projs.py
NACHC-CAD/linkage-agent-tools
324299e534bc55bd652eb670feb195ce5646f13e
[ "Apache-2.0" ]
null
null
null
from config import Configuration from pymongo import MongoClient c = Configuration("config.json") client = MongoClient(c.mongo_uri) database = client.linkage_agent results = database.match_groups.aggregate( [ { "$group": { "_id": {"$size": "$run_results"}, "total": {"$sum": 1}, } } ] ) for result in results: print(result)
19.571429
49
0.564477
from config import Configuration from pymongo import MongoClient c = Configuration("config.json") client = MongoClient(c.mongo_uri) database = client.linkage_agent results = database.match_groups.aggregate( [ { "$group": { "_id": {"$size": "$run_results"}, "total": {"$sum": 1}, } } ] ) for result in results: print(result)
true
true
f710ebfe96225e5ddcad7a7dd3bcf159cbd86425
2,814
py
Python
tests/test_test_functions.py
thouska/SALib
fd64136192f00a9e3e65a8c5c05e30d93ed5e750
[ "MIT" ]
2
2019-02-01T17:24:38.000Z
2019-02-01T17:30:43.000Z
tests/test_test_functions.py
penghuz/SALib
5deeaf316ef58ea0a26295c8ad2ca57cdc739d45
[ "MIT" ]
3
2018-11-06T11:13:43.000Z
2018-11-16T15:48:44.000Z
tests/test_test_functions.py
penghuz/SALib
5deeaf316ef58ea0a26295c8ad2ca57cdc739d45
[ "MIT" ]
2
2019-09-22T05:30:21.000Z
2021-12-02T03:15:31.000Z
from nose.tools import assert_almost_equal, assert_equal, raises from numpy.testing import assert_allclose import numpy as np from SALib.test_functions.Sobol_G import evaluate, total_variance, \ partial_first_order_variance, \ sensitivity_index, \ total_sensitivity_index def test_Sobol_G(): ''' ''' parameter_values = np.zeros((1, 8)) actual = evaluate(parameter_values) expected = np.array([4.0583]) assert_allclose(actual, expected, atol=1e-4, rtol=1e-4) @raises(ValueError) def test_Sobol_G_raises_error_if_values_wrong_size(): """ Tests that a value error is raised if the Sobol G function is called with the wrong number of variables """ a = [1, 2, 3, 4, 5, 6, 7, 8] evaluate(np.array([1, 2, 3, 4, 5, 6, 7]), a) @raises(ValueError) def test_Sobol_G_raises_error_if_values_gt_one(): """ Tests that a value error is raised if the Sobol G function is called with values greater than one """ evaluate(np.array([0, 1, .02, 0.23, 1.234, 0.02848848, 0, 0.78])) @raises(ValueError) def test_Sobol_G_raises_error_if_values_lt_zero(): """ Tests that a value error is raised if the Sobol G function is called with values less than zero. """ evaluate(np.array([0, -1, -.02, 1, 1, -0.1, -0, -12])) @raises(TypeError) def test_Sobol_G_raises_error_if_values_not_numpy_array(): """ Tests that a type error is raised if the Sobol G function is called with values argument not as a numpy array. """ fixture = [list(range(8)), str(12345678)] for x in fixture: evaluate(x) def test_total_variance(): a = np.array([78, 12, 0.5, 2, 97, 33]) actual = total_variance(a) expected = 0.19347 assert_allclose(actual, expected, rtol=1e-4) def test_partial_first_order_variance(): a = np.array([78, 12, 0.5, 2, 97, 33]) actual = partial_first_order_variance(a) expected = (len(a),) assert_equal(a.shape, expected) expected = np.array([0.000053, 0.001972, 0.148148, 0.037037, 0.000035, 0.000288]) assert_allclose(actual, expected, atol=1e-4, rtol=1e-4) def test_sensitivity_index(): a = np.array([78, 12, 0.5, 2, 97, 33]) actual = sensitivity_index(a) expected = np.array([0.000276, 0.010195, 0.765743, 0.191436, 0.000179, 0.001490]) assert_allclose(actual, expected, atol=1e-2, rtol=1e-6) def test_total_sensitivity_index(): a = np.array([78, 12, 0.5, 2, 97, 33]) actual = total_sensitivity_index(a) expected = np.array([0.030956547, 0.040875287, 0.796423551, 0.222116249, 0.030859879, 0.032170899]) assert_allclose(actual, expected, atol=1e-2, rtol=1e-6)
28.714286
85
0.641436
from nose.tools import assert_almost_equal, assert_equal, raises from numpy.testing import assert_allclose import numpy as np from SALib.test_functions.Sobol_G import evaluate, total_variance, \ partial_first_order_variance, \ sensitivity_index, \ total_sensitivity_index def test_Sobol_G(): parameter_values = np.zeros((1, 8)) actual = evaluate(parameter_values) expected = np.array([4.0583]) assert_allclose(actual, expected, atol=1e-4, rtol=1e-4) @raises(ValueError) def test_Sobol_G_raises_error_if_values_wrong_size(): a = [1, 2, 3, 4, 5, 6, 7, 8] evaluate(np.array([1, 2, 3, 4, 5, 6, 7]), a) @raises(ValueError) def test_Sobol_G_raises_error_if_values_gt_one(): evaluate(np.array([0, 1, .02, 0.23, 1.234, 0.02848848, 0, 0.78])) @raises(ValueError) def test_Sobol_G_raises_error_if_values_lt_zero(): evaluate(np.array([0, -1, -.02, 1, 1, -0.1, -0, -12])) @raises(TypeError) def test_Sobol_G_raises_error_if_values_not_numpy_array(): fixture = [list(range(8)), str(12345678)] for x in fixture: evaluate(x) def test_total_variance(): a = np.array([78, 12, 0.5, 2, 97, 33]) actual = total_variance(a) expected = 0.19347 assert_allclose(actual, expected, rtol=1e-4) def test_partial_first_order_variance(): a = np.array([78, 12, 0.5, 2, 97, 33]) actual = partial_first_order_variance(a) expected = (len(a),) assert_equal(a.shape, expected) expected = np.array([0.000053, 0.001972, 0.148148, 0.037037, 0.000035, 0.000288]) assert_allclose(actual, expected, atol=1e-4, rtol=1e-4) def test_sensitivity_index(): a = np.array([78, 12, 0.5, 2, 97, 33]) actual = sensitivity_index(a) expected = np.array([0.000276, 0.010195, 0.765743, 0.191436, 0.000179, 0.001490]) assert_allclose(actual, expected, atol=1e-2, rtol=1e-6) def test_total_sensitivity_index(): a = np.array([78, 12, 0.5, 2, 97, 33]) actual = total_sensitivity_index(a) expected = np.array([0.030956547, 0.040875287, 0.796423551, 0.222116249, 0.030859879, 0.032170899]) assert_allclose(actual, expected, atol=1e-2, rtol=1e-6)
true
true
f710ec229ca894ca35d13cd7b05863a50af3e4d5
1,129
py
Python
azext_iot/sdk/iothub/service/models/digital_twin_interfaces_patch_interfaces_value.py
YingXue/azure-iot-cli-extension
efe7897b1ae1d2a9953f501abe7654b84d69372d
[ "MIT" ]
null
null
null
azext_iot/sdk/iothub/service/models/digital_twin_interfaces_patch_interfaces_value.py
YingXue/azure-iot-cli-extension
efe7897b1ae1d2a9953f501abe7654b84d69372d
[ "MIT" ]
null
null
null
azext_iot/sdk/iothub/service/models/digital_twin_interfaces_patch_interfaces_value.py
YingXue/azure-iot-cli-extension
efe7897b1ae1d2a9953f501abe7654b84d69372d
[ "MIT" ]
null
null
null
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class DigitalTwinInterfacesPatchInterfacesValue(Model): """DigitalTwinInterfacesPatchInterfacesValue. :param properties: List of properties to update in an interface. :type properties: dict[str, ~service.models.DigitalTwinInterfacesPatchInterfacesValuePropertiesValue] """ _attribute_map = { 'properties': {'key': 'properties', 'type': '{DigitalTwinInterfacesPatchInterfacesValuePropertiesValue}'}, } def __init__(self, **kwargs): super(DigitalTwinInterfacesPatchInterfacesValue, self).__init__(**kwargs) self.properties = kwargs.get('properties', None)
37.633333
114
0.649247
from msrest.serialization import Model class DigitalTwinInterfacesPatchInterfacesValue(Model): _attribute_map = { 'properties': {'key': 'properties', 'type': '{DigitalTwinInterfacesPatchInterfacesValuePropertiesValue}'}, } def __init__(self, **kwargs): super(DigitalTwinInterfacesPatchInterfacesValue, self).__init__(**kwargs) self.properties = kwargs.get('properties', None)
true
true
f710ee9b7dec0a3ac267c1d7e46c767a086a4ec8
1,450
py
Python
proselint/checks/consistency/spelling.py
ankita240796/proselint
50d2a482df8f467737f9c958ace98ba152bec832
[ "BSD-3-Clause" ]
4,163
2015-10-03T07:37:21.000Z
2022-03-31T03:52:32.000Z
proselint/checks/consistency/spelling.py
ankita240796/proselint
50d2a482df8f467737f9c958ace98ba152bec832
[ "BSD-3-Clause" ]
878
2015-09-30T20:03:33.000Z
2022-03-28T11:06:15.000Z
proselint/checks/consistency/spelling.py
ankita240796/proselint
50d2a482df8f467737f9c958ace98ba152bec832
[ "BSD-3-Clause" ]
249
2015-10-04T12:21:27.000Z
2022-02-28T22:13:11.000Z
"""Inconsistent spelling. --- layout: post source: Intelligent Editing Ltd. source_url: http://bit.ly/1x3hYj7 title: Inconsistent spelling date: 2014-06-10 12:31:19 categories: writing --- Intelligent Editing Ltd. says: > Some words have more than one correct spelling. American, British, Australian and Canadian English all have their own preferences. Even within those, there can be multiple spellings. For example, in the UK 'realise' is often preferred. However, 'realize' has been used in British-English for centuries and is preferred in the Oxford English Dictionary. However, no matter which spelling is preferred, one thing is always wrong: you mustn't use two different spellings in the same document. """ from proselint.tools import consistency_check, memoize @memoize def check(text): """Check the text.""" err = "consistency.spelling" msg = "Inconsistent spelling of '{}' (vs. '{}')." word_pairs = [ ["advisor", "adviser"], # ["analyse", "analyze"], ["centre", "center"], ["colour", "color"], ["emphasise", "emphasize"], ["finalise", "finalize"], ["focussed", "focused"], ["labour", "labor"], ["learnt", "learned"], ["organise", "organize"], ["organised", "organized"], ["organising", "organizing"], ["recognise", "recognize"], ] return consistency_check(text, word_pairs, err, msg)
30.208333
79
0.648276
from proselint.tools import consistency_check, memoize @memoize def check(text): err = "consistency.spelling" msg = "Inconsistent spelling of '{}' (vs. '{}')." word_pairs = [ ["advisor", "adviser"], ["centre", "center"], ["colour", "color"], ["emphasise", "emphasize"], ["finalise", "finalize"], ["focussed", "focused"], ["labour", "labor"], ["learnt", "learned"], ["organise", "organize"], ["organised", "organized"], ["organising", "organizing"], ["recognise", "recognize"], ] return consistency_check(text, word_pairs, err, msg)
true
true
f710eef1eb36847687f68491ed5a96826bf349fb
318
py
Python
setup.py
allenai/manipulathor
4562eb8c2f67ff67e5b9ba3930da84b6023a58a4
[ "MIT" ]
55
2021-04-20T03:51:25.000Z
2022-03-30T02:30:53.000Z
setup.py
allenai/manipulathor
4562eb8c2f67ff67e5b9ba3930da84b6023a58a4
[ "MIT" ]
7
2021-04-28T17:35:02.000Z
2021-08-24T09:37:14.000Z
setup.py
allenai/manipulathor
4562eb8c2f67ff67e5b9ba3930da84b6023a58a4
[ "MIT" ]
10
2021-04-23T00:56:39.000Z
2022-02-22T08:28:33.000Z
from setuptools import find_packages, setup if __name__ == "__main__": setup( name="manipulathor", packages=find_packages(), version="0.0.1", install_requires=[ "allenact==0.2.2", "allenact_plugins[ithor]==0.2.2", "setuptools", ], )
22.714286
45
0.531447
from setuptools import find_packages, setup if __name__ == "__main__": setup( name="manipulathor", packages=find_packages(), version="0.0.1", install_requires=[ "allenact==0.2.2", "allenact_plugins[ithor]==0.2.2", "setuptools", ], )
true
true
f710efea21dad3a91fd998d1e0b0dc08ee754d47
9,973
py
Python
src/nft_analytics.py
dineshpinto/nft_analytics
99fd4adbfe786f4de6fa2a6a0c5e8a58eaaf338a
[ "MIT" ]
6
2022-01-09T05:04:07.000Z
2022-03-03T20:26:27.000Z
src/nft_analytics.py
dineshpinto/nft-analytics
99fd4adbfe786f4de6fa2a6a0c5e8a58eaaf338a
[ "MIT" ]
null
null
null
src/nft_analytics.py
dineshpinto/nft-analytics
99fd4adbfe786f4de6fa2a6a0c5e8a58eaaf338a
[ "MIT" ]
1
2022-02-09T04:58:51.000Z
2022-02-09T04:58:51.000Z
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2021 Dinesh Pinto 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 json import logging import os import sys from json import JSONDecodeError import numpy as np import pandas as pd from tqdm import tqdm from .infura_api import InfuraAPI from .opensea_api import OpenSeaAPI logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', stream=sys.stdout, level=logging.INFO) logger = logging.getLogger(__name__) class NFTAnalytics(OpenSeaAPI): def __init__(self, asset_contract_address: str): super().__init__(asset_contract_address) self.eth_api = InfuraAPI() @staticmethod def make_directories(folder_name: str): """ Set up directories for data and results if they don't exist. """ data_folder = os.path.join("data", folder_name) result_folder = os.path.join("results", folder_name) if not os.path.isdir(data_folder): logger.info(f"Making directoy {data_folder}") os.makedirs(data_folder) if not os.path.isdir(result_folder): logger.info(f"Making directoy {result_folder}") os.makedirs(result_folder) return data_folder, result_folder def fetch_data(self, max_offset: int = 10000, collection: str = None) -> list: """ Query OpenSea API for collection data, offset is shifted until max offset is reached (i.e. number of items in a collection). """ local_assets = [] pbar = tqdm(range(0, max_offset + 1, 50)) for offset in pbar: pbar.set_description(f"{offset}") try: asset_data = self.get_asset_data(offset=offset, limit=50, collection=collection) except JSONDecodeError: logger.error(f"Only fetched data till offset={offset - 1}. " f"Warning={self.get_asset_data(offset=offset, limit=50)}") return local_assets if "assets" not in asset_data: logger.error(f"Only fetched data till offset={offset - 1}. Warning={asset_data}") return local_assets for asset in asset_data["assets"]: local_assets.append(asset) return local_assets def fetch_events(self, max_offset: int = 10000) -> list: """ Query OpenSea API for event data, offset is shifted until max offset is reached (i.e. number of items in a collection). """ local_events = [] pbar = tqdm(range(0, max_offset + 1, 300)) for offset in pbar: pbar.set_description(f"{offset}") try: event_data = self.get_event_data(offset=offset, limit=300) except JSONDecodeError: logger.error(f"Only fetched data till offset={offset - 1}. " f"Warning={self.get_asset_data(offset=offset, limit=50)}") return local_events if "asset_events" not in event_data: logger.error(f"Only fetched data till offset={offset - 1}. Warning={event_data}") return local_events for event in event_data["asset_events"]: local_events.append(event) return local_events @staticmethod def save_json(asset_data: list, filename: str = "data.json"): with open(filename, 'w', encoding='utf-8') as f: json.dump(asset_data, f, ensure_ascii=False, indent=4) logger.info(f"Saved asset data to {filename}") @staticmethod def load_json(filename: str = "data.json") -> list: with open(filename) as f: asset_data = json.load(f) return asset_data @staticmethod def get_trait_values_for_type(asset_data: list, trait_type: str) -> list: """ Get all possible values of traits for a specific type of trait. """ trait_values = [] for asset in asset_data: for traits in asset["traits"]: if traits["trait_type"] == trait_type and traits["value"] not in trait_values: trait_values.append(traits["value"]) return trait_values def get_trait_type_median_price(self, asset_data: list, trait_type: str) -> dict: """ Get the median price of a specific trait type. """ trait_value_prices = {} for value in self.get_trait_values_for_type(asset_data, trait_type): listing_prices_trait = [] for asset in asset_data: if asset["sell_orders"]: for traits in asset["traits"]: if traits["trait_type"] == trait_type and traits["value"] == value: listing_prices_trait.append(float(asset["sell_orders"][0]["base_price"]) / 1e18) trait_value_prices[value] = np.median(np.array(listing_prices_trait)) return dict(sorted(trait_value_prices.items(), key=lambda item: item[1], reverse=True)) def get_median_prices(self, asset_data: list, traits_dict: dict) -> np.ndarray: """ Get median prices of all trait types. """ median_prices = [] for trait_type, trait_value in traits_dict.items(): median_prices.append(self.get_trait_type_median_price(asset_data, trait_type)[trait_value]) return np.array(median_prices) def get_traits_with_median_prices(self, asset_data: list, asset: dict) -> dict: """ Get median prices of trait types for specific asset. """ traits = {} for trait in asset["traits"]: traits[trait["trait_type"]] = trait["value"] trait_prices = {} for trait_type, trait_value in traits.items(): price = self.get_trait_type_median_price(asset_data, trait_type)[trait_value] trait_prices[trait_value + " " + trait_type] = price return trait_prices def get_nft_holdings(self, asset_data: list, asset_name: str, eth_balances: bool = True) \ -> pd.DataFrame: """ Query the number of NFTs held and/or the ETH balances of addresses in a collection. """ nfts_held = {} for asset in asset_data: nfts_held[asset["owner"]["address"]] = 0 for asset in asset_data: nfts_held[asset["owner"]["address"]] += 1 logger.info(f"Total NFTs in collection = {sum(nfts_held.values())}") if eth_balances: logger.info(f"Getting NFT holdings and ETH balances...") df = pd.DataFrame(columns=["Address", asset_name, "ETH_balance"]) pbar = tqdm(nfts_held.items()) for idx, (address, num_nfts) in enumerate(pbar): pbar.set_description(f"{idx}") df.loc[idx] = [address, num_nfts, self.eth_api.get_eth_balance(address)] else: logger.info(f"Getting NFT holdings...") df = pd.DataFrame(columns=["Address", asset_name]) pbar = tqdm(nfts_held.items()) for idx, (address, num_nfts) in enumerate(pbar): pbar.set_description(f"{idx}") df.loc[idx] = [address, num_nfts] etherscan_links = [] for address in df["Address"]: etherscan_links.append(f"https://etherscan.io/address/{address}") df["Etherscan_link"] = etherscan_links opensea_links = [] for address in df["Address"]: opensea_links.append(f"https://opensea.io/{address}") df["OpenSea_link"] = opensea_links return df @staticmethod def calculate_rarity_df(asset_data: list, items_in_collection: int) -> pd.DataFrame: """ Calculate rarity of a particular trait. Uses the formula from rarity tools, full article at: raritytools.medium.com/ranking-rarity-understanding-rarity-calculation-methods-86ceaeb9b98c Formula: [Rarity Score for a Trait Value] = 1 / ([Number of Items with that Trait Value] / [Total Number of Items in Collection]) The total Rarity Score for an NFT is the sum of the Rarity Score of all of its trait values. """ df = pd.DataFrame(columns=["Name", "Price", "Rarity", "RarityPriceRatio"]) for idx, asset in enumerate(asset_data): if asset["sell_orders"]: if asset["sell_orders"][0]["payment_token_contract"]["symbol"] == "ETH": price = float(asset["sell_orders"][0]["current_price"]) / 1e18 if price != 0: rarity = 0 for trait in asset["traits"]: trait_count = int(trait["trait_count"]) if trait_count != 0: rarity += 1 / (trait_count / items_in_collection) name = asset["name"] df.loc[idx] = [name, price, rarity, rarity / price] return df
39.418972
108
0.620475
import json import logging import os import sys from json import JSONDecodeError import numpy as np import pandas as pd from tqdm import tqdm from .infura_api import InfuraAPI from .opensea_api import OpenSeaAPI logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', stream=sys.stdout, level=logging.INFO) logger = logging.getLogger(__name__) class NFTAnalytics(OpenSeaAPI): def __init__(self, asset_contract_address: str): super().__init__(asset_contract_address) self.eth_api = InfuraAPI() @staticmethod def make_directories(folder_name: str): data_folder = os.path.join("data", folder_name) result_folder = os.path.join("results", folder_name) if not os.path.isdir(data_folder): logger.info(f"Making directoy {data_folder}") os.makedirs(data_folder) if not os.path.isdir(result_folder): logger.info(f"Making directoy {result_folder}") os.makedirs(result_folder) return data_folder, result_folder def fetch_data(self, max_offset: int = 10000, collection: str = None) -> list: local_assets = [] pbar = tqdm(range(0, max_offset + 1, 50)) for offset in pbar: pbar.set_description(f"{offset}") try: asset_data = self.get_asset_data(offset=offset, limit=50, collection=collection) except JSONDecodeError: logger.error(f"Only fetched data till offset={offset - 1}. " f"Warning={self.get_asset_data(offset=offset, limit=50)}") return local_assets if "assets" not in asset_data: logger.error(f"Only fetched data till offset={offset - 1}. Warning={asset_data}") return local_assets for asset in asset_data["assets"]: local_assets.append(asset) return local_assets def fetch_events(self, max_offset: int = 10000) -> list: local_events = [] pbar = tqdm(range(0, max_offset + 1, 300)) for offset in pbar: pbar.set_description(f"{offset}") try: event_data = self.get_event_data(offset=offset, limit=300) except JSONDecodeError: logger.error(f"Only fetched data till offset={offset - 1}. " f"Warning={self.get_asset_data(offset=offset, limit=50)}") return local_events if "asset_events" not in event_data: logger.error(f"Only fetched data till offset={offset - 1}. Warning={event_data}") return local_events for event in event_data["asset_events"]: local_events.append(event) return local_events @staticmethod def save_json(asset_data: list, filename: str = "data.json"): with open(filename, 'w', encoding='utf-8') as f: json.dump(asset_data, f, ensure_ascii=False, indent=4) logger.info(f"Saved asset data to {filename}") @staticmethod def load_json(filename: str = "data.json") -> list: with open(filename) as f: asset_data = json.load(f) return asset_data @staticmethod def get_trait_values_for_type(asset_data: list, trait_type: str) -> list: trait_values = [] for asset in asset_data: for traits in asset["traits"]: if traits["trait_type"] == trait_type and traits["value"] not in trait_values: trait_values.append(traits["value"]) return trait_values def get_trait_type_median_price(self, asset_data: list, trait_type: str) -> dict: trait_value_prices = {} for value in self.get_trait_values_for_type(asset_data, trait_type): listing_prices_trait = [] for asset in asset_data: if asset["sell_orders"]: for traits in asset["traits"]: if traits["trait_type"] == trait_type and traits["value"] == value: listing_prices_trait.append(float(asset["sell_orders"][0]["base_price"]) / 1e18) trait_value_prices[value] = np.median(np.array(listing_prices_trait)) return dict(sorted(trait_value_prices.items(), key=lambda item: item[1], reverse=True)) def get_median_prices(self, asset_data: list, traits_dict: dict) -> np.ndarray: median_prices = [] for trait_type, trait_value in traits_dict.items(): median_prices.append(self.get_trait_type_median_price(asset_data, trait_type)[trait_value]) return np.array(median_prices) def get_traits_with_median_prices(self, asset_data: list, asset: dict) -> dict: traits = {} for trait in asset["traits"]: traits[trait["trait_type"]] = trait["value"] trait_prices = {} for trait_type, trait_value in traits.items(): price = self.get_trait_type_median_price(asset_data, trait_type)[trait_value] trait_prices[trait_value + " " + trait_type] = price return trait_prices def get_nft_holdings(self, asset_data: list, asset_name: str, eth_balances: bool = True) \ -> pd.DataFrame: nfts_held = {} for asset in asset_data: nfts_held[asset["owner"]["address"]] = 0 for asset in asset_data: nfts_held[asset["owner"]["address"]] += 1 logger.info(f"Total NFTs in collection = {sum(nfts_held.values())}") if eth_balances: logger.info(f"Getting NFT holdings and ETH balances...") df = pd.DataFrame(columns=["Address", asset_name, "ETH_balance"]) pbar = tqdm(nfts_held.items()) for idx, (address, num_nfts) in enumerate(pbar): pbar.set_description(f"{idx}") df.loc[idx] = [address, num_nfts, self.eth_api.get_eth_balance(address)] else: logger.info(f"Getting NFT holdings...") df = pd.DataFrame(columns=["Address", asset_name]) pbar = tqdm(nfts_held.items()) for idx, (address, num_nfts) in enumerate(pbar): pbar.set_description(f"{idx}") df.loc[idx] = [address, num_nfts] etherscan_links = [] for address in df["Address"]: etherscan_links.append(f"https://etherscan.io/address/{address}") df["Etherscan_link"] = etherscan_links opensea_links = [] for address in df["Address"]: opensea_links.append(f"https://opensea.io/{address}") df["OpenSea_link"] = opensea_links return df @staticmethod def calculate_rarity_df(asset_data: list, items_in_collection: int) -> pd.DataFrame: df = pd.DataFrame(columns=["Name", "Price", "Rarity", "RarityPriceRatio"]) for idx, asset in enumerate(asset_data): if asset["sell_orders"]: if asset["sell_orders"][0]["payment_token_contract"]["symbol"] == "ETH": price = float(asset["sell_orders"][0]["current_price"]) / 1e18 if price != 0: rarity = 0 for trait in asset["traits"]: trait_count = int(trait["trait_count"]) if trait_count != 0: rarity += 1 / (trait_count / items_in_collection) name = asset["name"] df.loc[idx] = [name, price, rarity, rarity / price] return df
true
true
f710efff7d7574d3bc12318a869b973a6e958e4c
1,376
py
Python
07patterns/proxy_patterns.py
edgells/python-commons
38c0aa0ec10304a4147ea231c92c9e34da462052
[ "MIT" ]
null
null
null
07patterns/proxy_patterns.py
edgells/python-commons
38c0aa0ec10304a4147ea231c92c9e34da462052
[ "MIT" ]
null
null
null
07patterns/proxy_patterns.py
edgells/python-commons
38c0aa0ec10304a4147ea231c92c9e34da462052
[ "MIT" ]
null
null
null
""" proxy patterns: 代理模式 为其它对象提供一种代理以控制对这个对象的操作 要素: 一个开放的方法集(interface) 实现相应方法集的proxy 对象 实现了相应方法集的类 应用: 远程代理, 为一个对象在不同地址空间提供局部代表, 这样就可以隐藏一个对象存在于不同地址空间的事实 哪么两个进程间, 是否可以通过这样的方式实现数据共享 虚拟代理, 根据需要创建开销很大的对象, 通过它存放实例化需要很长时间的真实对象 安全代理, 用来控制真实对象访问时的权限 """ class GiveGift: def give_dolls(self): raise NotImplemented("give dolls not implementation") def give_flowers(self): raise NotImplemented("give flowers not implementation") def give_give_chocolate(self): raise NotImplemented("give chocolate not implementation") class Pursuit(GiveGift): def __init__(self, mm): self.mm = mm def give_dolls(self): print(self.mm, "\t 送你娃娃") def give_flowers(self): print(self.mm, "\t 送你鲜花") def give_give_chocolate(self): print(self.mm, "\t 送你巧克力") class Proxy(GiveGift): def __init__(self, mm): self.gg = Pursuit(mm) def give_dolls(self): self.gg.give_dolls() def give_flowers(self): self.gg.give_flowers() def give_give_chocolate(self): self.gg.give_give_chocolate() def test(): mm = "娇娇" print("hello" + "world") proxy = Proxy(mm) proxy.give_dolls() proxy.give_flowers() proxy.give_give_chocolate() if __name__ == '__main__': test()
18.346667
65
0.630087
class GiveGift: def give_dolls(self): raise NotImplemented("give dolls not implementation") def give_flowers(self): raise NotImplemented("give flowers not implementation") def give_give_chocolate(self): raise NotImplemented("give chocolate not implementation") class Pursuit(GiveGift): def __init__(self, mm): self.mm = mm def give_dolls(self): print(self.mm, "\t 送你娃娃") def give_flowers(self): print(self.mm, "\t 送你鲜花") def give_give_chocolate(self): print(self.mm, "\t 送你巧克力") class Proxy(GiveGift): def __init__(self, mm): self.gg = Pursuit(mm) def give_dolls(self): self.gg.give_dolls() def give_flowers(self): self.gg.give_flowers() def give_give_chocolate(self): self.gg.give_give_chocolate() def test(): mm = "娇娇" print("hello" + "world") proxy = Proxy(mm) proxy.give_dolls() proxy.give_flowers() proxy.give_give_chocolate() if __name__ == '__main__': test()
true
true
f710f0a83392d109deba5e1325e4da0add75371c
992
py
Python
miranda/templates/eccc_conversion_legacy.py
Ouranosinc/miranda
5c54767a4e6e6c3c1f638ca0fe22673ea98e2746
[ "Apache-2.0" ]
4
2019-11-07T17:45:26.000Z
2021-09-22T18:22:01.000Z
miranda/templates/eccc_conversion_legacy.py
Ouranosinc/miranda
5c54767a4e6e6c3c1f638ca0fe22673ea98e2746
[ "Apache-2.0" ]
12
2019-09-19T17:05:39.000Z
2022-03-31T20:26:16.000Z
miranda/templates/eccc_conversion_legacy.py
Ouranosinc/miranda
5c54767a4e6e6c3c1f638ca0fe22673ea98e2746
[ "Apache-2.0" ]
1
2020-02-01T01:01:22.000Z
2020-02-01T01:01:22.000Z
from datetime import date from pathlib import Path from miranda.eccc import aggregate_nc_files, convert_hourly_flat_files if __name__ == "__main__": var_names = [ "atmospheric_pressure", "wind_speed", "relative_humidity", "dry_bulb_temperature", "freezing_rain", "ice_pellet_presence", "rainfall_amount", "precipitation_flux", ] station_file = "/home/tjs/Desktop/ec_data/Station Inventory EN.csv" source_data = Path("/home/tjs/Desktop/ec_data/eccc_all") convert_hourly_flat_files( source_files=source_data, output_folder=source_data, variables=var_names ) for var in var_names: out_file = source_data.joinpath( "{}_eccc_hourly_{}".format(var, date.today().strftime("%Y%m%d")) ) aggregate_nc_files( source_files=source_data, output_file=out_file, variables=var, station_inventory=station_file, )
28.342857
80
0.646169
from datetime import date from pathlib import Path from miranda.eccc import aggregate_nc_files, convert_hourly_flat_files if __name__ == "__main__": var_names = [ "atmospheric_pressure", "wind_speed", "relative_humidity", "dry_bulb_temperature", "freezing_rain", "ice_pellet_presence", "rainfall_amount", "precipitation_flux", ] station_file = "/home/tjs/Desktop/ec_data/Station Inventory EN.csv" source_data = Path("/home/tjs/Desktop/ec_data/eccc_all") convert_hourly_flat_files( source_files=source_data, output_folder=source_data, variables=var_names ) for var in var_names: out_file = source_data.joinpath( "{}_eccc_hourly_{}".format(var, date.today().strftime("%Y%m%d")) ) aggregate_nc_files( source_files=source_data, output_file=out_file, variables=var, station_inventory=station_file, )
true
true
f710f131b31a6ae3297050ebf6dc9c582f0bcce4
1,207
py
Python
emails/migrations/0001_initial.py
vftens/Django-CRM
fd02e42b2e9525abcc0e14ee924e5bdf569117bb
[ "MIT" ]
null
null
null
emails/migrations/0001_initial.py
vftens/Django-CRM
fd02e42b2e9525abcc0e14ee924e5bdf569117bb
[ "MIT" ]
null
null
null
emails/migrations/0001_initial.py
vftens/Django-CRM
fd02e42b2e9525abcc0e14ee924e5bdf569117bb
[ "MIT" ]
null
null
null
# Generated by Django 2.1.2 on 2019-01-28 07:07 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Email", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("from_email", models.EmailField(max_length=200)), ("to_email", models.EmailField(max_length=200)), ("subject", models.CharField(max_length=200)), ("message", models.CharField(max_length=200)), ("file", models.FileField(null=True, upload_to="files/")), ("send_time", models.DateTimeField(auto_now_add=True)), ("status", models.CharField(default="sent", max_length=200)), ("important", models.BooleanField(default=False, max_length=10)), ], options={"ordering": ["-id"],}, ), ]
32.621622
81
0.488815
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Email", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("from_email", models.EmailField(max_length=200)), ("to_email", models.EmailField(max_length=200)), ("subject", models.CharField(max_length=200)), ("message", models.CharField(max_length=200)), ("file", models.FileField(null=True, upload_to="files/")), ("send_time", models.DateTimeField(auto_now_add=True)), ("status", models.CharField(default="sent", max_length=200)), ("important", models.BooleanField(default=False, max_length=10)), ], options={"ordering": ["-id"],}, ), ]
true
true
f710f14079931a4defa63d5727d3ec20f1744236
1,799
py
Python
colors_from_mpl.py
smsaladi/fixthejet
b3089e6ee8cf2afbf24251de47702e0b1446eb73
[ "MIT" ]
3
2018-04-18T05:05:34.000Z
2019-04-30T01:41:10.000Z
colors_from_mpl.py
smsaladi/fixthejet
b3089e6ee8cf2afbf24251de47702e0b1446eb73
[ "MIT" ]
2
2018-03-29T16:28:23.000Z
2018-05-13T20:41:48.000Z
colors_from_mpl.py
smsaladi/fixthejet
b3089e6ee8cf2afbf24251de47702e0b1446eb73
[ "MIT" ]
null
null
null
""" Writes out hex colors from color scales provided in matplotlib into JS file python colors_from_mpl.py >> js/colorscales.js """ import itertools import json import numpy as np import matplotlib.colors import matplotlib.cm # Have colormaps separated into categories: # http://matplotlib.org/examples/color/colormaps_reference.html cmap_names = [ ('Perceptually Uniform Sequential', [ 'viridis', 'plasma', 'inferno', 'magma']), ('Sequential', [ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']), ('Sequential (2)', [ 'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']), ('Diverging', [ 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']), ('Qualitative', [ 'Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c']), ('Miscellaneous', [ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'hsv', 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar']) ] cm_names = [cat[1] for cat in cmap_names] print("var mpl_scales = {") for name in itertools.chain.from_iterable(cm_names): cmap = matplotlib.cm.get_cmap(name) values = np.linspace(0, 1, cmap.N) rgba = cmap(values) hex = np.apply_along_axis(matplotlib.colors.rgb2hex, axis=1, arr=rgba) print(' "{}": {},\n'.format(name, json.dumps(hex.tolist()))) print("};")
33.943396
74
0.595887
import itertools import json import numpy as np import matplotlib.colors import matplotlib.cm cmap_names = [ ('Perceptually Uniform Sequential', [ 'viridis', 'plasma', 'inferno', 'magma']), ('Sequential', [ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']), ('Sequential (2)', [ 'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']), ('Diverging', [ 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']), ('Qualitative', [ 'Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c']), ('Miscellaneous', [ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'hsv', 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar']) ] cm_names = [cat[1] for cat in cmap_names] print("var mpl_scales = {") for name in itertools.chain.from_iterable(cm_names): cmap = matplotlib.cm.get_cmap(name) values = np.linspace(0, 1, cmap.N) rgba = cmap(values) hex = np.apply_along_axis(matplotlib.colors.rgb2hex, axis=1, arr=rgba) print(' "{}": {},\n'.format(name, json.dumps(hex.tolist()))) print("};")
true
true
f710f3dcc85493b56211d6d60424c411329b33b7
697
py
Python
walter/common/walterWidgets/__init__.py
all-in-one-of/OpenWalter
c2034f7fac20b36ffe3e500c01d40b87e84e2b97
[ "libtiff" ]
187
2018-08-14T19:06:20.000Z
2022-03-04T06:03:25.000Z
walter/common/walterWidgets/__init__.py
all-in-one-of/OpenWalter
c2034f7fac20b36ffe3e500c01d40b87e84e2b97
[ "libtiff" ]
9
2018-08-22T15:34:48.000Z
2019-11-27T13:45:21.000Z
walter/common/walterWidgets/__init__.py
all-in-one-of/OpenWalter
c2034f7fac20b36ffe3e500c01d40b87e84e2b97
[ "libtiff" ]
41
2018-08-14T19:06:09.000Z
2021-09-04T20:01:10.000Z
# Copyright 2017 Rodeo FX. All rights reserved. from .utils import dpiScale from .utils import toPyObject from .walterBaseTreeView import ACTIONS from .walterBaseTreeView import BaseDelegate from .walterBaseTreeView import BaseItem from .walterBaseTreeView import BaseModel from .walterBaseTreeView import BaseTreeView from .walterBaseTreeView import NODE_BAR_COLOUR from .walterLayersView import LayersItem from .walterLayersView import LayersModel from .walterLayersView import LayersView from .walterComplexMenu import ComplexMenu from .walterBaseVariantsMenu import BaseVariantAction from .walterBaseVariantsMenu import BaseVariantSetMenu from .walterBaseVariantsMenu import BaseVariantsMenu
38.722222
54
0.875179
from .utils import dpiScale from .utils import toPyObject from .walterBaseTreeView import ACTIONS from .walterBaseTreeView import BaseDelegate from .walterBaseTreeView import BaseItem from .walterBaseTreeView import BaseModel from .walterBaseTreeView import BaseTreeView from .walterBaseTreeView import NODE_BAR_COLOUR from .walterLayersView import LayersItem from .walterLayersView import LayersModel from .walterLayersView import LayersView from .walterComplexMenu import ComplexMenu from .walterBaseVariantsMenu import BaseVariantAction from .walterBaseVariantsMenu import BaseVariantSetMenu from .walterBaseVariantsMenu import BaseVariantsMenu
true
true
f710f4117998ddf963e36f7ec2257386788aec0a
3,240
py
Python
examples/ssh/asyncssh-server.py
GoTodd/python-prompt-toolkit
a9488fbd2ab1dff8e736b6f15c8811a6e4702f0a
[ "BSD-3-Clause" ]
1
2021-07-09T15:46:40.000Z
2021-07-09T15:46:40.000Z
examples/ssh/asyncssh-server.py
GoTodd/python-prompt-toolkit
a9488fbd2ab1dff8e736b6f15c8811a6e4702f0a
[ "BSD-3-Clause" ]
1
2020-08-11T19:53:13.000Z
2020-08-11T19:53:13.000Z
examples/ssh/asyncssh-server.py
GoTodd/python-prompt-toolkit
a9488fbd2ab1dff8e736b6f15c8811a6e4702f0a
[ "BSD-3-Clause" ]
1
2020-10-28T01:55:03.000Z
2020-10-28T01:55:03.000Z
#!/usr/bin/env python """ Example of running a prompt_toolkit application in an asyncssh server. """ import asyncio import logging import asyncssh from pygments.lexers.html import HtmlLexer from prompt_toolkit.completion import WordCompleter from prompt_toolkit.contrib.ssh import PromptToolkitSSHServer, PromptToolkitSSHSession from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.shortcuts import ProgressBar, print_formatted_text from prompt_toolkit.shortcuts.dialogs import input_dialog, yes_no_dialog from prompt_toolkit.shortcuts.prompt import PromptSession animal_completer = WordCompleter( [ "alligator", "ant", "ape", "bat", "bear", "beaver", "bee", "bison", "butterfly", "cat", "chicken", "crocodile", "dinosaur", "dog", "dolphin", "dove", "duck", "eagle", "elephant", "fish", "goat", "gorilla", "kangaroo", "leopard", "lion", "mouse", "rabbit", "rat", "snake", "spider", "turkey", "turtle", ], ignore_case=True, ) async def interact(ssh_session: PromptToolkitSSHSession) -> None: """ The application interaction. This will run automatically in a prompt_toolkit AppSession, which means that any prompt_toolkit application (dialogs, prompts, etc...) will use the SSH channel for input and output. """ prompt_session = PromptSession() # Alias 'print_formatted_text', so that 'print' calls go to the SSH client. print = print_formatted_text print("We will be running a few prompt_toolkit applications through this ") print("SSH connection.\n") # Simple progress bar. with ProgressBar() as pb: for i in pb(range(50)): await asyncio.sleep(0.1) # Normal prompt. text = await prompt_session.prompt_async("(normal prompt) Type something: ") print("You typed", text) # Prompt with auto completion. text = await prompt_session.prompt_async( "(autocompletion) Type an animal: ", completer=animal_completer ) print("You typed", text) # prompt with syntax highlighting. text = await prompt_session.prompt_async( "(HTML syntax highlighting) Type something: ", lexer=PygmentsLexer(HtmlLexer) ) print("You typed", text) # Show yes/no dialog. await prompt_session.prompt_async("Showing yes/no dialog... [ENTER]") await yes_no_dialog("Yes/no dialog", "Running over asyncssh").run_async() # Show input dialog await prompt_session.prompt_async("Showing input dialog... [ENTER]") await input_dialog("Input dialog", "Running over asyncssh").run_async() def main(port=8222): # Set up logging. logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) loop = asyncio.get_event_loop() loop.run_until_complete( asyncssh.create_server( lambda: PromptToolkitSSHServer(interact), "", port, server_host_keys=["/etc/ssh/ssh_host_ecdsa_key"], ) ) loop.run_forever() if __name__ == "__main__": main()
26.557377
86
0.641975
import asyncio import logging import asyncssh from pygments.lexers.html import HtmlLexer from prompt_toolkit.completion import WordCompleter from prompt_toolkit.contrib.ssh import PromptToolkitSSHServer, PromptToolkitSSHSession from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.shortcuts import ProgressBar, print_formatted_text from prompt_toolkit.shortcuts.dialogs import input_dialog, yes_no_dialog from prompt_toolkit.shortcuts.prompt import PromptSession animal_completer = WordCompleter( [ "alligator", "ant", "ape", "bat", "bear", "beaver", "bee", "bison", "butterfly", "cat", "chicken", "crocodile", "dinosaur", "dog", "dolphin", "dove", "duck", "eagle", "elephant", "fish", "goat", "gorilla", "kangaroo", "leopard", "lion", "mouse", "rabbit", "rat", "snake", "spider", "turkey", "turtle", ], ignore_case=True, ) async def interact(ssh_session: PromptToolkitSSHSession) -> None: prompt_session = PromptSession() print = print_formatted_text print("We will be running a few prompt_toolkit applications through this ") print("SSH connection.\n") with ProgressBar() as pb: for i in pb(range(50)): await asyncio.sleep(0.1) text = await prompt_session.prompt_async("(normal prompt) Type something: ") print("You typed", text) text = await prompt_session.prompt_async( "(autocompletion) Type an animal: ", completer=animal_completer ) print("You typed", text) text = await prompt_session.prompt_async( "(HTML syntax highlighting) Type something: ", lexer=PygmentsLexer(HtmlLexer) ) print("You typed", text) await prompt_session.prompt_async("Showing yes/no dialog... [ENTER]") await yes_no_dialog("Yes/no dialog", "Running over asyncssh").run_async() await prompt_session.prompt_async("Showing input dialog... [ENTER]") await input_dialog("Input dialog", "Running over asyncssh").run_async() def main(port=8222): logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) loop = asyncio.get_event_loop() loop.run_until_complete( asyncssh.create_server( lambda: PromptToolkitSSHServer(interact), "", port, server_host_keys=["/etc/ssh/ssh_host_ecdsa_key"], ) ) loop.run_forever() if __name__ == "__main__": main()
true
true
f710f43f2783402dc0325a5df802bd24de543b39
5,432
py
Python
route/login_register.py
ProductiveAndEfficient/openNAMU
af3beee5d6e486a4cf152803483e3878b3347882
[ "BSD-3-Clause" ]
null
null
null
route/login_register.py
ProductiveAndEfficient/openNAMU
af3beee5d6e486a4cf152803483e3878b3347882
[ "BSD-3-Clause" ]
null
null
null
route/login_register.py
ProductiveAndEfficient/openNAMU
af3beee5d6e486a4cf152803483e3878b3347882
[ "BSD-3-Clause" ]
null
null
null
from .tool.func import * def login_register_2(conn): curs = conn.cursor() if ban_check(None, 'login') == 1: return re_error('/ban') ip = ip_check() admin = admin_check() if admin != 1 and ip_or_user(ip) == 0: return redirect('/user') if admin != 1: curs.execute(db_change('select data from other where name = "reg"')) set_d = curs.fetchall() if set_d and set_d[0][0] == 'on': return re_error('/ban') if flask.request.method == 'POST': if captcha_post(flask.request.form.get('g-recaptcha-response', flask.request.form.get('g-recaptcha', ''))) == 1: return re_error('/error/13') else: captcha_post('', 0) user_id = flask.request.form.get('id', '') user_pw = flask.request.form.get('pw', '') user_repeat = flask.request.form.get('pw2', '') if user_id == '' or user_pw == '': return re_error('/error/27') if user_pw != user_repeat: return re_error('/error/20') if re.search(r'(?:[^A-Za-zㄱ-힣0-9])', user_id): return re_error('/error/8') curs.execute(db_change('select html from html_filter where kind = "name"')) set_d = curs.fetchall() for i in set_d: check_r = re.compile(i[0], re.I) if check_r.search(user_id): return re_error('/error/8') if len(user_id) > 32: return re_error('/error/7') curs.execute(db_change("select id from user where id = ?"), [user_id]) if curs.fetchall(): return re_error('/error/6') curs.execute(db_change("select id from user_application where id = ?"), [user_id]) if curs.fetchall(): return re_error('/error/6') hashed = pw_encode(user_pw) ans_q = flask.request.form.get('approval_question_answer', '') curs.execute(db_change('select data from other where name = "requires_approval"')) requires_approval = curs.fetchall() requires_approval = requires_approval and requires_approval[0][0] == 'on' requires_approval = None if admin == 1 else requires_approval if requires_approval: curs.execute(db_change('select data from other where name = "approval_question"')) approval_question = curs.fetchall() approval_question = approval_question[0][0] if approval_question and approval_question[0][0] else '' else: approval_question = '' # c_id, c_pw, c_ans, c_que, c_key, c_type flask.session['c_id'] = user_id flask.session['c_pw'] = hashed flask.session['c_type'] = 'register' if requires_approval: flask.session['c_ans'] = flask.request.form.get('approval_question_answer', '') flask.session['c_que'] = approval_question curs.execute(db_change('select data from other where name = "email_have"')) sql_data = curs.fetchall() if sql_data and sql_data[0][0] != '' and admin != 1: flask.session['c_key'] = load_random_key(32) return redirect('/need_email') else: flask.session['c_key'] = 'email_pass' return redirect('/check_key') else: curs.execute(db_change('select data from other where name = "contract"')) data = curs.fetchall() contract = (data[0][0] + '<hr class="main_hr">') if data and data[0][0] != '' else '' approval_question = '' curs.execute(db_change('select data from other where name = "requires_approval"')) requires_approval = curs.fetchall() requires_approval = requires_approval and requires_approval[0][0] == 'on' requires_approval = None if admin == 1 else requires_approval if requires_approval: curs.execute(db_change('select data from other where name = "approval_question"')) data = curs.fetchall() if data and data[0][0] != '': approval_question = ''' <hr class="main_hr"> <span>''' + load_lang('approval_question') + ' : ' + data[0][0] + '''<span> <hr class="main_hr"> <input placeholder="''' + load_lang('approval_question') + '''" name="approval_question_answer" type="text"> <hr class="main_hr"> ''' return easy_minify(flask.render_template(skin_check(), imp = [load_lang('register'), wiki_set(), custom(), other2([0, 0])], data = ''' <form method="post"> ''' + contract + ''' <input placeholder="''' + load_lang('id') + '''" name="id" type="text"> <hr class="main_hr"> <input placeholder="''' + load_lang('password') + '''" name="pw" type="password"> <hr class="main_hr"> <input placeholder="''' + load_lang('password_confirm') + '''" name="pw2" type="password"> <hr class="main_hr"> ''' + approval_question + ''' ''' + captcha_get() + ''' <button type="submit">''' + load_lang('save') + '''</button> ''' + http_warrin() + ''' </form> ''', menu = [['user', load_lang('return')]] ))
41.784615
128
0.544919
from .tool.func import * def login_register_2(conn): curs = conn.cursor() if ban_check(None, 'login') == 1: return re_error('/ban') ip = ip_check() admin = admin_check() if admin != 1 and ip_or_user(ip) == 0: return redirect('/user') if admin != 1: curs.execute(db_change('select data from other where name = "reg"')) set_d = curs.fetchall() if set_d and set_d[0][0] == 'on': return re_error('/ban') if flask.request.method == 'POST': if captcha_post(flask.request.form.get('g-recaptcha-response', flask.request.form.get('g-recaptcha', ''))) == 1: return re_error('/error/13') else: captcha_post('', 0) user_id = flask.request.form.get('id', '') user_pw = flask.request.form.get('pw', '') user_repeat = flask.request.form.get('pw2', '') if user_id == '' or user_pw == '': return re_error('/error/27') if user_pw != user_repeat: return re_error('/error/20') if re.search(r'(?:[^A-Za-zㄱ-힣0-9])', user_id): return re_error('/error/8') curs.execute(db_change('select html from html_filter where kind = "name"')) set_d = curs.fetchall() for i in set_d: check_r = re.compile(i[0], re.I) if check_r.search(user_id): return re_error('/error/8') if len(user_id) > 32: return re_error('/error/7') curs.execute(db_change("select id from user where id = ?"), [user_id]) if curs.fetchall(): return re_error('/error/6') curs.execute(db_change("select id from user_application where id = ?"), [user_id]) if curs.fetchall(): return re_error('/error/6') hashed = pw_encode(user_pw) ans_q = flask.request.form.get('approval_question_answer', '') curs.execute(db_change('select data from other where name = "requires_approval"')) requires_approval = curs.fetchall() requires_approval = requires_approval and requires_approval[0][0] == 'on' requires_approval = None if admin == 1 else requires_approval if requires_approval: curs.execute(db_change('select data from other where name = "approval_question"')) approval_question = curs.fetchall() approval_question = approval_question[0][0] if approval_question and approval_question[0][0] else '' else: approval_question = '' flask.session['c_id'] = user_id flask.session['c_pw'] = hashed flask.session['c_type'] = 'register' if requires_approval: flask.session['c_ans'] = flask.request.form.get('approval_question_answer', '') flask.session['c_que'] = approval_question curs.execute(db_change('select data from other where name = "email_have"')) sql_data = curs.fetchall() if sql_data and sql_data[0][0] != '' and admin != 1: flask.session['c_key'] = load_random_key(32) return redirect('/need_email') else: flask.session['c_key'] = 'email_pass' return redirect('/check_key') else: curs.execute(db_change('select data from other where name = "contract"')) data = curs.fetchall() contract = (data[0][0] + '<hr class="main_hr">') if data and data[0][0] != '' else '' approval_question = '' curs.execute(db_change('select data from other where name = "requires_approval"')) requires_approval = curs.fetchall() requires_approval = requires_approval and requires_approval[0][0] == 'on' requires_approval = None if admin == 1 else requires_approval if requires_approval: curs.execute(db_change('select data from other where name = "approval_question"')) data = curs.fetchall() if data and data[0][0] != '': approval_question = ''' <hr class="main_hr"> <span>''' + load_lang('approval_question') + ' : ' + data[0][0] + '''<span> <hr class="main_hr"> <input placeholder="''' + load_lang('approval_question') + '''" name="approval_question_answer" type="text"> <hr class="main_hr"> ''' return easy_minify(flask.render_template(skin_check(), imp = [load_lang('register'), wiki_set(), custom(), other2([0, 0])], data = ''' <form method="post"> ''' + contract + ''' <input placeholder="''' + load_lang('id') + '''" name="id" type="text"> <hr class="main_hr"> <input placeholder="''' + load_lang('password') + '''" name="pw" type="password"> <hr class="main_hr"> <input placeholder="''' + load_lang('password_confirm') + '''" name="pw2" type="password"> <hr class="main_hr"> ''' + approval_question + ''' ''' + captcha_get() + ''' <button type="submit">''' + load_lang('save') + '''</button> ''' + http_warrin() + ''' </form> ''', menu = [['user', load_lang('return')]] ))
true
true
f710f564a7de8e73147bdf29014882d066a8fb91
2,157
py
Python
src/charm.py
manadart/service-discovery-operator
aca8ee64405d549e9b03a324478d15427922e567
[ "Apache-2.0" ]
null
null
null
src/charm.py
manadart/service-discovery-operator
aca8ee64405d549e9b03a324478d15427922e567
[ "Apache-2.0" ]
null
null
null
src/charm.py
manadart/service-discovery-operator
aca8ee64405d549e9b03a324478d15427922e567
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # Copyright 2022 joseph # See LICENSE file for licensing details. # # Learn more at: https://juju.is/docs/sdk import logging from ops.charm import CharmBase from ops.framework import StoredState from ops.main import main from ops.model import ActiveStatus from charms.service_discovery_operator.v0.event import DiscoveryEventCharmEvents from charms.service_discovery_operator.v0.service_discovery import ServiceDiscovery logger = logging.getLogger(__name__) class ServiceDiscoveryCharm(CharmBase): on = DiscoveryEventCharmEvents() _stored = StoredState() def __init__(self, *args): super().__init__(*args) self._stored.set_default(discovery_pid=None) self._stored.set_default(discovery_payload=None) self._service_discovery = ServiceDiscovery(self) self.framework.observe(self.on.start, self._on_start) self.framework.observe(self.on.discovery, self._on_discovery) self.framework.observe(self.on.leader_elected, self._on_leader_elected) def _on_start(self, event): self.unit.status = ActiveStatus() def _on_leader_elected(self, event): if self.unit.is_leader(): self._service_discovery.start_discovery() else: self._service_discovery.stop_discovery() def _on_discovery(self, event): self.unit.status = ActiveStatus(self._read_discovery_payload()) def _read_discovery_payload(self): with open(self.payload_file_name, 'r') as f: return f.read() @property def unit_tag(self): unit_num = self.unit.name.split("/")[-1] return "unit-{}-{}".format(self.app.name, unit_num) @property def discovery_pid(self): return self._stored.discovery_pid @discovery_pid.setter def discovery_pid(self, pid): self._stored.discovery_pid = pid @property def payload_file_name(self): return self._stored.payload_file_name @payload_file_name.setter def payload_file_name(self, file_name): self._stored.payload_file_name = file_name if __name__ == "__main__": main(ServiceDiscoveryCharm)
28.381579
83
0.713027
import logging from ops.charm import CharmBase from ops.framework import StoredState from ops.main import main from ops.model import ActiveStatus from charms.service_discovery_operator.v0.event import DiscoveryEventCharmEvents from charms.service_discovery_operator.v0.service_discovery import ServiceDiscovery logger = logging.getLogger(__name__) class ServiceDiscoveryCharm(CharmBase): on = DiscoveryEventCharmEvents() _stored = StoredState() def __init__(self, *args): super().__init__(*args) self._stored.set_default(discovery_pid=None) self._stored.set_default(discovery_payload=None) self._service_discovery = ServiceDiscovery(self) self.framework.observe(self.on.start, self._on_start) self.framework.observe(self.on.discovery, self._on_discovery) self.framework.observe(self.on.leader_elected, self._on_leader_elected) def _on_start(self, event): self.unit.status = ActiveStatus() def _on_leader_elected(self, event): if self.unit.is_leader(): self._service_discovery.start_discovery() else: self._service_discovery.stop_discovery() def _on_discovery(self, event): self.unit.status = ActiveStatus(self._read_discovery_payload()) def _read_discovery_payload(self): with open(self.payload_file_name, 'r') as f: return f.read() @property def unit_tag(self): unit_num = self.unit.name.split("/")[-1] return "unit-{}-{}".format(self.app.name, unit_num) @property def discovery_pid(self): return self._stored.discovery_pid @discovery_pid.setter def discovery_pid(self, pid): self._stored.discovery_pid = pid @property def payload_file_name(self): return self._stored.payload_file_name @payload_file_name.setter def payload_file_name(self, file_name): self._stored.payload_file_name = file_name if __name__ == "__main__": main(ServiceDiscoveryCharm)
true
true
f710f6dafcfddb3ac08084fae91ac3551fd92098
607
py
Python
example_project/example_app/models.py
IgnisDa/django-tokens
02069ed7ea9487c4ed52af99e2d0d704c018ea79
[ "Apache-2.0" ]
null
null
null
example_project/example_app/models.py
IgnisDa/django-tokens
02069ed7ea9487c4ed52af99e2d0d704c018ea79
[ "Apache-2.0" ]
null
null
null
example_project/example_app/models.py
IgnisDa/django-tokens
02069ed7ea9487c4ed52af99e2d0d704c018ea79
[ "Apache-2.0" ]
null
null
null
from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from . import managers class CustomUser(AbstractUser): username = models.CharField( max_length=150, help_text=_("The username of the user."), unique=True ) email = models.EmailField(help_text=_("Email of the user."), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = managers.CustomUserManager() class Meta: ordering = ("id",) def __str__(self): return f"{self.email}'s account"
25.291667
77
0.69687
from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from . import managers class CustomUser(AbstractUser): username = models.CharField( max_length=150, help_text=_("The username of the user."), unique=True ) email = models.EmailField(help_text=_("Email of the user."), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = managers.CustomUserManager() class Meta: ordering = ("id",) def __str__(self): return f"{self.email}'s account"
true
true
f710f843c30bce62ef56f5d70535c8feb9462389
85
py
Python
tests/test_reml.py
jgalar/reml
a1031e9d4a92508d8c4658dc9ad3c1ee2532788a
[ "MIT" ]
null
null
null
tests/test_reml.py
jgalar/reml
a1031e9d4a92508d8c4658dc9ad3c1ee2532788a
[ "MIT" ]
null
null
null
tests/test_reml.py
jgalar/reml
a1031e9d4a92508d8c4658dc9ad3c1ee2532788a
[ "MIT" ]
null
null
null
from reml import __version__ def test_version(): assert __version__ == "0.1.0"
14.166667
33
0.705882
from reml import __version__ def test_version(): assert __version__ == "0.1.0"
true
true
f710f93ca310a569f1514937b149a28f034cb42f
949
py
Python
warehouse_manager/main/migrations/0007_remove_warehousereply_files_alter_ticketimage_ticket_and_more.py
dzhigaev/warehouse_manager
3f81d2d889f3bec3cb0f9fd9c5aa053e34d4740f
[ "MIT" ]
null
null
null
warehouse_manager/main/migrations/0007_remove_warehousereply_files_alter_ticketimage_ticket_and_more.py
dzhigaev/warehouse_manager
3f81d2d889f3bec3cb0f9fd9c5aa053e34d4740f
[ "MIT" ]
null
null
null
warehouse_manager/main/migrations/0007_remove_warehousereply_files_alter_ticketimage_ticket_and_more.py
dzhigaev/warehouse_manager
3f81d2d889f3bec3cb0f9fd9c5aa053e34d4740f
[ "MIT" ]
null
null
null
# Generated by Django 4.0 on 2022-01-25 21:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0006_ticketimage_external_url_alter_warehousereply_files'), ] operations = [ migrations.RemoveField( model_name='warehousereply', name='files', ), migrations.AlterField( model_name='ticketimage', name='ticket', field=models.ManyToManyField(to='main.Tickets'), ), migrations.CreateModel( name='ReplyImage', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file', models.FileField(blank=True, max_length=255, upload_to='replyfiles/%Y/%m/%d')), ('reply', models.ManyToManyField(to='main.WarehouseReply')), ], ), ]
30.612903
117
0.584826
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0006_ticketimage_external_url_alter_warehousereply_files'), ] operations = [ migrations.RemoveField( model_name='warehousereply', name='files', ), migrations.AlterField( model_name='ticketimage', name='ticket', field=models.ManyToManyField(to='main.Tickets'), ), migrations.CreateModel( name='ReplyImage', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file', models.FileField(blank=True, max_length=255, upload_to='replyfiles/%Y/%m/%d')), ('reply', models.ManyToManyField(to='main.WarehouseReply')), ], ), ]
true
true
f710f9e7c439c261ad1bf7d1d5b544451f4cc069
1,042
py
Python
stubs.min/System/Windows/Forms/__init___parts/ProgressBarStyle.py
ricardyn/ironpython-stubs
4d2b405eda3ceed186e8adca55dd97c332c6f49d
[ "MIT" ]
1
2021-02-02T13:39:16.000Z
2021-02-02T13:39:16.000Z
stubs.min/System/Windows/Forms/__init___parts/ProgressBarStyle.py
hdm-dt-fb/ironpython-stubs
4d2b405eda3ceed186e8adca55dd97c332c6f49d
[ "MIT" ]
null
null
null
stubs.min/System/Windows/Forms/__init___parts/ProgressBarStyle.py
hdm-dt-fb/ironpython-stubs
4d2b405eda3ceed186e8adca55dd97c332c6f49d
[ "MIT" ]
null
null
null
class ProgressBarStyle(Enum,IComparable,IFormattable,IConvertible): """ Specifies the style that a System.Windows.Forms.ProgressBar uses to indicate the progress of an operation. enum ProgressBarStyle,values: Blocks (0),Continuous (1),Marquee (2) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self,*args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self,*args): pass def __gt__(self,*args): 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 def __le__(self,*args): pass def __lt__(self,*args): pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass Blocks=None Continuous=None Marquee=None value__=None
29.771429
215
0.676583
class ProgressBarStyle(Enum,IComparable,IFormattable,IConvertible): pass """ __format__(formattable: IFormattable,format: str) -> str """ pass pass def __gt__(self,*args): 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 pass def __lt__(self,*args): pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass Blocks=None Continuous=None Marquee=None value__=None
true
true
f710fa23050dd716d54383573b4029851899a772
2,989
py
Python
data_fill/banks_closest.py
hhalim/TargetBanks
8febd7300f3b01e92641e0f63355d3f66bfe674c
[ "MIT" ]
null
null
null
data_fill/banks_closest.py
hhalim/TargetBanks
8febd7300f3b01e92641e0f63355d3f66bfe674c
[ "MIT" ]
null
null
null
data_fill/banks_closest.py
hhalim/TargetBanks
8febd7300f3b01e92641e0f63355d3f66bfe674c
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import config as cfg import pyodbc """ Fill in closest Police Stations within 10 miles If there is no closest PS, then ClosestPSDistance = MeanPSDistance = 10.5 miles Latitude/Longitude distance coefficients: --Miles 3958.75 --Kilometers 6367.45 --Feet 20890584 --Meters 6367450 """ def calculate_distance(bankID, lat, lng): query = """ DECLARE @latitude float, @longitude float SELECT @latitude = ?, @longitude = ? SELECT [StationID] ,[Name] , [Address1] , [City] , [State] , Distance FROM ( SELECT [StationID] ,[Name] , [Address1] , [City] , [State] , ( 3959 * acos( cos( radians(@latitude) ) * cos( radians( Lat ) ) * cos( radians( Lng ) - radians(@longitude) ) + sin( radians(@latitude) ) * sin( radians( Lat ) ) ) ) AS Distance FROM PoliceStation ) as x WHERE Distance <= 10 ORDER BY Distance; """ cnxn = pyodbc.connect( 'DRIVER={ODBC Driver 13 for SQL Server};SERVER=' + cfg.mssql['server'] + ';DATABASE=' + cfg.mssql['database'] + ';UID=' + cfg.mssql['username'] + ';PWD=' + cfg.mssql['password'] ) cursor = cnxn.cursor() params = [lat, lng] rows = cursor.execute(query, params) #Calculate psCount = 0 totdist = 0 closestStationID = None for row in rows: totdist = totdist + float(row.Distance) if(psCount == 0): print(bankID, row.StationID, row.Name, row.City, row.Distance) closestStationID = row.StationID closestPSDistance = float(row.Distance) psCount = psCount + 1 meanPSDistance = totdist / psCount if psCount else None # Save back into table query2 = """ UPDATE Bank SET ClosestStationID = ? , ClosestPSDistance = ? , MeanPSDistance = ? , PSCount = ? WHERE BankID = ? ; """ over10 = 10.5 #over 10 miles if not closestStationID: #no closest station in 10 miles closestStationID = None closestPSDistance = over10 meanPSDistance = over10 psCount = 0 params2 = [closestStationID, closestPSDistance, meanPSDistance, psCount, bankID] cursor.execute(query2, params2) cnxn.commit() #---------------------------------------------- # Calculate distance for all rows cnxn = pyodbc.connect( 'DRIVER={ODBC Driver 13 for SQL Server};SERVER=' + cfg.mssql['server'] + ';DATABASE=' + cfg.mssql['database'] + ';UID=' + cfg.mssql['username'] + ';PWD=' + cfg.mssql['password'] ) cursor = cnxn.cursor() query = "SELECT bankID, lat, lng FROM Bank WHERE [ClosestPSDistance] IS NULL;" rows = cursor.execute(query) for row in rows: calculate_distance(row.bankID, row.lat, row.lng)
29.594059
119
0.557042
import config as cfg import pyodbc def calculate_distance(bankID, lat, lng): query = """ DECLARE @latitude float, @longitude float SELECT @latitude = ?, @longitude = ? SELECT [StationID] ,[Name] , [Address1] , [City] , [State] , Distance FROM ( SELECT [StationID] ,[Name] , [Address1] , [City] , [State] , ( 3959 * acos( cos( radians(@latitude) ) * cos( radians( Lat ) ) * cos( radians( Lng ) - radians(@longitude) ) + sin( radians(@latitude) ) * sin( radians( Lat ) ) ) ) AS Distance FROM PoliceStation ) as x WHERE Distance <= 10 ORDER BY Distance; """ cnxn = pyodbc.connect( 'DRIVER={ODBC Driver 13 for SQL Server};SERVER=' + cfg.mssql['server'] + ';DATABASE=' + cfg.mssql['database'] + ';UID=' + cfg.mssql['username'] + ';PWD=' + cfg.mssql['password'] ) cursor = cnxn.cursor() params = [lat, lng] rows = cursor.execute(query, params) psCount = 0 totdist = 0 closestStationID = None for row in rows: totdist = totdist + float(row.Distance) if(psCount == 0): print(bankID, row.StationID, row.Name, row.City, row.Distance) closestStationID = row.StationID closestPSDistance = float(row.Distance) psCount = psCount + 1 meanPSDistance = totdist / psCount if psCount else None query2 = """ UPDATE Bank SET ClosestStationID = ? , ClosestPSDistance = ? , MeanPSDistance = ? , PSCount = ? WHERE BankID = ? ; """ over10 = 10.5 if not closestStationID: closestStationID = None closestPSDistance = over10 meanPSDistance = over10 psCount = 0 params2 = [closestStationID, closestPSDistance, meanPSDistance, psCount, bankID] cursor.execute(query2, params2) cnxn.commit() cnxn = pyodbc.connect( 'DRIVER={ODBC Driver 13 for SQL Server};SERVER=' + cfg.mssql['server'] + ';DATABASE=' + cfg.mssql['database'] + ';UID=' + cfg.mssql['username'] + ';PWD=' + cfg.mssql['password'] ) cursor = cnxn.cursor() query = "SELECT bankID, lat, lng FROM Bank WHERE [ClosestPSDistance] IS NULL;" rows = cursor.execute(query) for row in rows: calculate_distance(row.bankID, row.lat, row.lng)
true
true
f710fa70daba0358925a0155ad3cb8fdb4671af0
4,050
py
Python
train.py
Wesley-Tse/Road-Detection
c3b444287d9b41ccc4234e737e4421b5d1b3c3da
[ "Apache-2.0" ]
null
null
null
train.py
Wesley-Tse/Road-Detection
c3b444287d9b41ccc4234e737e4421b5d1b3c3da
[ "Apache-2.0" ]
null
null
null
train.py
Wesley-Tse/Road-Detection
c3b444287d9b41ccc4234e737e4421b5d1b3c3da
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @author: Wesley # @time: 2020-12-11 10:47 import os import time import torch from torch import nn from models.dinknet34 import DinkNet34 from loss import dice_bce_loss from models.unet import UNet from dataset import MyDataset from torch.utils.data import DataLoader img_path = r'E:\PyCharmProject\datasets\5k\train_set\JPEGImages' mask_path = r'E:\PyCharmProject\datasets\5k\train_set\SegmentationClass' val_img_path = r'E:\PyCharmProject\datasets\5k\validate_set\JPEGImages' val_mask_path = r'E:\PyCharmProject\datasets\5k\validate_set\SegmentationClass' log = './dinknet.txt' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') batch_size_per = 16 batch_size = batch_size_per * torch.cuda.device_count() epoch_limit = 10 net = DinkNet34().to(device) net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count())) weight = r'E:\PyCharmProject\Road-Detection\weights\dinknet34.pt' # if os.path.exists(weight): # net.load_state_dict(torch.load(weight)) train_dataset = MyDataset(img_path, mask_path) val_dataset = MyDataset(val_img_path, val_mask_path) train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) val_dataloader = DataLoader(val_dataset, batch_size=batch_size) adam = torch.optim.Adam(net.parameters(), lr=2e-4) sgd = torch.optim.SGD(net.parameters(), lr=0.01, momentum=0.9) loss_fun = dice_bce_loss() if __name__ == '__main__': epoch = 1 log = open(log, 'w', encoding='utf-8') log.write('epoch' + '\t' + 'loss' + '\t' + 'pa' + '\t' + 'iou' + '\t' + 'precision' + '\n') log.flush() while epoch < 300: s_time = time.time() print('epoch - {} - training'.format(epoch)) net.train() TP = FP = TN = FN = 0 pa = 0 iou = 0 stop = 0 flag = 0 train_loss = 0 batch = len(train_dataloader) for i, (img, mask) in enumerate(train_dataloader): img = img.to(device) mask = mask.to(device) out = net(img) loss = loss_fun(mask, out) adam.zero_grad() loss.backward() adam.step() if i % 10 == 0: print('{}: {}/{} - loss: {}'.format(epoch, i, batch, loss.item())) # torch.save(net.state_dict(), weight) # print('save success') train_loss += loss.item() epoch_loss = train_loss / len(train_dataloader) e_time = time.time() print('epoch - {} - epoch_loss: {}'.format(epoch, epoch_loss)) print('total-time: ', e_time - s_time) print('epoch - {} - evaluating'.format(epoch)) net.eval() for img, mask in val_dataloader: img = img.to(device) mask = mask.to(device) with torch.no_grad(): pred = net(img) pred[pred >= 0.5] = 1 pred[pred < 0.5] = 0 TP += ((pred == 1) & (mask == 1)).cpu().sum().item() TN += ((pred == 0) & (mask == 0)).cpu().sum().item() FN += ((pred == 0) & (mask == 1)).cpu().sum().item() FP += ((pred == 1) & (mask == 0)).cpu().sum().item() pa = (TP + TN) / (TP + TN + FP + FN) precision = TP / (TP + FN) iou = TP / (TP + FP + FN) print('pa: ', pa) print('iou: ', iou) print('precision', precision) log.write( str(epoch) + '\t' + str(epoch_loss) + '\t' + str(pa) + '\t' + str(iou) + '\t' + str(precision) + '\n') log.flush() if iou > stop: stop = iou torch.save(net.state_dict(), weight) print("save success,iou updated to: {}".format(iou)) flag = 0 else: flag += 1 print("pa为{},没有提升,参数未更新,iou为{},第{}次未更新".format(iou, stop, flag)) if flag >= epoch_limit: print("early stop at epoch {}, finally iou: {}".format(epoch, stop)) break epoch += 1 log.close()
33.471074
114
0.564691
import os import time import torch from torch import nn from models.dinknet34 import DinkNet34 from loss import dice_bce_loss from models.unet import UNet from dataset import MyDataset from torch.utils.data import DataLoader img_path = r'E:\PyCharmProject\datasets\5k\train_set\JPEGImages' mask_path = r'E:\PyCharmProject\datasets\5k\train_set\SegmentationClass' val_img_path = r'E:\PyCharmProject\datasets\5k\validate_set\JPEGImages' val_mask_path = r'E:\PyCharmProject\datasets\5k\validate_set\SegmentationClass' log = './dinknet.txt' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') batch_size_per = 16 batch_size = batch_size_per * torch.cuda.device_count() epoch_limit = 10 net = DinkNet34().to(device) net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count())) weight = r'E:\PyCharmProject\Road-Detection\weights\dinknet34.pt' train_dataset = MyDataset(img_path, mask_path) val_dataset = MyDataset(val_img_path, val_mask_path) train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) val_dataloader = DataLoader(val_dataset, batch_size=batch_size) adam = torch.optim.Adam(net.parameters(), lr=2e-4) sgd = torch.optim.SGD(net.parameters(), lr=0.01, momentum=0.9) loss_fun = dice_bce_loss() if __name__ == '__main__': epoch = 1 log = open(log, 'w', encoding='utf-8') log.write('epoch' + '\t' + 'loss' + '\t' + 'pa' + '\t' + 'iou' + '\t' + 'precision' + '\n') log.flush() while epoch < 300: s_time = time.time() print('epoch - {} - training'.format(epoch)) net.train() TP = FP = TN = FN = 0 pa = 0 iou = 0 stop = 0 flag = 0 train_loss = 0 batch = len(train_dataloader) for i, (img, mask) in enumerate(train_dataloader): img = img.to(device) mask = mask.to(device) out = net(img) loss = loss_fun(mask, out) adam.zero_grad() loss.backward() adam.step() if i % 10 == 0: print('{}: {}/{} - loss: {}'.format(epoch, i, batch, loss.item())) train_loss += loss.item() epoch_loss = train_loss / len(train_dataloader) e_time = time.time() print('epoch - {} - epoch_loss: {}'.format(epoch, epoch_loss)) print('total-time: ', e_time - s_time) print('epoch - {} - evaluating'.format(epoch)) net.eval() for img, mask in val_dataloader: img = img.to(device) mask = mask.to(device) with torch.no_grad(): pred = net(img) pred[pred >= 0.5] = 1 pred[pred < 0.5] = 0 TP += ((pred == 1) & (mask == 1)).cpu().sum().item() TN += ((pred == 0) & (mask == 0)).cpu().sum().item() FN += ((pred == 0) & (mask == 1)).cpu().sum().item() FP += ((pred == 1) & (mask == 0)).cpu().sum().item() pa = (TP + TN) / (TP + TN + FP + FN) precision = TP / (TP + FN) iou = TP / (TP + FP + FN) print('pa: ', pa) print('iou: ', iou) print('precision', precision) log.write( str(epoch) + '\t' + str(epoch_loss) + '\t' + str(pa) + '\t' + str(iou) + '\t' + str(precision) + '\n') log.flush() if iou > stop: stop = iou torch.save(net.state_dict(), weight) print("save success,iou updated to: {}".format(iou)) flag = 0 else: flag += 1 print("pa为{},没有提升,参数未更新,iou为{},第{}次未更新".format(iou, stop, flag)) if flag >= epoch_limit: print("early stop at epoch {}, finally iou: {}".format(epoch, stop)) break epoch += 1 log.close()
true
true
f710fa824dd142658303167ff27d7e85e9f7eece
2,813
py
Python
clamm/streams/plot_big_stft.py
p5a0u9l/clamm
a41ce2526e9792ce08263bf27eb9c417608d1f5d
[ "MIT" ]
1
2021-05-26T03:55:23.000Z
2021-05-26T03:55:23.000Z
clamm/streams/plot_big_stft.py
p5a0u9l/clamm
a41ce2526e9792ce08263bf27eb9c417608d1f5d
[ "MIT" ]
null
null
null
clamm/streams/plot_big_stft.py
p5a0u9l/clamm
a41ce2526e9792ce08263bf27eb9c417608d1f5d
[ "MIT" ]
null
null
null
""" Convert a large audio wav file (album length, i.e. > 30 minutes typically) into a series of videos consisting of the audio synchronized with images of the spectrogram. """ import os import sys import multiprocessing as mp import subprocess import tqdm import numpy as np import librosa.core import librosa.display import librosa.feature import matplotlib.pyplot as plt plt.switch_backend("agg") SAMPLERATE = 44.1e3 # samples/sec WAVPATH = sys.argv[1] BASENAME = os.path.basename(WAVPATH).replace(".wav", "") ROOT = "/mnt/nfs-share/music/data" FRAMEROOT = ROOT + "/frames/" + BASENAME DURATION = 20 # NUMPROC = 8 FFTFREQ = librosa.fft_frequencies(sr=SAMPLERATE) F_MAX = np.max(FFTFREQ) N_FFT = 2048 N_HOP = int(1.0 / 4 * N_FFT) FILETIME = librosa.core.get_duration(filename=WAVPATH) NFRAME = int(FILETIME) / DURATION # allow truncation DUMPFILE = "data.npy" FPS = 5 def single_image(argtuple): y, i_frame, i_second = argtuple fractional_second = float(i_second) / FPS abs_index = i_frame * DURATION * FPS + i_second time = DURATION*i_frame + fractional_second titlestr = "%s - file time %0.2f seconds" % (BASENAME, time) # display the spectrogram plt.figure(figsize=(18, 8)) librosa.display.specshow( y, x_axis='time', y_axis='mel', sr=SAMPLERATE, hop_length=N_HOP) plt.vlines( fractional_second, 0, F_MAX, linestyles='dashed', colors='w', alpha=0.6) plt.title(titlestr) plt.savefig(FRAMEROOT + "/%05d.png" % (abs_index)) plt.tight_layout() plt.close() def main(): """ main """ pbar = tqdm.tqdm(total=NFRAME) pool = mp.Pool(NUMPROC) init = False if not os.path.exists(FRAMEROOT): os.makedirs(FRAMEROOT) for i_frame in range(10, NFRAME): # load the audio x, sr = librosa.core.load( WAVPATH, sr=SAMPLERATE, offset=DURATION * i_frame, duration=DURATION) # compute the spectrogram x = librosa.power_to_db( librosa.feature.melspectrogram( y=x, hop_length=N_HOP, n_fft=N_FFT, sr=SAMPLERATE), ref=np.max) if not init: f_mean = np.sum(x, axis=1) init = True else: f_mean += np.sum(x, axis=1) # loop updates pbar.update(1) pool.map( single_image, [(x, i_frame, i_second) for i_second in range(FPS*DURATION)]) np.save(BASENAME + 'f_mean.npy', f_mean) pbar.close() subprocess.call([ "ffmpeg", '-r', '5', '-i', FRAMEROOT + '%05d.png', '-i', WAVPATH, '-shortest', '-c:v', 'libx264', '-c:a', 'aac', '-strict', '-2', '-pix_fmt', 'yuv420p', '-crf', '23', '-r', '5', '-y', ROOT + "/videos/" + BASENAME + '.mp4']) if __name__ == '__main__': main()
27.048077
79
0.618557
import os import sys import multiprocessing as mp import subprocess import tqdm import numpy as np import librosa.core import librosa.display import librosa.feature import matplotlib.pyplot as plt plt.switch_backend("agg") SAMPLERATE = 44.1e3 WAVPATH = sys.argv[1] BASENAME = os.path.basename(WAVPATH).replace(".wav", "") ROOT = "/mnt/nfs-share/music/data" FRAMEROOT = ROOT + "/frames/" + BASENAME DURATION = 20 NUMPROC = 8 FFTFREQ = librosa.fft_frequencies(sr=SAMPLERATE) F_MAX = np.max(FFTFREQ) N_FFT = 2048 N_HOP = int(1.0 / 4 * N_FFT) FILETIME = librosa.core.get_duration(filename=WAVPATH) NFRAME = int(FILETIME) / DURATION DUMPFILE = "data.npy" FPS = 5 def single_image(argtuple): y, i_frame, i_second = argtuple fractional_second = float(i_second) / FPS abs_index = i_frame * DURATION * FPS + i_second time = DURATION*i_frame + fractional_second titlestr = "%s - file time %0.2f seconds" % (BASENAME, time) plt.figure(figsize=(18, 8)) librosa.display.specshow( y, x_axis='time', y_axis='mel', sr=SAMPLERATE, hop_length=N_HOP) plt.vlines( fractional_second, 0, F_MAX, linestyles='dashed', colors='w', alpha=0.6) plt.title(titlestr) plt.savefig(FRAMEROOT + "/%05d.png" % (abs_index)) plt.tight_layout() plt.close() def main(): pbar = tqdm.tqdm(total=NFRAME) pool = mp.Pool(NUMPROC) init = False if not os.path.exists(FRAMEROOT): os.makedirs(FRAMEROOT) for i_frame in range(10, NFRAME): x, sr = librosa.core.load( WAVPATH, sr=SAMPLERATE, offset=DURATION * i_frame, duration=DURATION) x = librosa.power_to_db( librosa.feature.melspectrogram( y=x, hop_length=N_HOP, n_fft=N_FFT, sr=SAMPLERATE), ref=np.max) if not init: f_mean = np.sum(x, axis=1) init = True else: f_mean += np.sum(x, axis=1) pbar.update(1) pool.map( single_image, [(x, i_frame, i_second) for i_second in range(FPS*DURATION)]) np.save(BASENAME + 'f_mean.npy', f_mean) pbar.close() subprocess.call([ "ffmpeg", '-r', '5', '-i', FRAMEROOT + '%05d.png', '-i', WAVPATH, '-shortest', '-c:v', 'libx264', '-c:a', 'aac', '-strict', '-2', '-pix_fmt', 'yuv420p', '-crf', '23', '-r', '5', '-y', ROOT + "/videos/" + BASENAME + '.mp4']) if __name__ == '__main__': main()
true
true
f710fad258d902d6f03329a00440cfd3df370e4a
964
py
Python
quiz_data.py
ashutoshkrris/GUI-Quiz-Tkinter
4d88fa9543b52d83b398c5f4796bc7e10f6c6f33
[ "MIT" ]
10
2021-10-31T04:28:43.000Z
2022-02-27T20:10:31.000Z
quiz_data.py
ashutoshkrris/GUI-Quiz-Tkinter
4d88fa9543b52d83b398c5f4796bc7e10f6c6f33
[ "MIT" ]
null
null
null
quiz_data.py
ashutoshkrris/GUI-Quiz-Tkinter
4d88fa9543b52d83b398c5f4796bc7e10f6c6f33
[ "MIT" ]
2
2021-11-25T20:36:54.000Z
2021-12-26T04:26:48.000Z
import requests parameters = { "amount": 10, "type": "multiple" } response = requests.get(url="https://opentdb.com/api.php", params=parameters) question_data = response.json()["results"] """ Sample Response [ { 'category': 'Sports', 'type': 'multiple', 'difficulty': 'medium', 'question': 'Which Formula One driver was nicknamed &#039;The Professor&#039;?', 'correct_answer': 'Alain Prost', 'incorrect_answers': [ 'Ayrton Senna', 'Niki Lauda', 'Emerson Fittipaldi' ] }, { 'category': 'Entertainment: Music', 'type': 'multiple', 'difficulty': 'medium', 'question': 'In which city did American rap producer DJ Khaled originate from?', 'correct_answer': 'Miami', 'incorrect_answers': [ 'New York', 'Detroit', 'Atlanta' ] } ] """
22.952381
88
0.51971
import requests parameters = { "amount": 10, "type": "multiple" } response = requests.get(url="https://opentdb.com/api.php", params=parameters) question_data = response.json()["results"]
true
true
f710fada49d8e202c88e0310925e822723cb3e6e
890
py
Python
mglearn/plot_animal_tree.py
mbooali/introduction-to-machine
3f75f9897f1f63f07bb6eace312fa35e16786623
[ "MIT" ]
51
2019-02-01T19:43:37.000Z
2022-03-16T09:07:03.000Z
mglearn/plot_animal_tree.py
mbooali/introduction-to-machine
3f75f9897f1f63f07bb6eace312fa35e16786623
[ "MIT" ]
2
2019-02-23T18:54:22.000Z
2019-11-09T01:30:32.000Z
mglearn/plot_animal_tree.py
mbooali/introduction-to-machine
3f75f9897f1f63f07bb6eace312fa35e16786623
[ "MIT" ]
35
2019-02-08T02:00:31.000Z
2022-03-01T23:17:00.000Z
from imageio import imread import matplotlib.pyplot as plt def plot_animal_tree(ax=None): import graphviz if ax is None: ax = plt.gca() mygraph = graphviz.Digraph(node_attr={'shape': 'box'}, edge_attr={'labeldistance': "10.5"}, format="png") mygraph.node("0", "Has feathers?") mygraph.node("1", "Can fly?") mygraph.node("2", "Has fins?") mygraph.node("3", "Hawk") mygraph.node("4", "Penguin") mygraph.node("5", "Dolphin") mygraph.node("6", "Bear") mygraph.edge("0", "1", label="True") mygraph.edge("0", "2", label="False") mygraph.edge("1", "3", label="True") mygraph.edge("1", "4", label="False") mygraph.edge("2", "5", label="True") mygraph.edge("2", "6", label="False") mygraph.render("tmp") ax.imshow(imread("tmp.png")) ax.set_axis_off()
31.785714
67
0.55618
from imageio import imread import matplotlib.pyplot as plt def plot_animal_tree(ax=None): import graphviz if ax is None: ax = plt.gca() mygraph = graphviz.Digraph(node_attr={'shape': 'box'}, edge_attr={'labeldistance': "10.5"}, format="png") mygraph.node("0", "Has feathers?") mygraph.node("1", "Can fly?") mygraph.node("2", "Has fins?") mygraph.node("3", "Hawk") mygraph.node("4", "Penguin") mygraph.node("5", "Dolphin") mygraph.node("6", "Bear") mygraph.edge("0", "1", label="True") mygraph.edge("0", "2", label="False") mygraph.edge("1", "3", label="True") mygraph.edge("1", "4", label="False") mygraph.edge("2", "5", label="True") mygraph.edge("2", "6", label="False") mygraph.render("tmp") ax.imshow(imread("tmp.png")) ax.set_axis_off()
true
true
f710fc68e45a37cce5c656828378d0930abb6dd0
688
py
Python
migrations/0002_auto_20161121_1848.py
WPRDC/property-api
980f541b07bef3c8842994cfb903b42cc2c25064
[ "MIT" ]
1
2021-10-01T18:35:46.000Z
2021-10-01T18:35:46.000Z
migrations/0002_auto_20161121_1848.py
WPRDC/property-api
980f541b07bef3c8842994cfb903b42cc2c25064
[ "MIT" ]
null
null
null
migrations/0002_auto_20161121_1848.py
WPRDC/property-api
980f541b07bef3c8842994cfb903b42cc2c25064
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-21 23:48 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('property_api', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='ckanresource', name='ckan_instance', ), migrations.AddField( model_name='ckanresource', name='slug', field=models.CharField(default='', max_length=200), preserve_default=False, ), migrations.DeleteModel( name='CKANInstance', ), ]
23.724138
63
0.581395
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('property_api', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='ckanresource', name='ckan_instance', ), migrations.AddField( model_name='ckanresource', name='slug', field=models.CharField(default='', max_length=200), preserve_default=False, ), migrations.DeleteModel( name='CKANInstance', ), ]
true
true
f710fc9750183ff8de75d9d019041bf7217e7cc6
494
py
Python
packages/python/plotly/plotly/validators/scattercarpet/marker/_sizemode.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/validators/scattercarpet/marker/_sizemode.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/validators/scattercarpet/marker/_sizemode.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
import _plotly_utils.basevalidators class SizemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="sizemode", parent_name="scattercarpet.marker", **kwargs ): super(SizemodeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), values=kwargs.pop("values", ["diameter", "area"]), **kwargs, )
32.933333
82
0.645749
import _plotly_utils.basevalidators class SizemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="sizemode", parent_name="scattercarpet.marker", **kwargs ): super(SizemodeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), values=kwargs.pop("values", ["diameter", "area"]), **kwargs, )
true
true
f710fcfe271b86745020637094a542da9581bfff
3,083
py
Python
src/dispatch/team/views.py
contractshark/dispatch
32226d89b306ac2979d916c87eeba567efaac4d3
[ "Apache-2.0" ]
1
2022-02-23T02:42:10.000Z
2022-02-23T02:42:10.000Z
src/dispatch/team/views.py
contractshark/dispatch
32226d89b306ac2979d916c87eeba567efaac4d3
[ "Apache-2.0" ]
1
2021-04-08T10:03:36.000Z
2021-04-08T10:03:36.000Z
src/dispatch/team/views.py
AlexaKelley/dispatch
b46d8416a0e4ec9badb76f6f3d1765c6093203f8
[ "Apache-2.0" ]
1
2021-04-08T10:02:57.000Z
2021-04-08T10:02:57.000Z
from typing import List from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.orm import Session from dispatch.database import get_db, search_filter_sort_paginate from .models import ( TeamContactCreate, TeamContactRead, TeamContactUpdate, TeamPagination, ) from .service import create, delete, get, get_by_email, update router = APIRouter() @router.get("/", response_model=TeamPagination) def get_teams( db_session: Session = Depends(get_db), page: int = 1, items_per_page: int = Query(5, alias="itemsPerPage"), query_str: str = Query(None, alias="q"), sort_by: List[str] = Query([], alias="sortBy[]"), descending: List[bool] = Query([], alias="descending[]"), fields: List[str] = Query([], alias="fields[]"), ops: List[str] = Query([], alias="ops[]"), values: List[str] = Query([], alias="values[]"), ): """ Get all team contacts. """ return search_filter_sort_paginate( db_session=db_session, model="TeamContact", query_str=query_str, page=page, items_per_page=items_per_page, sort_by=sort_by, descending=descending, fields=fields, values=values, ops=ops, ) @router.post("/", response_model=TeamContactRead) def create_team(*, db_session: Session = Depends(get_db), team_contact_in: TeamContactCreate): """ Create a new team contact. """ team = get_by_email(db_session=db_session, email=team_contact_in.email) if team: raise HTTPException(status_code=400, detail="The team with this email already exists.") team = create(db_session=db_session, team_contact_in=team_contact_in) return team @router.get("/{team_id}", response_model=TeamContactRead) def get_team(*, db_session: Session = Depends(get_db), team_contact_id: int): """ Get a team contact. """ team = get(db_session=db_session, team_contact_id=team_contact_id) if not team: raise HTTPException(status_code=404, detail="The team with this id does not exist.") return team @router.put("/{team_contact_id}", response_model=TeamContactRead) def update_team( *, db_session: Session = Depends(get_db), team_contact_id: int, team_contact_in: TeamContactUpdate, ): """ Update a team contact. """ team = get(db_session=db_session, team_contact_id=team_contact_id) if not team: raise HTTPException(status_code=404, detail="The team with this id does not exist.") team = update(db_session=db_session, team_contact=team, team_contact_in=team_contact_in) return team @router.delete("/{team_contact_id}", response_model=TeamContactRead) def delete_team(*, db_session: Session = Depends(get_db), team_contact_id: int): """ Delete a team contact. """ team = get(db_session=db_session, team_contact_id=team_contact_id) if not team: raise HTTPException(status_code=404, detail="The team with this id does not exist.") delete(db_session=db_session, team_contact_id=team_contact_id) return team
31.141414
95
0.693156
from typing import List from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.orm import Session from dispatch.database import get_db, search_filter_sort_paginate from .models import ( TeamContactCreate, TeamContactRead, TeamContactUpdate, TeamPagination, ) from .service import create, delete, get, get_by_email, update router = APIRouter() @router.get("/", response_model=TeamPagination) def get_teams( db_session: Session = Depends(get_db), page: int = 1, items_per_page: int = Query(5, alias="itemsPerPage"), query_str: str = Query(None, alias="q"), sort_by: List[str] = Query([], alias="sortBy[]"), descending: List[bool] = Query([], alias="descending[]"), fields: List[str] = Query([], alias="fields[]"), ops: List[str] = Query([], alias="ops[]"), values: List[str] = Query([], alias="values[]"), ): return search_filter_sort_paginate( db_session=db_session, model="TeamContact", query_str=query_str, page=page, items_per_page=items_per_page, sort_by=sort_by, descending=descending, fields=fields, values=values, ops=ops, ) @router.post("/", response_model=TeamContactRead) def create_team(*, db_session: Session = Depends(get_db), team_contact_in: TeamContactCreate): team = get_by_email(db_session=db_session, email=team_contact_in.email) if team: raise HTTPException(status_code=400, detail="The team with this email already exists.") team = create(db_session=db_session, team_contact_in=team_contact_in) return team @router.get("/{team_id}", response_model=TeamContactRead) def get_team(*, db_session: Session = Depends(get_db), team_contact_id: int): team = get(db_session=db_session, team_contact_id=team_contact_id) if not team: raise HTTPException(status_code=404, detail="The team with this id does not exist.") return team @router.put("/{team_contact_id}", response_model=TeamContactRead) def update_team( *, db_session: Session = Depends(get_db), team_contact_id: int, team_contact_in: TeamContactUpdate, ): team = get(db_session=db_session, team_contact_id=team_contact_id) if not team: raise HTTPException(status_code=404, detail="The team with this id does not exist.") team = update(db_session=db_session, team_contact=team, team_contact_in=team_contact_in) return team @router.delete("/{team_contact_id}", response_model=TeamContactRead) def delete_team(*, db_session: Session = Depends(get_db), team_contact_id: int): team = get(db_session=db_session, team_contact_id=team_contact_id) if not team: raise HTTPException(status_code=404, detail="The team with this id does not exist.") delete(db_session=db_session, team_contact_id=team_contact_id) return team
true
true
f710fd96673d5984891916ed0869543983fb7de1
3,520
py
Python
controller.py
Shihao-Feng-98/RRP_Hopper_simulation
444dbcce90d5ffb6bf577ed03adc9717183e21ae
[ "MIT" ]
4
2021-11-12T06:11:13.000Z
2022-03-30T12:10:47.000Z
controller.py
Shihao-Feng-98/RRP_Hopper_simulation
444dbcce90d5ffb6bf577ed03adc9717183e21ae
[ "MIT" ]
null
null
null
controller.py
Shihao-Feng-98/RRP_Hopper_simulation
444dbcce90d5ffb6bf577ed03adc9717183e21ae
[ "MIT" ]
3
2021-12-09T02:27:38.000Z
2022-03-29T06:48:08.000Z
''' only for RRP Hopper Shihao Feng 2021.10.28 ''' import numpy as np import pybullet as p from leg_kinematics import LegKinematicsRRP import pinocchio as pin class JointPDController(object): def __init__ (self): self.kp = np.array([70, 70, 1500]) self.kd = np.array([2, 2, 10]) def solve(self, q_d, dq_d, q_state, dq_state): q = q_state[7:10] dq = dq_state[6:9] ddq_d = np.zeros(3) # 期望加速度计算量大,简单地设为0 tau_d = ddq_d + self.kd*(dq_d - dq) + self.kp*(q_d - q) # (3,) return tau_d class SLIPController(object): def __init__(self): self.q_d = np.array([0., 0., 0.]) # q_d[2] always 0 self.dq_d = np.array([0., 0., 0.]) # always 0 # 关节增益 self.kp = np.array([70., 70., 3000.]) self.kd = np.array([2., 2., 10.]) # 阻尼模拟能量损失, 同时防止腿抖动 # 身体姿态增益 self.kp_pose = 5. * np.ones(2) self.kd_pose = 1. * np.ones(2) # 水平速度增益 self.kp_vel = 0.1 * np.ones(2) self.leg_length_normal = 0.55 self.RRP = LegKinematicsRRP(L=self.leg_length_normal) # private methods def __w_to_drpy(self, rpy, w): ''' rpy -> (3,), w -> (3,),drpy -> (3,) ''' H = np.array([[np.cos(rpy[2])/np.cos(rpy[1]), np.sin(rpy[2])/np.cos(rpy[1]), 0.], [-np.sin(rpy[2]), np.cos(rpy[2]), 0.], [np.cos(rpy[2])*np.tan(rpy[1]), np.sin(rpy[2])*np.tan(rpy[1]), 0.]]) drpy = (H @ w.reshape(-1,1)).ravel() return drpy def solve(self, q_state, dq_state, robot_state_machine, T_s, vel, dir, F_thrust): tau_d = np.zeros(3) # 初始化 orn_body = q_state[3:7] # 身体姿态 四元数 rpy = np.array(p.getEulerFromQuaternion(orn_body)) w_body = dq_state[3:6] # 身体角速度 w drpy = self.__w_to_drpy(rpy, w_body) q = q_state[7:10] # 关节位置 dq = dq_state[6:9] # 关节速度 # 控制虚拟弹簧力 tau_d[2] = self.kd[2]*(self.dq_d[2] - dq[2]) \ + self.kp[2]*(self.q_d[2] - q[2]) # 弹簧伸长时,施加推力抵消能量损耗 if robot_state_machine == 'THRUST': tau_d[2] += F_thrust # 触地或者离地时,关节扭矩为0 if (robot_state_machine == 'LOADING' or robot_state_machine == 'UNLOADING'): tau_d[0:2] = np.zeros(2) # 弹簧压缩或者伸长时,施加关节扭矩控制身体姿态 if (robot_state_machine == 'COMPRESSION' or robot_state_machine == 'THRUST'): # 姿态线性伺服控制 tau_d[0:2] = - (self.kd_pose*(np.zeros(2) - drpy[0:2]) \ + self.kp_pose*(np.zeros(2) - rpy[0:2])) # (2,) # 飞行时,控制足端移动到落地点 if robot_state_machine == 'FLIGHT': vel_xy_d = np.array([vel*np.cos(dir), vel*np.sin(dir)]) v_body = dq_state[0:2] # 当前水平速度 # 相对于H系:坐标系原点与身体坐标系重合,方向与世界坐标系平行 xy_d = v_body*T_s/2 - self.kp_vel*(vel_xy_d - v_body) # 计算落脚点 r = q[2] + self.leg_length_normal z_d = - (r**2 - xy_d[0]**2 - xy_d[1]**2)**0.5 # 转换到B系:身体坐标系 R_HB = pin.rpy.rpyToMatrix(rpy) R_BH = R_HB.T p_H = np.array([xy_d[0], xy_d[1], z_d]) p_B = (R_BH @ p_H.reshape(-1,1)).ravel() # (3,) q_d = self.RRP.IK(p_B) self.q_d[0:2] = q_d[0:2] # 关节PD控制 tau_d[0:2] = self.kd[0:2]*(self.dq_d[0:2] - dq[0:2]) \ + self.kp[0:2]*(self.q_d[0:2] - q[0:2]) # (2,) print('tau_d: ', tau_d) return tau_d
35.2
92
0.505114
import numpy as np import pybullet as p from leg_kinematics import LegKinematicsRRP import pinocchio as pin class JointPDController(object): def __init__ (self): self.kp = np.array([70, 70, 1500]) self.kd = np.array([2, 2, 10]) def solve(self, q_d, dq_d, q_state, dq_state): q = q_state[7:10] dq = dq_state[6:9] ddq_d = np.zeros(3) tau_d = ddq_d + self.kd*(dq_d - dq) + self.kp*(q_d - q) return tau_d class SLIPController(object): def __init__(self): self.q_d = np.array([0., 0., 0.]) self.dq_d = np.array([0., 0., 0.]) self.kp = np.array([70., 70., 3000.]) self.kd = np.array([2., 2., 10.]) self.kp_pose = 5. * np.ones(2) self.kd_pose = 1. * np.ones(2) self.kp_vel = 0.1 * np.ones(2) self.leg_length_normal = 0.55 self.RRP = LegKinematicsRRP(L=self.leg_length_normal) def __w_to_drpy(self, rpy, w): H = np.array([[np.cos(rpy[2])/np.cos(rpy[1]), np.sin(rpy[2])/np.cos(rpy[1]), 0.], [-np.sin(rpy[2]), np.cos(rpy[2]), 0.], [np.cos(rpy[2])*np.tan(rpy[1]), np.sin(rpy[2])*np.tan(rpy[1]), 0.]]) drpy = (H @ w.reshape(-1,1)).ravel() return drpy def solve(self, q_state, dq_state, robot_state_machine, T_s, vel, dir, F_thrust): tau_d = np.zeros(3) orn_body = q_state[3:7] rpy = np.array(p.getEulerFromQuaternion(orn_body)) w_body = dq_state[3:6] drpy = self.__w_to_drpy(rpy, w_body) q = q_state[7:10] dq = dq_state[6:9] tau_d[2] = self.kd[2]*(self.dq_d[2] - dq[2]) \ + self.kp[2]*(self.q_d[2] - q[2]) if robot_state_machine == 'THRUST': tau_d[2] += F_thrust if (robot_state_machine == 'LOADING' or robot_state_machine == 'UNLOADING'): tau_d[0:2] = np.zeros(2) if (robot_state_machine == 'COMPRESSION' or robot_state_machine == 'THRUST'): tau_d[0:2] = - (self.kd_pose*(np.zeros(2) - drpy[0:2]) \ + self.kp_pose*(np.zeros(2) - rpy[0:2])) if robot_state_machine == 'FLIGHT': vel_xy_d = np.array([vel*np.cos(dir), vel*np.sin(dir)]) v_body = dq_state[0:2] xy_d = v_body*T_s/2 - self.kp_vel*(vel_xy_d - v_body) r = q[2] + self.leg_length_normal z_d = - (r**2 - xy_d[0]**2 - xy_d[1]**2)**0.5 R_HB = pin.rpy.rpyToMatrix(rpy) R_BH = R_HB.T p_H = np.array([xy_d[0], xy_d[1], z_d]) p_B = (R_BH @ p_H.reshape(-1,1)).ravel() q_d = self.RRP.IK(p_B) self.q_d[0:2] = q_d[0:2] tau_d[0:2] = self.kd[0:2]*(self.dq_d[0:2] - dq[0:2]) \ + self.kp[0:2]*(self.q_d[0:2] - q[0:2]) print('tau_d: ', tau_d) return tau_d
true
true
f710fdc0e254ef0ce35311f43c26d937585b5b27
13,741
py
Python
pynucastro/networks/rate_collection.py
XinlongSBU/pynucastro
4f1547e99208ad03d8f79d748601219591a157b5
[ "BSD-3-Clause" ]
null
null
null
pynucastro/networks/rate_collection.py
XinlongSBU/pynucastro
4f1547e99208ad03d8f79d748601219591a157b5
[ "BSD-3-Clause" ]
null
null
null
pynucastro/networks/rate_collection.py
XinlongSBU/pynucastro
4f1547e99208ad03d8f79d748601219591a157b5
[ "BSD-3-Clause" ]
null
null
null
"""A collection of classes and methods to deal with collections of rates that together make up a network.""" # Common Imports from __future__ import print_function import functools import math from operator import mul import os from collections import OrderedDict from ipywidgets import interact import matplotlib as mpl import matplotlib.pyplot as plt #from mpl_toolkits.axes_grid1 import make_axes_locatable import networkx as nx # Import Rate from pynucastro.rates import Rate, Nucleus, Library mpl.rcParams['figure.dpi'] = 100 class Composition(object): """a composition holds the mass fractions of the nuclei in a network -- useful for evaluating the rates """ def __init__(self, nuclei, small=1.e-16): """nuclei is an iterable of the nuclei (Nucleus objects) in the network""" if not isinstance(nuclei[0], Nucleus): raise ValueError("must supply an iterable of Nucleus objects") else: self.X = {k: small for k in nuclei} def set_solar_like(self, Z=0.02): """ approximate a solar abundance, setting p to 0.7, He4 to 0.3 - Z and the remainder evenly distributed with Z """ num = len(self.X) rem = Z/(num-2) for k in self.X: if k == Nucleus("p"): self.X[k] = 0.7 elif k.raw == "he4": self.X[k] = 0.3 - Z else: self.X[k] = rem self.normalize() def set_all(self, xval): """ set all species to a particular value """ for k in self.X: self.X[k] = xval def set_nuc(self, name, xval): """ set nuclei name to the mass fraction xval """ for k in self.X: if k.raw == name: self.X[k] = xval break def normalize(self): """ normalize the mass fractions to sum to 1 """ X_sum = sum([self.X[k] for k in self.X]) for k in self.X: self.X[k] /= X_sum def get_molar(self): """ return a dictionary of molar fractions""" molar_frac = {k: v/k.A for k, v in self.X.items()} return molar_frac def __str__(self): ostr = "" for k in self.X: ostr += " X({}) : {}\n".format(k, self.X[k]) return ostr class RateCollection(object): """ a collection of rates that together define a network """ pynucastro_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) def __init__(self, rate_files=None, libraries=None, rates=None): """ rate_files are the files that together define the network. This can be any iterable or single string. This can include Reaclib library files storing multiple rates. If libraries is supplied, initialize a RateCollection using the rates in the Library object(s) in list 'libraries'. If rates is supplied, initialize a RateCollection using the Rate objects in the list 'rates'. Any combination of these options may be combined. """ self.files = [] self.rates = [] self.library = None if rate_files: if isinstance(rate_files, str): rate_files = [rate_files] self._read_rate_files(rate_files) if rates: if isinstance(rates, Rate): rates = [rates] try: for r in rates: assert(isinstance(r, Rate)) except: print('Expected Rate object or list of Rate objects passed as the rates argument.') raise else: rlib = Library(rates=rates) if not self.library: self.library = rlib else: self.library = self.library + rlib if libraries: if isinstance(libraries, Library): libraries = [libraries] try: for lib in libraries: assert(isinstance(lib, Library)) except: print('Expected Library object or list of Library objects passed as the libraries argument.') raise else: if not self.library: self.library = libraries.pop(0) for lib in libraries: self.library = self.library + lib if self.library: self.rates = self.rates + self.library.get_rates() # get the unique nuclei u = [] for r in self.rates: t = set(r.reactants + r.products) u = set(list(u) + list(t)) self.unique_nuclei = sorted(u) # now make a list of each rate that touches each nucleus # we'll store this in a dictionary keyed on the nucleus self.nuclei_consumed = OrderedDict() self.nuclei_produced = OrderedDict() for n in self.unique_nuclei: self.nuclei_consumed[n] = [r for r in self.rates if n in r.reactants] self.nuclei_produced[n] = [r for r in self.rates if n in r.products] # Re-order self.rates so Reaclib rates come first, # followed by Tabular rates. This is needed if # reaclib coefficients are targets of a pointer array # in the Fortran network. # It is desired to avoid wasting array size # storing meaningless Tabular coefficient pointers. self.rates = sorted(self.rates, key=lambda r: r.chapter == 't') self.tabular_rates = [] self.reaclib_rates = [] for n, r in enumerate(self.rates): if r.chapter == 't': self.tabular_rates.append(n) elif isinstance(r.chapter, int): self.reaclib_rates.append(n) else: print('ERROR: Chapter type unknown for rate chapter {}'.format( str(r.chapter))) exit() def _read_rate_files(self, rate_files): # get the rates self.files = rate_files for rf in self.files: try: rflib = Library(rf) except: print("Error reading library from file: {}".format(rf)) raise else: if not self.library: self.library = rflib else: self.library = self.library + rflib def get_nuclei(self): """ get all the nuclei that are part of the network """ return self.unique_nuclei def evaluate_rates(self, rho, T, composition): """evaluate the rates for a specific density, temperature, and composition""" rvals = OrderedDict() ys = composition.get_molar() for r in self.rates: val = r.prefactor * rho**r.dens_exp * r.eval(T) yfac = functools.reduce(mul, [ys[q] for q in r.reactants]) rvals[r] = yfac * val return rvals def network_overview(self): """ return a verbose network overview """ ostr = "" for n in self.unique_nuclei: ostr += "{}\n".format(n) ostr += " consumed by:\n" for r in self.nuclei_consumed[n]: ostr += " {}\n".format(r.string) ostr += " produced by:\n" for r in self.nuclei_produced[n]: ostr += " {}\n".format(r.string) ostr += "\n" return ostr def write_network(self, *args, **kwargs): """Before writing the network, check to make sure the rates are distinguishable by name.""" assert self._distinguishable_rates(), "ERROR: Rates not uniquely identified by Rate.fname" self._write_network(*args, **kwargs) def _distinguishable_rates(self): """Every Rate in this RateCollection should have a unique Rate.fname, as the network writers distinguish the rates on this basis.""" names = [r.fname for r in self.rates] return len(set(names)) == len(self.rates) def _write_network(self, *args, **kwargs): """A stub for function to output the network -- this is implementation dependent.""" print('To create network integration source code, use a class that implements a specific network type.') return def plot(self, outfile=None, rho=None, T=None, comp=None, size=(800, 600), dpi=100): """Make a plot of the network structure showing the links between nuclei""" G = nx.MultiDiGraph() G.position = {} G.labels = {} fig, ax = plt.subplots() #divider = make_axes_locatable(ax) #cax = divider.append_axes('right', size='15%', pad=0.05) ax.plot([0, 0], [8, 8], 'b-') # nodes -- the node nuclei will be all of the heavies, but not # p, n, alpha, unless we have p + p, 3-a, etc. node_nuclei = [] for n in self.unique_nuclei: if n.raw not in ["p", "n", "he4"]: node_nuclei.append(n) else: for r in self.rates: if r.reactants.count(n) > 1: node_nuclei.append(n) break for n in node_nuclei: G.add_node(n) G.position[n] = (n.N, n.Z) G.labels[n] = r"${}$".format(n.pretty) if rho is not None and T is not None and comp is not None: ydots = self.evaluate_rates(rho, T, comp) else: ydots = None #for rr in ydots: # print("{}: {}".format(rr, ydots[rr])) # edges for n in node_nuclei: for r in self.nuclei_consumed[n]: for p in r.products: if p in node_nuclei: # networkx doesn't seem to keep the edges in # any particular order, so we associate data # to the edges here directly, in this case, # the reaction rate, which will be used to # color it if ydots is None: G.add_edges_from([(n, p)], weight=0.5) else: try: rate_weight = math.log10(ydots[r]) except ValueError: # if ydots[r] is zero, then set the weight # to roughly the minimum exponent possible # for python floats rate_weight = -308 except: raise G.add_edges_from([(n, p)], weight=rate_weight) nx.draw_networkx_nodes(G, G.position, node_color="#A0CBE2", alpha=1.0, node_shape="o", node_size=1000, linewidth=2.0, zorder=10, ax=ax) nx.draw_networkx_labels(G, G.position, G.labels, font_size=13, font_color="w", zorder=100, ax=ax) # get the edges and weights coupled in the same order edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items()) edges_lc = nx.draw_networkx_edges(G, G.position, width=3, edgelist=edges, edge_color=weights, node_size=1000, edge_cmap=plt.cm.viridis, zorder=1, ax=ax) # for networkx <= 2.0 draw_networkx_edges returns a # LineCollection matplotlib type which we can use for the # colorbar directly. For networkx >= 2.1, it is a collection # of FancyArrowPatch-s, which we need to run through a # PatchCollection. See: # https://stackoverflow.com/questions/18658047/adding-a-matplotlib-colorbar-from-a-patchcollection if ydots is not None: pc = mpl.collections.PatchCollection(edges_lc, cmap=plt.cm.viridis) pc.set_array(weights) plt.colorbar(pc, label="log10(rate)") Ns = [n.N for n in node_nuclei] Zs = [n.Z for n in node_nuclei] plt.xlim(min(Ns)-1, max(Ns)+1) #plt.ylim(min(Zs)-1, max(Zs)+1) plt.xlabel(r"$N$", fontsize="large") plt.ylabel(r"$Z$", fontsize="large") ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_aspect("equal", "datalim") fig.set_size_inches(size[0]/dpi, size[1]/dpi) if outfile is None: plt.show() else: plt.tight_layout() plt.savefig(outfile, dpi=dpi) def __repr__(self): string = "" for r in self.rates: string += "{}\n".format(r.string) return string class Explorer(object): """ interactively explore a rate collection """ def __init__(self, rc, comp, size=(800, 600)): """ take a RateCollection and a composition """ self.rc = rc self.comp = comp self.size = size def _make_plot(self, logrho, logT): self.rc.plot(rho=10.0**logrho, T=10.0**logT, comp=self.comp, size=self.size) def explore(self, logrho=(2, 6, 0.1), logT=(7, 9, 0.1)): """Perform interactive exploration of the network structure.""" interact(self._make_plot, logrho=logrho, logT=logT)
35.50646
112
0.543774
from __future__ import print_function import functools import math from operator import mul import os from collections import OrderedDict from ipywidgets import interact import matplotlib as mpl import matplotlib.pyplot as plt import networkx as nx from pynucastro.rates import Rate, Nucleus, Library mpl.rcParams['figure.dpi'] = 100 class Composition(object): def __init__(self, nuclei, small=1.e-16): if not isinstance(nuclei[0], Nucleus): raise ValueError("must supply an iterable of Nucleus objects") else: self.X = {k: small for k in nuclei} def set_solar_like(self, Z=0.02): num = len(self.X) rem = Z/(num-2) for k in self.X: if k == Nucleus("p"): self.X[k] = 0.7 elif k.raw == "he4": self.X[k] = 0.3 - Z else: self.X[k] = rem self.normalize() def set_all(self, xval): for k in self.X: self.X[k] = xval def set_nuc(self, name, xval): for k in self.X: if k.raw == name: self.X[k] = xval break def normalize(self): X_sum = sum([self.X[k] for k in self.X]) for k in self.X: self.X[k] /= X_sum def get_molar(self): molar_frac = {k: v/k.A for k, v in self.X.items()} return molar_frac def __str__(self): ostr = "" for k in self.X: ostr += " X({}) : {}\n".format(k, self.X[k]) return ostr class RateCollection(object): pynucastro_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) def __init__(self, rate_files=None, libraries=None, rates=None): self.files = [] self.rates = [] self.library = None if rate_files: if isinstance(rate_files, str): rate_files = [rate_files] self._read_rate_files(rate_files) if rates: if isinstance(rates, Rate): rates = [rates] try: for r in rates: assert(isinstance(r, Rate)) except: print('Expected Rate object or list of Rate objects passed as the rates argument.') raise else: rlib = Library(rates=rates) if not self.library: self.library = rlib else: self.library = self.library + rlib if libraries: if isinstance(libraries, Library): libraries = [libraries] try: for lib in libraries: assert(isinstance(lib, Library)) except: print('Expected Library object or list of Library objects passed as the libraries argument.') raise else: if not self.library: self.library = libraries.pop(0) for lib in libraries: self.library = self.library + lib if self.library: self.rates = self.rates + self.library.get_rates() u = [] for r in self.rates: t = set(r.reactants + r.products) u = set(list(u) + list(t)) self.unique_nuclei = sorted(u) self.nuclei_consumed = OrderedDict() self.nuclei_produced = OrderedDict() for n in self.unique_nuclei: self.nuclei_consumed[n] = [r for r in self.rates if n in r.reactants] self.nuclei_produced[n] = [r for r in self.rates if n in r.products] # Re-order self.rates so Reaclib rates come first, # followed by Tabular rates. This is needed if # reaclib coefficients are targets of a pointer array # in the Fortran network. # It is desired to avoid wasting array size # storing meaningless Tabular coefficient pointers. self.rates = sorted(self.rates, key=lambda r: r.chapter == 't') self.tabular_rates = [] self.reaclib_rates = [] for n, r in enumerate(self.rates): if r.chapter == 't': self.tabular_rates.append(n) elif isinstance(r.chapter, int): self.reaclib_rates.append(n) else: print('ERROR: Chapter type unknown for rate chapter {}'.format( str(r.chapter))) exit() def _read_rate_files(self, rate_files): # get the rates self.files = rate_files for rf in self.files: try: rflib = Library(rf) except: print("Error reading library from file: {}".format(rf)) raise else: if not self.library: self.library = rflib else: self.library = self.library + rflib def get_nuclei(self): return self.unique_nuclei def evaluate_rates(self, rho, T, composition): rvals = OrderedDict() ys = composition.get_molar() for r in self.rates: val = r.prefactor * rho**r.dens_exp * r.eval(T) yfac = functools.reduce(mul, [ys[q] for q in r.reactants]) rvals[r] = yfac * val return rvals def network_overview(self): ostr = "" for n in self.unique_nuclei: ostr += "{}\n".format(n) ostr += " consumed by:\n" for r in self.nuclei_consumed[n]: ostr += " {}\n".format(r.string) ostr += " produced by:\n" for r in self.nuclei_produced[n]: ostr += " {}\n".format(r.string) ostr += "\n" return ostr def write_network(self, *args, **kwargs): assert self._distinguishable_rates(), "ERROR: Rates not uniquely identified by Rate.fname" self._write_network(*args, **kwargs) def _distinguishable_rates(self): names = [r.fname for r in self.rates] return len(set(names)) == len(self.rates) def _write_network(self, *args, **kwargs): print('To create network integration source code, use a class that implements a specific network type.') return def plot(self, outfile=None, rho=None, T=None, comp=None, size=(800, 600), dpi=100): G = nx.MultiDiGraph() G.position = {} G.labels = {} fig, ax = plt.subplots() #divider = make_axes_locatable(ax) #cax = divider.append_axes('right', size='15%', pad=0.05) ax.plot([0, 0], [8, 8], 'b-') # nodes -- the node nuclei will be all of the heavies, but not # p, n, alpha, unless we have p + p, 3-a, etc. node_nuclei = [] for n in self.unique_nuclei: if n.raw not in ["p", "n", "he4"]: node_nuclei.append(n) else: for r in self.rates: if r.reactants.count(n) > 1: node_nuclei.append(n) break for n in node_nuclei: G.add_node(n) G.position[n] = (n.N, n.Z) G.labels[n] = r"${}$".format(n.pretty) if rho is not None and T is not None and comp is not None: ydots = self.evaluate_rates(rho, T, comp) else: ydots = None #for rr in ydots: # print("{}: {}".format(rr, ydots[rr])) # edges for n in node_nuclei: for r in self.nuclei_consumed[n]: for p in r.products: if p in node_nuclei: # networkx doesn't seem to keep the edges in if ydots is None: G.add_edges_from([(n, p)], weight=0.5) else: try: rate_weight = math.log10(ydots[r]) except ValueError: rate_weight = -308 except: raise G.add_edges_from([(n, p)], weight=rate_weight) nx.draw_networkx_nodes(G, G.position, node_color="#A0CBE2", alpha=1.0, node_shape="o", node_size=1000, linewidth=2.0, zorder=10, ax=ax) nx.draw_networkx_labels(G, G.position, G.labels, font_size=13, font_color="w", zorder=100, ax=ax) edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items()) edges_lc = nx.draw_networkx_edges(G, G.position, width=3, edgelist=edges, edge_color=weights, node_size=1000, edge_cmap=plt.cm.viridis, zorder=1, ax=ax) if ydots is not None: pc = mpl.collections.PatchCollection(edges_lc, cmap=plt.cm.viridis) pc.set_array(weights) plt.colorbar(pc, label="log10(rate)") Ns = [n.N for n in node_nuclei] Zs = [n.Z for n in node_nuclei] plt.xlim(min(Ns)-1, max(Ns)+1) plt.xlabel(r"$N$", fontsize="large") plt.ylabel(r"$Z$", fontsize="large") ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_aspect("equal", "datalim") fig.set_size_inches(size[0]/dpi, size[1]/dpi) if outfile is None: plt.show() else: plt.tight_layout() plt.savefig(outfile, dpi=dpi) def __repr__(self): string = "" for r in self.rates: string += "{}\n".format(r.string) return string class Explorer(object): def __init__(self, rc, comp, size=(800, 600)): self.rc = rc self.comp = comp self.size = size def _make_plot(self, logrho, logT): self.rc.plot(rho=10.0**logrho, T=10.0**logT, comp=self.comp, size=self.size) def explore(self, logrho=(2, 6, 0.1), logT=(7, 9, 0.1)): interact(self._make_plot, logrho=logrho, logT=logT)
true
true
f710fdd4366bd507e11c7c6ac41919ea1576386b
10,667
py
Python
notebooks/static_simulation.py
MGIMM/dynamic_balancing
74482a970996ec75f5fb3f433b8285420787ccd7
[ "MIT" ]
null
null
null
notebooks/static_simulation.py
MGIMM/dynamic_balancing
74482a970996ec75f5fb3f433b8285420787ccd7
[ "MIT" ]
null
null
null
notebooks/static_simulation.py
MGIMM/dynamic_balancing
74482a970996ec75f5fb3f433b8285420787ccd7
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # In[1]: import torch import numpy as np import matplotlib.pyplot as plt # from MMDBalancing import MMDBalancing as MMDB # from OptimalTransportBalancing import OptimalTransportBalancing as OTB # from NeuralAdversarialBalancing import NeuralAdversarialBalancing as NAB #get_ipython().run_line_magic('matplotlib', 'inline') import pandas as pd # utils from utils_balancing import * # In[2]: def static_simulation(): n = 5000 m = 5000 d = 1 r = lambda x:(x-3).square() + (x>-2)*(x+3).square() +x.abs() #r = lambda x:x.square() def get_data(n = 500,m = 500, r = r, d = d): def pi(x): return torch.sin(x)+ 2*torch.rand(x.shape)-1 def pi_ring(x): return torch.sin(x)+ 1*torch.rand(x.shape)-0.5 xi = torch.normal(mean = -1, std = 2, size = (n,d)) xi_ring = torch.zeros(size = (m,d)) for i in range(m): if torch.rand(1).item()>0.3: xi_ring[i,0] = torch.normal(mean = -4, std = 2, size = (1,)).item() else: xi_ring[i,0] = torch.normal(mean = 3, std = 0.2, size = (1,)).item() w = torch.ones(n) w_ring = torch.ones(m) xi_natural = torch.cat((xi, pi(xi)),axis = 1) xi_ring_natural = torch.cat((xi_ring, pi_ring(xi_ring)), axis = 1) Z =xi_natural[:,0]+xi_natural[:,1] + torch.rand((n,)) Z_ring =xi_ring_natural[:,0]+xi_ring_natural[:,1]+torch.rand((m,)) R = r(Z) return xi_natural,xi_ring_natural,R,Z,Z_ring # ## Reference value # In[7]: xi_natural, xi_ring_natural,R,Z,Z_ring = get_data(n = 50000, m = 50000) ref = r(Z_ring).mean() # ### Re-generate data set with $n=m=500$. # In[8]: n = 500 m = 500 xi_natural, xi_ring_natural,R,Z,Z_ring = get_data(n = n, m = m, r = r) # # GIPWE: DE and DRE # # 1. Data splitting (K-folds with K = 3) # In[9]: def get_split_ind(n,K = 3): I_n = torch.arange(n, dtype = float) rand_ind_n = torch.multinomial(I_n,len(I_n),replacement = False) num_folds_n = int(n/K) Ind = [] for i in range(K): if (i+1)*num_folds_n <= n: Ind.append(list(rand_ind_n[i*num_folds_n:(i+1)*num_folds_n].detach().numpy())) else: Ind.append(list(rand_ind_n[i*num_folds_n:].detach().numpy())) Ind_split = [] for i in range(K): list_n = [] for j in range(n): if j >= i*num_folds_n and j < (i+1)*num_folds_n: pass else: list_n.append(rand_ind_n[j].item()) Ind_split.append(list_n) return Ind_split,Ind # In[10]: K = 3 Ind_out, Ind_in = get_split_ind(n,K) # 2. Get GIPW weights # In[11]: from sklearn.ensemble import RandomForestRegressor import xgboost as xgb from sklearn.linear_model import LogisticRegression # In[12]: XGB = xgb.XGBRegressor(gamma = 5e0) RF = RandomForestRegressor(n_estimators = 20, min_samples_split = 20) LR = LogisticRegression() def get_GIPW_weights(model): eta = np.zeros(n) for k in range(K): SGIPW = Shallow_GIPW(xi_natural[Ind_out[k],:], xi_ring_natural) SGIPW.train(model,xi = np.array(xi_natural[Ind_in[k],:]),log=False) eta[Ind_in[k]] = SGIPW.weights*(SGIPW.weights>0) return eta eta_XGB = get_GIPW_weights(XGB) eta_RF = get_GIPW_weights(RF) eta_LR = get_GIPW_weights(LR) # In[13]: # OT OTB = OptimalTransportBalancing() eta_OT = OTB.get_weights(xi_natural,xi_ring_natural) eta_OT = eta_OT.detach().numpy() # In[17]: # MMD weights lambda_RKHS = 1e2 lambda_l2 = 1e-3 MMDB = MMDBalancing(xi_natural,xi_ring_natural,sigma = 5e-1,D = 2000) eta_MMD = MMDB.get_weights(lambda_RKHS = lambda_RKHS, lambda_l2 = lambda_l2) eta_MMD = eta_MMD.to("cpu").detach().numpy() # In[18]: # In[20]: # Neural Adversarial Balancing class NeuralNetwork(nn.Module): def __init__(self,input_dim = 1, num_nodes = 32): super(NeuralNetwork, self).__init__() self.flatten = nn.Flatten() self.linear_relu_stack = nn.Sequential( nn.Linear(input_dim, num_nodes), nn.ReLU(), #nn.Dropout(0.3), #nn.BatchNorm1d(num_nodes), nn.Linear(num_nodes, num_nodes), nn.ReLU(), nn.Linear(num_nodes, num_nodes), nn.ReLU(), #nn.Dropout(0.3), #nn.BatchNorm1d(num_nodes), #nn.Linear(num_nodes, num_nodes), #nn.ReLU(), # # #nn.Dropout(0.3), # # nn.BatchNorm1d(num_nodes), nn.Linear(num_nodes, 1), ) def forward(self, x): x = self.flatten(x) target = self.linear_relu_stack(x) return target # In[21]: AB = Adversarial_Balancing(xi_natural,xi_ring_natural) num_nodes_IPM = 24 model_IPM = NeuralNetwork(input_dim = d*2,num_nodes = 2*num_nodes_IPM).to(AB.dev) model_reweighting = NeuralNetwork(input_dim = d*2, num_nodes = num_nodes_IPM).to(AB.dev) learning_rate = 1e-3 optimizer_IPM = torch.optim.Adam(model_IPM.parameters(), lr=learning_rate, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=True) optimizer_reweighting = torch.optim.Adam(model_reweighting.parameters(), lr=learning_rate, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=True) # In[22]: epochs = 50 loss_trace = [] for t in range(epochs): #print(f"Epoch {t+1}\n-------------------------------") current_test_loss = AB.train_loop(model_IPM = model_IPM, model_reweighting = model_reweighting, optimizer_IPM = optimizer_IPM, optimizer_reweighting = optimizer_reweighting, IPM_steps = 3, reweight_steps = 3, lambda_l2_weight = 5e-2, lambda_l2_IPM = 1e-2, lambda_l1_IPM = 1e-2, ) loss_trace.append(current_test_loss.to("cpu").detach().numpy()) weights = model_reweighting(xi_natural.to("cuda:0")) #weights /=weights.mean() eta_NAB = weights.to("cpu").detach().numpy() # 4. Get $r^{\natural}$ estimation with the same K-fold splitting # In[26]: from sklearn.linear_model import LinearRegression RF_R = RandomForestRegressor(n_estimators = 20, min_samples_split = 5) #model_r = RF_R model_r = LinearRegression() # In[27]: def get_r_estimation(model, K = 3): r_hat = np.zeros(n) r_hat_ring = np.zeros(m) for k in range(K): SGIPW = Shallow_GIPW(xi_natural[Ind_out[k],:], xi_ring_natural) model_k = model model_k.fit(xi_natural[Ind_out[k],:].detach().numpy(), R[Ind_out[k]].detach().numpy()) r_hat[Ind_in[k]] = model_k.predict(xi_natural[Ind_in[k]].detach().numpy()) r_hat_ring += model_k.predict(xi_ring_natural.detach().numpy()) r_hat_ring /= K return r_hat, r_hat_ring # In[28]: r_hat,r_hat_ring = get_r_estimation(model_r) # In[29]: # ## Estimators # In[30]: def get_DE(eta, R = R, ref= ref): try: eta = torch.from_numpy(eta) except: pass pred = (eta*R).mean().item() error = torch.abs(pred - ref).item() return pred, error def get_DRE(eta,r_hat, r_hat_ring, R = R, ref = ref): try: eta = torch.from_numpy(eta) r_hat = torch.from_numpy(r_hat) except: pass pred = (eta*(R -r_hat)).mean() + r_hat_ring.mean() error = torch.abs(pred - ref).item() return pred.item(), error # In[31]: #pd.set_option("display.precision", 2) #pd.set_option('display.float_format', lambda x: '%.2f' % x) table_bad_reg = pd.DataFrame([[get_DE(eta_OT)[1],get_DRE(eta_OT,r_hat,r_hat_ring)[1]],[get_DE(eta_MMD)[1],get_DRE(eta_MMD,r_hat,r_hat_ring)[1]], [get_DE(eta_NAB)[1],get_DRE(eta_NAB,r_hat,r_hat_ring)[1]], [get_DE(eta_RF)[1],get_DRE(eta_RF,r_hat,r_hat_ring)[1]],[get_DE(eta_XGB)[1],get_DRE(eta_XGB,r_hat,r_hat_ring)[1]], [get_DE(eta_LR)[1],get_DRE(eta_LR,r_hat,r_hat_ring)[1]],[None, torch.abs(r_hat_ring.mean()-ref).item()]], columns = ("DE","DRE"), index = ("OT", "MMD","NAB", "GIPW-RF","GIPW-XGB","GIPW-LR","G-computation")) # ## Bad regression model: Linear regression # In[32]: # In[ ]: # ## Good regression model: XGBoosting # In[33]: XGB_R = xgb.XGBRegressor(n_estimators = 20, gamma = 1e-0) model_r = XGB_R r_hat,r_hat_ring = get_r_estimation(model_r) # In[34]: pd.set_option("display.precision", 2) table_good_reg = pd.DataFrame([[get_DE(eta_OT)[1],get_DRE(eta_OT,r_hat,r_hat_ring)[1]],[get_DE(eta_MMD)[1],get_DRE(eta_MMD,r_hat,r_hat_ring)[1]], [get_DE(eta_NAB)[1],get_DRE(eta_NAB,r_hat,r_hat_ring)[1]], [get_DE(eta_RF)[1],get_DRE(eta_RF,r_hat,r_hat_ring)[1]],[get_DE(eta_XGB)[1],get_DRE(eta_XGB,r_hat,r_hat_ring)[1]], [get_DE(eta_LR)[1],get_DRE(eta_LR,r_hat,r_hat_ring)[1]],[None, torch.abs(r_hat_ring.mean()-ref).item()]], columns = ("DE","DRE"), index = ("OT", "MMD","NAB", "GIPW-RF","GIPW-XGB","GIPW-LR","G-computation")) # In[35]: return table_bad_reg, table_good_reg
29.713092
627
0.524609
import torch import numpy as np import matplotlib.pyplot as plt import pandas as pd from utils_balancing import * def static_simulation(): n = 5000 m = 5000 d = 1 r = lambda x:(x-3).square() + (x>-2)*(x+3).square() +x.abs() def get_data(n = 500,m = 500, r = r, d = d): def pi(x): return torch.sin(x)+ 2*torch.rand(x.shape)-1 def pi_ring(x): return torch.sin(x)+ 1*torch.rand(x.shape)-0.5 xi = torch.normal(mean = -1, std = 2, size = (n,d)) xi_ring = torch.zeros(size = (m,d)) for i in range(m): if torch.rand(1).item()>0.3: xi_ring[i,0] = torch.normal(mean = -4, std = 2, size = (1,)).item() else: xi_ring[i,0] = torch.normal(mean = 3, std = 0.2, size = (1,)).item() w = torch.ones(n) w_ring = torch.ones(m) xi_natural = torch.cat((xi, pi(xi)),axis = 1) xi_ring_natural = torch.cat((xi_ring, pi_ring(xi_ring)), axis = 1) Z =xi_natural[:,0]+xi_natural[:,1] + torch.rand((n,)) Z_ring =xi_ring_natural[:,0]+xi_ring_natural[:,1]+torch.rand((m,)) R = r(Z) return xi_natural,xi_ring_natural,R,Z,Z_ring , xi_ring_natural,R,Z,Z_ring = get_data(n = 50000, m = 50000) ref = r(Z_ring).mean() r) def get_split_ind(n,K = 3): I_n = torch.arange(n, dtype = float) rand_ind_n = torch.multinomial(I_n,len(I_n),replacement = False) num_folds_n = int(n/K) Ind = [] for i in range(K): if (i+1)*num_folds_n <= n: Ind.append(list(rand_ind_n[i*num_folds_n:(i+1)*num_folds_n].detach().numpy())) else: Ind.append(list(rand_ind_n[i*num_folds_n:].detach().numpy())) Ind_split = [] for i in range(K): list_n = [] for j in range(n): if j >= i*num_folds_n and j < (i+1)*num_folds_n: pass else: list_n.append(rand_ind_n[j].item()) Ind_split.append(list_n) return Ind_split,Ind K = 3 Ind_out, Ind_in = get_split_ind(n,K) from sklearn.ensemble import RandomForestRegressor import xgboost as xgb from sklearn.linear_model import LogisticRegression XGB = xgb.XGBRegressor(gamma = 5e0) RF = RandomForestRegressor(n_estimators = 20, min_samples_split = 20) LR = LogisticRegression() def get_GIPW_weights(model): eta = np.zeros(n) for k in range(K): SGIPW = Shallow_GIPW(xi_natural[Ind_out[k],:], xi_ring_natural) SGIPW.train(model,xi = np.array(xi_natural[Ind_in[k],:]),log=False) eta[Ind_in[k]] = SGIPW.weights*(SGIPW.weights>0) return eta eta_XGB = get_GIPW_weights(XGB) eta_RF = get_GIPW_weights(RF) eta_LR = get_GIPW_weights(LR) OTB = OptimalTransportBalancing() eta_OT = OTB.get_weights(xi_natural,xi_ring_natural) eta_OT = eta_OT.detach().numpy() lambda_RKHS = 1e2 lambda_l2 = 1e-3 MMDB = MMDBalancing(xi_natural,xi_ring_natural,sigma = 5e-1,D = 2000) eta_MMD = MMDB.get_weights(lambda_RKHS = lambda_RKHS, lambda_l2 = lambda_l2) eta_MMD = eta_MMD.to("cpu").detach().numpy() class NeuralNetwork(nn.Module): def __init__(self,input_dim = 1, num_nodes = 32): super(NeuralNetwork, self).__init__() self.flatten = nn.Flatten() self.linear_relu_stack = nn.Sequential( nn.Linear(input_dim, num_nodes), nn.ReLU(), nn.Linear(num_nodes, num_nodes), nn.ReLU(), nn.Linear(num_nodes, num_nodes), nn.ReLU(), nodes, 1), ) def forward(self, x): x = self.flatten(x) target = self.linear_relu_stack(x) return target AB = Adversarial_Balancing(xi_natural,xi_ring_natural) num_nodes_IPM = 24 model_IPM = NeuralNetwork(input_dim = d*2,num_nodes = 2*num_nodes_IPM).to(AB.dev) model_reweighting = NeuralNetwork(input_dim = d*2, num_nodes = num_nodes_IPM).to(AB.dev) learning_rate = 1e-3 optimizer_IPM = torch.optim.Adam(model_IPM.parameters(), lr=learning_rate, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=True) optimizer_reweighting = torch.optim.Adam(model_reweighting.parameters(), lr=learning_rate, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=True) epochs = 50 loss_trace = [] for t in range(epochs): current_test_loss = AB.train_loop(model_IPM = model_IPM, model_reweighting = model_reweighting, optimizer_IPM = optimizer_IPM, optimizer_reweighting = optimizer_reweighting, IPM_steps = 3, reweight_steps = 3, lambda_l2_weight = 5e-2, lambda_l2_IPM = 1e-2, lambda_l1_IPM = 1e-2, ) loss_trace.append(current_test_loss.to("cpu").detach().numpy()) weights = model_reweighting(xi_natural.to("cuda:0")) eta_NAB = weights.to("cpu").detach().numpy() from sklearn.linear_model import LinearRegression RF_R = RandomForestRegressor(n_estimators = 20, min_samples_split = 5) model_r = LinearRegression() def get_r_estimation(model, K = 3): r_hat = np.zeros(n) r_hat_ring = np.zeros(m) for k in range(K): SGIPW = Shallow_GIPW(xi_natural[Ind_out[k],:], xi_ring_natural) model_k = model model_k.fit(xi_natural[Ind_out[k],:].detach().numpy(), R[Ind_out[k]].detach().numpy()) r_hat[Ind_in[k]] = model_k.predict(xi_natural[Ind_in[k]].detach().numpy()) r_hat_ring += model_k.predict(xi_ring_natural.detach().numpy()) r_hat_ring /= K return r_hat, r_hat_ring r_hat,r_hat_ring = get_r_estimation(model_r) def get_DE(eta, R = R, ref= ref): try: eta = torch.from_numpy(eta) except: pass pred = (eta*R).mean().item() error = torch.abs(pred - ref).item() return pred, error def get_DRE(eta,r_hat, r_hat_ring, R = R, ref = ref): try: eta = torch.from_numpy(eta) r_hat = torch.from_numpy(r_hat) except: pass pred = (eta*(R -r_hat)).mean() + r_hat_ring.mean() error = torch.abs(pred - ref).item() return pred.item(), error table_bad_reg = pd.DataFrame([[get_DE(eta_OT)[1],get_DRE(eta_OT,r_hat,r_hat_ring)[1]],[get_DE(eta_MMD)[1],get_DRE(eta_MMD,r_hat,r_hat_ring)[1]], [get_DE(eta_NAB)[1],get_DRE(eta_NAB,r_hat,r_hat_ring)[1]], [get_DE(eta_RF)[1],get_DRE(eta_RF,r_hat,r_hat_ring)[1]],[get_DE(eta_XGB)[1],get_DRE(eta_XGB,r_hat,r_hat_ring)[1]], [get_DE(eta_LR)[1],get_DRE(eta_LR,r_hat,r_hat_ring)[1]],[None, torch.abs(r_hat_ring.mean()-ref).item()]], columns = ("DE","DRE"), index = ("OT", "MMD","NAB", "GIPW-RF","GIPW-XGB","GIPW-LR","G-computation")) del_r = XGB_R r_hat,r_hat_ring = get_r_estimation(model_r) pd.set_option("display.precision", 2) table_good_reg = pd.DataFrame([[get_DE(eta_OT)[1],get_DRE(eta_OT,r_hat,r_hat_ring)[1]],[get_DE(eta_MMD)[1],get_DRE(eta_MMD,r_hat,r_hat_ring)[1]], [get_DE(eta_NAB)[1],get_DRE(eta_NAB,r_hat,r_hat_ring)[1]], [get_DE(eta_RF)[1],get_DRE(eta_RF,r_hat,r_hat_ring)[1]],[get_DE(eta_XGB)[1],get_DRE(eta_XGB,r_hat,r_hat_ring)[1]], [get_DE(eta_LR)[1],get_DRE(eta_LR,r_hat,r_hat_ring)[1]],[None, torch.abs(r_hat_ring.mean()-ref).item()]], columns = ("DE","DRE"), index = ("OT", "MMD","NAB", "GIPW-RF","GIPW-XGB","GIPW-LR","G-computation")) return table_bad_reg, table_good_reg
true
true
f710fe105613de2bff1cca2a11388db455eb4ef3
6,442
py
Python
povary/apps/articles/models.py
TorinAsakura/cooking
cf0c78f613fa9ce0fcd4ec7a397ab880d9dd631a
[ "BSD-3-Clause" ]
null
null
null
povary/apps/articles/models.py
TorinAsakura/cooking
cf0c78f613fa9ce0fcd4ec7a397ab880d9dd631a
[ "BSD-3-Clause" ]
null
null
null
povary/apps/articles/models.py
TorinAsakura/cooking
cf0c78f613fa9ce0fcd4ec7a397ab880d9dd631a
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- import datetime from django.db.models import Count import os from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db.models.signals import post_save from django.dispatch import receiver from uuslug import uuslug as slugify from sorl.thumbnail import ImageField from tags.models import Tag, TaggedItem from comments.models import Comment, CommentAnswer def category_upload_path(instance, filename): from utils import timestampbased_filename category_slug = slugify(instance.title) path = os.path.join( 'article_category', category_slug, timestampbased_filename(filename) ) return path def article_upload_path(instance, filename): from utils import timestampbased_filename article_slug = slugify(instance.title) path = os.path.join( 'articles', article_slug, timestampbased_filename(filename) ) return path class ArticleCategory(models.Model): title = models.CharField("Заголовок", max_length=255) slug = models.SlugField("URL", unique=True) image = ImageField("Изображение", upload_to=category_upload_path, blank=True, null=True) image_alt = models.CharField("ALT изображения", max_length=255, blank=True, null=True) image_title = models.CharField("TITLE изображения", max_length=255, blank=True, null=True) add_watermark = models.BooleanField("Добавлять водяной знак?", default=False) description = models.TextField("Описание", blank=True, null=True) author = models.ForeignKey(User, verbose_name="Автор") published = models.BooleanField("Опубликовано", default=True) created = models.DateTimeField("Время создания", auto_now_add=True) updated = models.DateTimeField("Время последнего обновления", auto_now=True) visits_num = models.PositiveIntegerField("Кол. посещений", default=0, editable=False) def set_tags(self, tags): Tag.objects.update_tags(self, tags) def get_tags(self, tags): return Tag.objects.get_for_object(self) def inc_visits(self): self.visits_num += 1 self.save() @property def tags(self): content_type = ContentType.objects.get_for_model(self) try: tagged_item = TaggedItem.objects.get(content_type=content_type, object_id=self.id)\ .prefetch_related('tags') except TaggedItem.DoesNotExist: return [] return tagged_item.tags.all() def get_absolute_url(self): return reverse("articlecategory_details", args=(self.slug, )) def __unicode__(self): return self.title class Meta: verbose_name = "Категория статей" verbose_name_plural = "Категории статей" class Article(models.Model): title = models.CharField("Заголовок", max_length=255) slug = models.SlugField("URL", unique=True) old_id = models.IntegerField("Старый ID", unique=True, blank=True, null=True) image = models.ImageField("Изображение", upload_to=article_upload_path, blank=True, null=True ) image_alt = models.CharField("ALT изображения", max_length=255, blank=True, null=True) image_title = models.CharField("TITLE изображения", max_length=255, blank=True, null=True) add_watermark = models.BooleanField("Добавлять водяной знак?", default=False) description = models.TextField("Описание", blank=True, null=True) body = models.TextField("Текст статьи") author = models.ForeignKey(User, verbose_name="Автор") category = models.ForeignKey(ArticleCategory, verbose_name="Категория", related_name="articles") verified = models.BooleanField("Проверена", default=False) published = models.BooleanField("Опубликовано", default=True) pub_date = models.DateTimeField("Опубликовано", blank=True) created = models.DateTimeField("Создано", auto_now_add=True) updated = models.DateTimeField("Обновлено", auto_now=True) visits_num = models.PositiveIntegerField("Кол. посещений", default=0, editable=False) comments_num = models.PositiveIntegerField(u"Кол. коментариев", default=0, editable=False) def inc_visits(self): self.visits_num += 1 self.save() @property def num_comments(self): comments = Comment.objects.filter( content_type_id=ContentType.objects.get_for_model(self).id, object_id=self.id ).annotate(answer_count=Count('answers')).values_list('answer_count', flat=True) cnt = 0 for i in range(len(comments)): cnt += 1 + comments[i] return cnt @property def tags(self): content_type = ContentType.objects.get_for_model(self) try: tagged_item = TaggedItem.objects.get(content_type=content_type, object_id=self.id) except TaggedItem.DoesNotExist: return [] return tagged_item.tags.all() def save(self, *args, **kwargs): if not self.pub_date: self.pub_date = datetime.datetime.now() super(Article, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("article_details", args=(self.slug, )) def get_contenttype_id(self): return ContentType.objects.get_for_model(Article).id def __unicode__(self): return self.title class Meta: verbose_name = "Статья" verbose_name_plural = "Статьи" @receiver(post_save, sender=Article) def publish_article_task(sender, instance, created, **kwargs): from articles.tasks import publish_article if not instance.published: publish_article.apply_async(args=(instance, ), eta=instance.pub_date) @receiver(post_save, sender=Article) def article_watermark(sender, instance, created, **kwargs): if not instance.add_watermark: return from utils import add_watermark marked_img = add_watermark(instance.image) if not marked_img: return instance.image = marked_img instance.save() @receiver(post_save, sender=ArticleCategory) def articlecategory_watermark(sender, instance, created, **kwargs): if not instance.add_watermark: return from utils import add_watermark marked_img = add_watermark(instance.image) if not marked_img: return instance.image = marked_img instance.save()
34.265957
100
0.703043
import datetime from django.db.models import Count import os from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db.models.signals import post_save from django.dispatch import receiver from uuslug import uuslug as slugify from sorl.thumbnail import ImageField from tags.models import Tag, TaggedItem from comments.models import Comment, CommentAnswer def category_upload_path(instance, filename): from utils import timestampbased_filename category_slug = slugify(instance.title) path = os.path.join( 'article_category', category_slug, timestampbased_filename(filename) ) return path def article_upload_path(instance, filename): from utils import timestampbased_filename article_slug = slugify(instance.title) path = os.path.join( 'articles', article_slug, timestampbased_filename(filename) ) return path class ArticleCategory(models.Model): title = models.CharField("Заголовок", max_length=255) slug = models.SlugField("URL", unique=True) image = ImageField("Изображение", upload_to=category_upload_path, blank=True, null=True) image_alt = models.CharField("ALT изображения", max_length=255, blank=True, null=True) image_title = models.CharField("TITLE изображения", max_length=255, blank=True, null=True) add_watermark = models.BooleanField("Добавлять водяной знак?", default=False) description = models.TextField("Описание", blank=True, null=True) author = models.ForeignKey(User, verbose_name="Автор") published = models.BooleanField("Опубликовано", default=True) created = models.DateTimeField("Время создания", auto_now_add=True) updated = models.DateTimeField("Время последнего обновления", auto_now=True) visits_num = models.PositiveIntegerField("Кол. посещений", default=0, editable=False) def set_tags(self, tags): Tag.objects.update_tags(self, tags) def get_tags(self, tags): return Tag.objects.get_for_object(self) def inc_visits(self): self.visits_num += 1 self.save() @property def tags(self): content_type = ContentType.objects.get_for_model(self) try: tagged_item = TaggedItem.objects.get(content_type=content_type, object_id=self.id)\ .prefetch_related('tags') except TaggedItem.DoesNotExist: return [] return tagged_item.tags.all() def get_absolute_url(self): return reverse("articlecategory_details", args=(self.slug, )) def __unicode__(self): return self.title class Meta: verbose_name = "Категория статей" verbose_name_plural = "Категории статей" class Article(models.Model): title = models.CharField("Заголовок", max_length=255) slug = models.SlugField("URL", unique=True) old_id = models.IntegerField("Старый ID", unique=True, blank=True, null=True) image = models.ImageField("Изображение", upload_to=article_upload_path, blank=True, null=True ) image_alt = models.CharField("ALT изображения", max_length=255, blank=True, null=True) image_title = models.CharField("TITLE изображения", max_length=255, blank=True, null=True) add_watermark = models.BooleanField("Добавлять водяной знак?", default=False) description = models.TextField("Описание", blank=True, null=True) body = models.TextField("Текст статьи") author = models.ForeignKey(User, verbose_name="Автор") category = models.ForeignKey(ArticleCategory, verbose_name="Категория", related_name="articles") verified = models.BooleanField("Проверена", default=False) published = models.BooleanField("Опубликовано", default=True) pub_date = models.DateTimeField("Опубликовано", blank=True) created = models.DateTimeField("Создано", auto_now_add=True) updated = models.DateTimeField("Обновлено", auto_now=True) visits_num = models.PositiveIntegerField("Кол. посещений", default=0, editable=False) comments_num = models.PositiveIntegerField(u"Кол. коментариев", default=0, editable=False) def inc_visits(self): self.visits_num += 1 self.save() @property def num_comments(self): comments = Comment.objects.filter( content_type_id=ContentType.objects.get_for_model(self).id, object_id=self.id ).annotate(answer_count=Count('answers')).values_list('answer_count', flat=True) cnt = 0 for i in range(len(comments)): cnt += 1 + comments[i] return cnt @property def tags(self): content_type = ContentType.objects.get_for_model(self) try: tagged_item = TaggedItem.objects.get(content_type=content_type, object_id=self.id) except TaggedItem.DoesNotExist: return [] return tagged_item.tags.all() def save(self, *args, **kwargs): if not self.pub_date: self.pub_date = datetime.datetime.now() super(Article, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("article_details", args=(self.slug, )) def get_contenttype_id(self): return ContentType.objects.get_for_model(Article).id def __unicode__(self): return self.title class Meta: verbose_name = "Статья" verbose_name_plural = "Статьи" @receiver(post_save, sender=Article) def publish_article_task(sender, instance, created, **kwargs): from articles.tasks import publish_article if not instance.published: publish_article.apply_async(args=(instance, ), eta=instance.pub_date) @receiver(post_save, sender=Article) def article_watermark(sender, instance, created, **kwargs): if not instance.add_watermark: return from utils import add_watermark marked_img = add_watermark(instance.image) if not marked_img: return instance.image = marked_img instance.save() @receiver(post_save, sender=ArticleCategory) def articlecategory_watermark(sender, instance, created, **kwargs): if not instance.add_watermark: return from utils import add_watermark marked_img = add_watermark(instance.image) if not marked_img: return instance.image = marked_img instance.save()
true
true
f710fe740f06cd1ce7d6e17259b4673874db184d
315
py
Python
app/thumbnails/utils.py
zybex86/pics
4ae4dcc0610ac37b5dae16a15328740e78868e50
[ "MIT" ]
null
null
null
app/thumbnails/utils.py
zybex86/pics
4ae4dcc0610ac37b5dae16a15328740e78868e50
[ "MIT" ]
null
null
null
app/thumbnails/utils.py
zybex86/pics
4ae4dcc0610ac37b5dae16a15328740e78868e50
[ "MIT" ]
null
null
null
from pathlib import Path from PIL import Image, ImageOps def generate_thumbnail(file_path, max_height): size = (max_height, max_height) thumbnail = ImageOps.fit(Image.open(file_path), size, Image.ANTIALIAS) thumbnail.save(f'{Path(file_path).stem}_thumb_{max_height}.jpg', 'JPEG') return thumbnail
31.5
76
0.752381
from pathlib import Path from PIL import Image, ImageOps def generate_thumbnail(file_path, max_height): size = (max_height, max_height) thumbnail = ImageOps.fit(Image.open(file_path), size, Image.ANTIALIAS) thumbnail.save(f'{Path(file_path).stem}_thumb_{max_height}.jpg', 'JPEG') return thumbnail
true
true
f710feaab45379a8bd9c845b0521809c0d560557
2,804
py
Python
tests/restapi/conftest.py
louisponet/aiida-core
3214236df66a3792ee57fe38a06c0c3bb65861ab
[ "MIT", "BSD-3-Clause" ]
1
2016-09-12T10:51:00.000Z
2016-09-12T10:51:00.000Z
tests/restapi/conftest.py
louisponet/aiida-core
3214236df66a3792ee57fe38a06c0c3bb65861ab
[ "MIT", "BSD-3-Clause" ]
17
2020-03-11T17:04:05.000Z
2020-05-01T09:34:45.000Z
tests/restapi/conftest.py
louisponet/aiida-core
3214236df66a3792ee57fe38a06c0c3bb65861ab
[ "MIT", "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """pytest fixtures for use with the aiida.restapi tests""" import pytest @pytest.fixture(scope='function') def restapi_server(): """Make REST API server""" from werkzeug.serving import make_server from aiida.restapi.common.config import CLI_DEFAULTS from aiida.restapi.run_api import configure_api def _restapi_server(restapi=None): if restapi is None: flask_restapi = configure_api() else: flask_restapi = configure_api(flask_api=restapi) return make_server( host=CLI_DEFAULTS['HOST_NAME'], port=int(CLI_DEFAULTS['PORT']), app=flask_restapi.app, threaded=True, processes=1, request_handler=None, passthrough_errors=True, ssl_context=None, fd=None ) return _restapi_server @pytest.fixture def server_url(): from aiida.restapi.common.config import CLI_DEFAULTS, API_CONFIG return f"http://{CLI_DEFAULTS['HOST_NAME']}:{CLI_DEFAULTS['PORT']}{API_CONFIG['PREFIX']}" @pytest.fixture def restrict_sqlalchemy_queuepool(aiida_profile): """Create special SQLAlchemy engine for use with QueryBuilder - backend-agnostic""" from aiida.manage.manager import get_manager backend_manager = get_manager().get_backend_manager() backend_manager.reset_backend_environment() backend_manager.load_backend_environment(aiida_profile, pool_timeout=1, max_overflow=0) @pytest.fixture def populate_restapi_database(clear_database_before_test): """Populates the database with a considerable set of nodes to test the restAPI""" # pylint: disable=unused-argument from aiida import orm struct_forcif = orm.StructureData().store() orm.StructureData().store() orm.StructureData().store() orm.Dict().store() orm.Dict().store() orm.CifData(ase=struct_forcif.get_ase()).store() orm.KpointsData().store() orm.FolderData().store() orm.CalcFunctionNode().store() orm.CalcJobNode().store() orm.CalcJobNode().store() orm.WorkFunctionNode().store() orm.WorkFunctionNode().store() orm.WorkChainNode().store()
32.604651
93
0.617689
true
true
f710ff32c9f3aa02f5a96ffecb083dfc2a5d990b
3,884
py
Python
xuerui_stat/analysis/random_forest/plot_tree.py
Xuerui-Yang/xuerui-stat
08b9dfedac810cbad5ee5969ca554212eb989db0
[ "MIT" ]
1
2019-11-02T03:00:52.000Z
2019-11-02T03:00:52.000Z
xuerui_stat/analysis/random_forest/plot_tree.py
Xuerui-Yang/xuerui-stat
08b9dfedac810cbad5ee5969ca554212eb989db0
[ "MIT" ]
4
2019-11-02T06:50:08.000Z
2019-11-02T06:50:18.000Z
xuerui_stat/analysis/random_forest/plot_tree.py
Xuerui-Yang/xuerui-stat
08b9dfedac810cbad5ee5969ca554212eb989db0
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt import seaborn as sns class PlotTree(): def __init__(self,tree_class): self._tree_class=tree_class self._decision_node = dict(boxstyle="sawtooth", fc="0.8") self._leaf_node = dict(boxstyle="round4", fc="0.8") self._arrow_args = dict(arrowstyle="<-") def __get_tree_depth(self,tree): """获取树的深度""" depth = 0 # 定义的dict中首位储存的是节点信息,不计入计数 for key in ('Left', 'Right'): # 记录各子节点的深度 sub_tree = tree[key] if type(sub_tree).__name__ == "dict": # 如果该节点有分支,迭代计算该节点的深度 thisdepth = self.__get_tree_depth(sub_tree) else: # 否则深度为一 thisdepth = 1 # 比较各分支深度,保留最深记录 if thisdepth > depth: depth = thisdepth # 分支深度加一即为当前节点深度 return depth + 1 def __plot_node(self,node_txt, cntr_pt, prnt_pt, node_type): self._ax1.annotate(node_txt, xy=prnt_pt, xycoords='axes fraction', xytext=cntr_pt, textcoords='axes fraction', va="center", ha="center", bbox=node_type, arrowprops=self._arrow_args) def __plot_mid_text(self,cntr_pt, prnt_pt, txt_string): xMid = (prnt_pt[0] - cntr_pt[0]) / 2.0 + cntr_pt[0] yMid = (prnt_pt[1] - cntr_pt[1]) / 2.0 + cntr_pt[1] self._ax1.text(xMid, yMid, txt_string, va="center", ha="center", rotation=30) def __plot_tree(self,tree, prnt_pt, node_txt, branch=None): self._layer += 1 diff = 1 / 2**(self._layer) keys = list(tree.keys()) text = tree[keys[0]] if branch == 'Left': self._xOff -= diff elif branch == 'Right': self._xOff += diff else: pass cntr_pt = (self._xOff, self._yOff) self.__plot_mid_text(cntr_pt, prnt_pt, node_txt) self.__plot_node(text, cntr_pt, prnt_pt, self._decision_node) self._yOff = self._yOff - 1.0 / self._totalD for key in keys[1:]: sub_tree = tree[key] if type(sub_tree).__name__ == 'dict': self.__plot_tree(sub_tree, cntr_pt, str(key), key) else: if key == 'Left': x = self._xOff - diff / 2 elif key == 'Right': x = self._xOff + diff / 2 else: pass self.__plot_node(sub_tree, (x, self._yOff), cntr_pt, self._leaf_node) self.__plot_mid_text((x, self._yOff), cntr_pt, str(key)) if branch == 'Left': self._xOff += diff elif branch == 'Right': self._xOff -= diff else: pass self._layer -= 1 self._yOff = self._yOff + 1.0 / self._totalD def tree_structure_plot(self): fig = plt.figure(1, facecolor='white') fig.clf() axprops = dict(xticks=[], yticks=[]) self._ax1 = plt.subplot(111, frameon=False, **axprops) self._totalD = float(self.__get_tree_depth(self._tree_class.tree)) self._xOff = 0.5 self._yOff = 1.0 self._layer = 0 self.__plot_tree(self._tree_class.tree, (0.5, 1.0), '') plt.show() def confusion_matrix_plot(self): mat=self._tree_class.confusion_matrix if mat is None: print("The confusion matrix is not computed. Please use 'test()' in 'DecisionTree' class to get it.") else: fig, ax = plt.subplots(figsize=(6, 6)) sns.heatmap(mat,xticklabels=mat.columns,yticklabels=mat.index, cbar_kws={"shrink": .5}, ax=ax) plt.tight_layout() plt.show()
37.346154
114
0.523687
import matplotlib.pyplot as plt import seaborn as sns class PlotTree(): def __init__(self,tree_class): self._tree_class=tree_class self._decision_node = dict(boxstyle="sawtooth", fc="0.8") self._leaf_node = dict(boxstyle="round4", fc="0.8") self._arrow_args = dict(arrowstyle="<-") def __get_tree_depth(self,tree): depth = 0 for key in ('Left', 'Right'): sub_tree = tree[key] if type(sub_tree).__name__ == "dict": thisdepth = self.__get_tree_depth(sub_tree) else: thisdepth = 1 if thisdepth > depth: depth = thisdepth return depth + 1 def __plot_node(self,node_txt, cntr_pt, prnt_pt, node_type): self._ax1.annotate(node_txt, xy=prnt_pt, xycoords='axes fraction', xytext=cntr_pt, textcoords='axes fraction', va="center", ha="center", bbox=node_type, arrowprops=self._arrow_args) def __plot_mid_text(self,cntr_pt, prnt_pt, txt_string): xMid = (prnt_pt[0] - cntr_pt[0]) / 2.0 + cntr_pt[0] yMid = (prnt_pt[1] - cntr_pt[1]) / 2.0 + cntr_pt[1] self._ax1.text(xMid, yMid, txt_string, va="center", ha="center", rotation=30) def __plot_tree(self,tree, prnt_pt, node_txt, branch=None): self._layer += 1 diff = 1 / 2**(self._layer) keys = list(tree.keys()) text = tree[keys[0]] if branch == 'Left': self._xOff -= diff elif branch == 'Right': self._xOff += diff else: pass cntr_pt = (self._xOff, self._yOff) self.__plot_mid_text(cntr_pt, prnt_pt, node_txt) self.__plot_node(text, cntr_pt, prnt_pt, self._decision_node) self._yOff = self._yOff - 1.0 / self._totalD for key in keys[1:]: sub_tree = tree[key] if type(sub_tree).__name__ == 'dict': self.__plot_tree(sub_tree, cntr_pt, str(key), key) else: if key == 'Left': x = self._xOff - diff / 2 elif key == 'Right': x = self._xOff + diff / 2 else: pass self.__plot_node(sub_tree, (x, self._yOff), cntr_pt, self._leaf_node) self.__plot_mid_text((x, self._yOff), cntr_pt, str(key)) if branch == 'Left': self._xOff += diff elif branch == 'Right': self._xOff -= diff else: pass self._layer -= 1 self._yOff = self._yOff + 1.0 / self._totalD def tree_structure_plot(self): fig = plt.figure(1, facecolor='white') fig.clf() axprops = dict(xticks=[], yticks=[]) self._ax1 = plt.subplot(111, frameon=False, **axprops) self._totalD = float(self.__get_tree_depth(self._tree_class.tree)) self._xOff = 0.5 self._yOff = 1.0 self._layer = 0 self.__plot_tree(self._tree_class.tree, (0.5, 1.0), '') plt.show() def confusion_matrix_plot(self): mat=self._tree_class.confusion_matrix if mat is None: print("The confusion matrix is not computed. Please use 'test()' in 'DecisionTree' class to get it.") else: fig, ax = plt.subplots(figsize=(6, 6)) sns.heatmap(mat,xticklabels=mat.columns,yticklabels=mat.index, cbar_kws={"shrink": .5}, ax=ax) plt.tight_layout() plt.show()
true
true
f710ffa92c65c26a8bceb22d583bbb5d86dd8d0f
955
py
Python
lib/coloraide/distance/delta_e_z.py
CodeByZach/sublime_color_helper
9d881e1f036c886fedd94b026735c4727b7a34d3
[ "MIT" ]
14
2021-12-07T02:40:08.000Z
2022-01-24T19:38:17.000Z
lib/coloraide/distance/delta_e_z.py
CodeByZach/sublime_color_helper
9d881e1f036c886fedd94b026735c4727b7a34d3
[ "MIT" ]
null
null
null
lib/coloraide/distance/delta_e_z.py
CodeByZach/sublime_color_helper
9d881e1f036c886fedd94b026735c4727b7a34d3
[ "MIT" ]
null
null
null
""" Delta E z. https://www.osapublishing.org/oe/fulltext.cfm?uri=oe-25-13-15131&id=368272 """ from ..distance import DeltaE import math from .. import util from typing import TYPE_CHECKING, Any if TYPE_CHECKING: # pragma: no cover from ..color import Color class DEZ(DeltaE): """Delta E z class.""" NAME = "jz" @classmethod def distance(cls, color: 'Color', sample: 'Color', **kwargs: Any) -> float: """Delta E z color distance formula.""" jz1, az1, bz1 = util.no_nans(color.convert('jzazbz').coords()) jz2, az2, bz2 = util.no_nans(sample.convert('jzazbz').coords()) cz1 = math.sqrt(az1 ** 2 + bz1 ** 2) cz2 = math.sqrt(az2 ** 2 + bz2 ** 2) hz1 = math.atan2(bz1, az1) hz2 = math.atan2(bz2, az2) djz = jz1 - jz2 dcz = cz1 - cz2 dhz = 2 * math.sqrt(cz1 * cz2) * math.sin((hz1 - hz2) / 2) return math.sqrt(djz ** 2 + dcz ** 2 + dhz ** 2)
25.131579
79
0.57801
from ..distance import DeltaE import math from .. import util from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from ..color import Color class DEZ(DeltaE): NAME = "jz" @classmethod def distance(cls, color: 'Color', sample: 'Color', **kwargs: Any) -> float: jz1, az1, bz1 = util.no_nans(color.convert('jzazbz').coords()) jz2, az2, bz2 = util.no_nans(sample.convert('jzazbz').coords()) cz1 = math.sqrt(az1 ** 2 + bz1 ** 2) cz2 = math.sqrt(az2 ** 2 + bz2 ** 2) hz1 = math.atan2(bz1, az1) hz2 = math.atan2(bz2, az2) djz = jz1 - jz2 dcz = cz1 - cz2 dhz = 2 * math.sqrt(cz1 * cz2) * math.sin((hz1 - hz2) / 2) return math.sqrt(djz ** 2 + dcz ** 2 + dhz ** 2)
true
true
f71100307ac314b71fd446938bf616987ca61fb0
40,965
py
Python
thinc/types.py
notplus/thinc
9228eba1a0af20fb0de80970791c601549b40e26
[ "MIT" ]
null
null
null
thinc/types.py
notplus/thinc
9228eba1a0af20fb0de80970791c601549b40e26
[ "MIT" ]
null
null
null
thinc/types.py
notplus/thinc
9228eba1a0af20fb0de80970791c601549b40e26
[ "MIT" ]
null
null
null
from typing import Union, Tuple, Sized, Container, Any, TypeVar, Callable from typing import Iterable, Iterator, Sequence, Dict, Generic, cast from typing import Optional, List, overload from dataclasses import dataclass import numpy import sys try: import cupy get_array_module = cupy.get_array_module except ImportError: get_array_module = lambda obj: numpy # Use typing_extensions for Python versions < 3.8 if sys.version_info < (3, 8): from typing_extensions import Protocol, Literal else: from typing import Protocol, Literal # noqa: F401 # fmt: off XY_YZ_OutT = TypeVar("XY_YZ_OutT") XY_XY_OutT = TypeVar("XY_XY_OutT") DeviceTypes = Literal["cpu", "gpu", "tpu"] Batchable = Union["Pairs", "Ragged", "Padded", "ArrayXd", List, Tuple] Xp = Union["numpy", "cupy"] # type: ignore Shape = Tuple[int, ...] DTypes = Literal["f", "i", "float16", "float32", "float64", "int32", "int64", "uint32", "uint64"] DTypesFloat = Literal["f", "float32", "float16", "float64"] DTypesInt = Literal["i", "int32", "int64", "uint32", "uint64"] Array1d = Union["Floats1d", "Ints1d"] Array2d = Union["Floats2d", "Ints2d"] Array3d = Union["Floats3d", "Ints3d"] Array4d = Union["Floats4d", "Ints4d"] FloatsXd = Union["Floats1d", "Floats2d", "Floats3d", "Floats4d"] IntsXd = Union["Ints1d", "Ints2d", "Ints3d", "Ints4d"] ArrayXd = Union[FloatsXd, IntsXd] List1d = Union[List["Floats1d"], List["Ints1d"]] List2d = Union[List["Floats2d"], List["Ints2d"]] List3d = Union[List["Floats3d"], List["Ints3d"]] List4d = Union[List["Floats4d"], List["Ints4d"]] ListXd = Union[List["FloatsXd"], List["IntsXd"]] ArrayT = TypeVar("ArrayT") SelfT = TypeVar("SelfT") Array1dT = TypeVar("Array1dT", bound="Array1d") # These all behave the same as far as indexing is concerned Slicish = Union[slice, List[int], "ArrayXd"] _1_KeyScalar = int _1_Key1d = Slicish _1_AllKeys = Union[_1_KeyScalar, _1_Key1d] _F1_AllReturns = Union[float, "Floats1d"] _I1_AllReturns = Union[int, "Ints1d"] _2_KeyScalar = Tuple[int, int] _2_Key1d = Union[int, Tuple[Slicish, int], Tuple[int, Slicish]] _2_Key2d = Union[Tuple[Slicish, Slicish], Slicish] _2_AllKeys = Union[_2_KeyScalar, _2_Key1d, _2_Key2d] _F2_AllReturns = Union[float, "Floats1d", "Floats2d"] _I2_AllReturns = Union[int, "Ints1d", "Ints2d"] _3_KeyScalar = Tuple[int, int, int] _3_Key1d = Union[Tuple[int, int], Tuple[int, int, Slicish], Tuple[int, Slicish, int], Tuple[Slicish, int, int]] _3_Key2d = Union[int, Tuple[int, Slicish], Tuple[Slicish, int], Tuple[int, Slicish, Slicish], Tuple[Slicish, int, Slicish], Tuple[Slicish, Slicish, int]] _3_Key3d = Union[Slicish, Tuple[Slicish, Slicish], Tuple[Slicish, Slicish, Slicish]] _3_AllKeys = Union[_3_KeyScalar, _3_Key1d, _3_Key2d, _3_Key3d] _F3_AllReturns = Union[float, "Floats1d", "Floats2d", "Floats3d"] _I3_AllReturns = Union[int, "Ints1d", "Ints2d", "Ints3d"] _4_KeyScalar = Tuple[int, int, int, int] _4_Key1d = Union[Tuple[int, int, int], Tuple[int, int, int, Slicish], Tuple[int, int, Slicish, int], Tuple[int, Slicish, int, int], Tuple[Slicish, int, int, int]] _4_Key2d = Union[Tuple[int, int], Tuple[int, int, Slicish], Tuple[int, Slicish, int], Tuple[Slicish, int, int], Tuple[int, int, Slicish, Slicish], Tuple[int, Slicish, int, Slicish], Tuple[int, Slicish, Slicish, int], Tuple[Slicish, int, int, Slicish], Tuple[Slicish, int, Slicish, int], Tuple[Slicish, Slicish, int, int]] _4_Key3d = Union[int, Tuple[int, Slicish], Tuple[Slicish, int], Tuple[int, Slicish, Slicish], Tuple[Slicish, int, Slicish], Tuple[Slicish, Slicish, int], Tuple[int, Slicish, Slicish, Slicish], Tuple[Slicish, int, Slicish, Slicish], Tuple[Slicish, Slicish, int, Slicish], Tuple[Slicish, Slicish, Slicish, int]] _4_Key4d = Union[Slicish, Tuple[Slicish, Slicish], Tuple[Slicish, Slicish, Slicish], Tuple[Slicish, Slicish, Slicish, Slicish]] _4_AllKeys = Union[_4_KeyScalar, _4_Key1d, _4_Key2d, _4_Key3d, _4_Key4d] _F4_AllReturns = Union[float, "Floats1d", "Floats2d", "Floats3d", "Floats4d"] _I4_AllReturns = Union[int, "Ints1d", "Ints2d", "Ints3d", "Ints4d"] # Typedefs for the reduction methods. Tru = Literal[True] Fal = Literal[False] OneAx = Union[int, Tuple[int]] TwoAx = Tuple[int, int] ThreeAx = Tuple[int, int, int] FourAx = Tuple[int, int, int, int] _1_AllAx = Optional[OneAx] _2_AllAx = Union[Optional[TwoAx], OneAx] _3_AllAx = Union[Optional[ThreeAx], TwoAx, OneAx] _4_AllAx = Union[Optional[FourAx], ThreeAx, TwoAx, OneAx] _1F_ReduceResults = Union[float, "Floats1d"] _2F_ReduceResults = Union[float, "Floats1d", "Floats2d"] _3F_ReduceResults = Union[float, "Floats1d", "Floats2d", "Floats3d"] _4F_ReduceResults = Union[float, "Floats1d", "Floats2d", "Floats3d", "Floats4d"] _1I_ReduceResults = Union[int, "Ints1d"] _2I_ReduceResults = Union[int, "Ints1d", "Ints2d"] _3I_ReduceResults = Union[int, "Ints1d", "Ints2d", "Ints3d"] _4I_ReduceResults = Union[int, "Ints1d", "Ints2d", "Ints3d", "Ints4d"] # TODO: # We need to get correct overloads in for the following reduction methods. # The 'sum' reduction is correct --- the others need to be just the same, # but with a different name. # max, min, prod, round, var, mean, ptp, std # There's also one *slightly* different function, cumsum. This doesn't # have a scalar version -- it always makes an array. class _Array(Sized, Container): @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v) @property def dtype(self) -> DTypes: ... @property def data(self) -> memoryview: ... @property def flags(self) -> Any: ... @property def size(self) -> int: ... @property def itemsize(self) -> int: ... @property def nbytes(self) -> int: ... @property def ndim(self) -> int: ... @property def shape(self) -> Shape: ... @property def strides(self) -> Tuple[int, ...]: ... # TODO: Is ArrayT right? def astype(self: ArrayT, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> ArrayT: ... def copy(self: ArrayT, order: str = ...) -> ArrayT: ... def fill(self, value: Any) -> None: ... # Shape manipulation def reshape(self: ArrayT, shape: Shape, *, order: str = ...) -> ArrayT: ... def transpose(self: ArrayT, axes: Shape) -> ArrayT: ... # TODO: is this right? It returns 1d def flatten(self, order: str = ...): ... # TODO: is this right? It returns 1d def ravel(self, order: str = ...): ... def squeeze(self, axis: Union[int, Shape] = ...): ... def __len__(self) -> int: ... def __setitem__(self, key, value): ... def __iter__(self) -> Iterator[Any]: ... def __contains__(self, key) -> bool: ... def __index__(self) -> int: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __complex__(self) -> complex: ... def __bool__(self) -> bool: ... def __bytes__(self) -> bytes: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... def __copy__(self, order: str = ...): ... def __deepcopy__(self, memo: dict) -> ArrayT: ... def __lt__(self, other): ... def __le__(self, other): ... def __eq__(self, other): ... def __ne__(self, other): ... def __gt__(self, other): ... def __ge__(self, other): ... def __add__(self, other): ... def __radd__(self, other): ... def __iadd__(self, other): ... def __sub__(self, other): ... def __rsub__(self, other): ... def __isub__(self, other): ... def __mul__(self, other): ... def __rmul__(self, other): ... def __imul__(self, other): ... def __truediv__(self, other): ... def __rtruediv__(self, other): ... def __itruediv__(self, other): ... def __floordiv__(self, other): ... def __rfloordiv__(self, other): ... def __ifloordiv__(self, other): ... def __mod__(self, other): ... def __rmod__(self, other): ... def __imod__(self, other): ... def __divmod__(self, other): ... def __rdivmod__(self, other): ... # NumPy's __pow__ doesn't handle a third argument def __pow__(self, other): ... def __rpow__(self, other): ... def __ipow__(self, other): ... def __lshift__(self, other): ... def __rlshift__(self, other): ... def __ilshift__(self, other): ... def __rshift__(self, other): ... def __rrshift__(self, other): ... def __irshift__(self, other): ... def __and__(self, other): ... def __rand__(self, other): ... def __iand__(self, other): ... def __xor__(self, other): ... def __rxor__(self, other): ... def __ixor__(self, other): ... def __or__(self, other): ... def __ror__(self, other): ... def __ior__(self, other): ... def __matmul__(self, other): ... def __rmatmul__(self, other): ... def __neg__(self: ArrayT) -> ArrayT: ... def __pos__(self: ArrayT) -> ArrayT: ... def __abs__(self: ArrayT) -> ArrayT: ... def __invert__(self: ArrayT) -> ArrayT: ... def get(self: ArrayT) -> ArrayT: ... def all(self, axis: int = -1, out: Optional[ArrayT] = None, keepdims: bool = False) -> ArrayT: ... def any(self, axis: int = -1, out: Optional[ArrayT] = None, keepdims: bool = False) -> ArrayT: ... # def argmax(self, axis: int = -1, out: Optional["Array"] = None, keepdims: Union[Tru, Fal]=False) -> Union[int, "Ints1d"]: ... def argmin(self, axis: int = -1, out: Optional[ArrayT] = None) -> ArrayT: ... def clip(self, a_min: Any, a_max: Any, out: Optional[ArrayT]) -> ArrayT: ... #def cumsum( self: ArrayT, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional[ArrayT] = None) -> ArrayT: ... def max(self, axis: int = -1, out: Optional[ArrayT] = None) -> ArrayT: ... # def mean(self, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional[SelfT] = None, keepdims: bool = False) -> "Array": ... def min(self, axis: int = -1, out: Optional[ArrayT] = None) -> ArrayT: ... def nonzero(self) -> ArrayT: ... def prod(self, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional[ArrayT] = None, keepdims: bool = False) -> ArrayT: ... def round(self, decimals: int = 0, out: Optional[ArrayT] = None) -> ArrayT: ... # def sum(self, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional[ArrayT] = None, keepdims: bool = False) -> ArrayT: ... def tobytes(self, order: str = "C") -> bytes: ... def tolist(self) -> List[Any]: ... def var(self: SelfT, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional[ArrayT] = None, ddof: int = 0, keepdims: bool = False) -> SelfT: ... class _Floats(_Array): @property def dtype(self) -> DTypesFloat: ... def fill(self, value: float) -> None: ... def reshape(self, shape: Shape, *, order: str = ...) -> "_Floats": ... class _Ints(_Array): @property def dtype(self) -> DTypesInt: ... def fill(self, value: int) -> None: ... def reshape(self, shape: Shape, *, order: str = ...) -> "_Ints": ... """ Extensive overloads to represent __getitem__ behaviour. In an N+1 dimensional array, there will be N possible return types. For instance, if you have a 2d array, you could get back a float (array[i, j]), a floats1d (array[i]) or a floats2d (array[:i, :j]). You'll get the scalar if you have N ints in the index, a 1d array if you have N-1 ints, etc. So the trick here is to make a union with the various combinations that produce each result type, and then only have one overload per result. If we overloaded on each *key* type, that would get crazy, because there's tonnes of combinations. In each rank, we can use the same key-types for float and int, but we need a different return-type union. """ class _Array1d(_Array): """1-dimensional array.""" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=1) @property def ndim(self) -> Literal[1]: ... @property def shape(self) -> Tuple[int]: ... def __iter__(self) -> Iterator[Union[float, int]]: ... def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "_Array1d": ... def flatten(self: SelfT, order: str = ...) -> SelfT: ... def ravel(self: SelfT, order: str = ...) -> SelfT: ... # These is actually a bit too strict: It's legal to say 'array1d + array2d' # That's kind of bad code though; it's better to write array2d + array1d. # We could relax this, but let's try the strict version. def __add__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __sub__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __mul__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __pow__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __matmul__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... # These are not too strict though: you can't do += with higher dimensional. def __iadd__(self, other: Union[float, int, "Array1d"]): ... def __isub__(self, other: Union[float, int, "Array1d"]): ... def __imul__(self, other: Union[float, int, "Array1d"]): ... def __ipow__(self, other: Union[float, int, "Array1d"]): ... @overload def argmax(self, keepdims: Fal = False, axis: int = -1, out: Optional[_Array] = None) -> int: ... @overload def argmax(self, keepdims: Tru, axis: int = -1, out: Optional[_Array] = None) -> "Ints1d": ... def argmax(self, keepdims: bool = False, axis: int = -1, out: Optional[_Array] = None) -> Union[int, "Ints1d"]: ... @overload def mean(self, keepdims: Tru, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... @overload def mean(self, keepdims: Fal = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats1d"] = None) -> float: ... def mean(self, keepdims: bool = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats1d"] = None) -> Union["Floats1d", float]: ... class Floats1d(_Array1d, _Floats): """1-dimensional array of floats.""" T: "Floats1d" @classmethod def __get_validators__(cls): """Runtine validation for pydantic.""" yield lambda v: validate_array(v, ndim=1, dtype="f") def __iter__(self) -> Iterator[float]: ... @overload def __getitem__(self, key: _1_KeyScalar) -> float: ... @overload def __getitem__(self, key: _1_Key1d) -> "Floats1d": ... def __getitem__(self, key: _1_AllKeys) -> _F1_AllReturns: ... @overload def __setitem__(self, key: _1_KeyScalar, value: float) -> None: ... @overload def __setitem__(self, key: _1_Key1d, value: "Floats1d") -> None: ... def __setitem__(self, key: _1_AllKeys, _F1_AllReturns) -> None: ... @overload def cumsum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... @overload # Cumsum is unusual in this def cumsum(self, *, keepdims: Fal, axis: Optional[OneAx] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... def cumsum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... @overload def sum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... @overload def sum(self, *, keepdims: Fal, axis: Optional[OneAx] = None, out = None) -> float: ... def sum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Floats1d"] = None) -> _1F_ReduceResults: ... class Ints1d(_Array1d, _Ints): """1-dimensional array of ints.""" T: "Ints1d" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=1, dtype="i") def __iter__(self) -> Iterator[int]: ... @overload def __getitem__(self, key: _1_KeyScalar) -> int: ... @overload def __getitem__(self, key: _1_Key1d) -> "Ints1d": ... def __getitem__(self, key: _1_AllKeys) -> _I1_AllReturns: ... @overload def __setitem__(self, key: _1_KeyScalar, value: int) -> None: ... @overload def __setitem__(self, key: _1_Key1d, value: Union[int, "Ints1d"]) -> None: ... def __setitem__(self, key: _1_AllKeys, _I1_AllReturns) -> None: ... @overload def cumsum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Ints1d"] = None) -> "Ints1d": ... @overload def cumsum(self, *, keepdims: Fal = False, axis: Optional[OneAx] = None, out: Optional["Ints1d"] = None) -> "Ints1d": ... def cumsum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Ints1d"] = None) -> "Ints1d": ... @overload def sum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Ints1d"] = None) -> "Ints1d": ... @overload def sum(self, *, keepdims: Fal = False, axis: Optional[OneAx] = None, out = None) -> int: ... def sum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Ints1d"] = None) -> _1I_ReduceResults: ... class _Array2d(_Array): @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=2) @property def ndim(self) -> Literal[2]: ... @property def shape(self) -> Tuple[int, int]: ... def __iter__(self) -> Iterator[Array1d]: ... def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "Array2d": ... # These is actually a bit too strict: It's legal to say 'array2d + array3d' # That's kind of bad code though; it's better to write array3d + array2d. # We could relax this, but let's try the strict version. def __add__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... def __sub__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... def __mul__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... def __pow__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... def __matmul__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... # These are not too strict though: you can't do += with higher dimensional. def __iadd__(self, other: Union[float, int, Array1d, "Array2d"]): ... def __isub__(self, other: Union[float, int, Array1d, "Array2d"]): ... def __imul__(self, other: Union[float, int, Array1d, "Array2d"]): ... def __ipow__(self, other: Union[float, int, Array1d, "Array2d"]): ... @overload def argmax(self, keepdims: Fal = False, axis: int = -1, out: Optional[_Array] = None) -> Ints1d: ... @overload def argmax(self, keepdims: Tru, axis: int = -1, out: Optional[_Array] = None) -> "Ints2d": ... def argmax(self, keepdims: bool = False, axis: int = -1, out: Optional[_Array] = None) -> Union[Ints1d, "Ints2d"]: ... @overload def mean(self, keepdims: Fal = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats2d"] = None) -> Floats1d: ... @overload def mean(self, keepdims: Tru, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats2d"] = None) -> "Floats2d": ... def mean(self, keepdims: bool = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats2d"] = None) -> Union["Floats2d", Floats1d]: ... class Floats2d(_Array2d, _Floats): """2-dimensional array of floats""" T: "Floats2d" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=2, dtype="f") def __iter__(self) -> Iterator[Floats1d]: ... @overload def __getitem__(self, key: _2_KeyScalar) -> float: ... @overload def __getitem__(self, key: _2_Key1d) -> Floats1d: ... @overload def __getitem__(self, key: _2_Key2d) -> "Floats2d": ... def __getitem__(self, key: _2_AllKeys) -> _F2_AllReturns: ... @overload def __setitem__(self, key: _2_KeyScalar, value: float) -> None: ... @overload def __setitem__(self, key: _2_Key1d, value: Union[float, Floats1d]) -> None: ... @overload def __setitem__(self, key: _2_Key2d, value: _F2_AllReturns) -> None: ... def __setitem__(self, key: _2_AllKeys, value: _F2_AllReturns) -> None: ... @overload def sum(self, *, keepdims: Tru, axis: _2_AllAx = None, out: Optional["Floats2d"] = None) -> "Floats2d": ... @overload def sum(self, *, keepdims: Fal = False, axis: OneAx, out: Optional[Floats1d] = None) -> Floats1d: ... @overload def sum(self, *, keepdims: Fal = False, axis: TwoAx, out = None) -> float: ... def sum(self, *, keepdims: bool = False, axis: _2_AllAx = None, out: Union[None, "Floats1d", "Floats2d"] = None) -> _2F_ReduceResults: ... class Ints2d(_Array2d, _Ints): """2-dimensional array of ints.""" T: "Ints2d" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=2, dtype="i") def __iter__(self) -> Iterator[Ints1d]: ... @overload def __getitem__(self, key: _2_KeyScalar) -> int: ... @overload def __getitem__(self, key: _2_Key1d) -> Ints1d: ... @overload def __getitem__(self, key: _2_Key2d) -> "Ints2d": ... def __getitem__(self, key: _2_AllKeys) -> _I2_AllReturns: ... @overload def __setitem__(self, key: _2_KeyScalar, value: int) -> None: ... @overload def __setitem__(self, key: _2_Key1d, value: Ints1d) -> None: ... @overload def __setitem__(self, key: _2_Key2d, value: "Ints2d") -> None: ... def __setitem__(self, key: _2_AllKeys, value: _I2_AllReturns) -> None: ... @overload def sum(self, keepdims: Fal = False, axis: int = -1, out: Optional["Ints1d"] = None) -> Ints1d: ... @overload def sum(self, keepdims: Tru, axis: int = -1, out: Optional["Ints2d"] = None) -> "Ints2d": ... def sum(self, keepdims: bool = False, axis: int = -1, out: Optional[Union["Ints1d", "Ints2d"]] = None) -> Union["Ints2d", Ints1d]: ... class _Array3d(_Array): """3-dimensional array of floats""" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=3) @property def ndim(self) -> Literal[3]: ... @property def shape(self) -> Tuple[int, int, int]: ... def __iter__(self) -> Iterator[Array2d]: ... def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "Array3d": ... # These is actually a bit too strict: It's legal to say 'array2d + array3d' # That's kind of bad code though; it's better to write array3d + array2d. # We could relax this, but let's try the strict version. def __add__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __sub__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __mul__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __pow__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __matmul__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... # These are not too strict though: you can't do += with higher dimensional. def __iadd__(self, other: Union[float, int, Array1d, Array2d, "Array3d"]): ... def __isub__(self, other: Union[float, int, Array1d, Array2d, "Array3d"]): ... def __imul__(self, other: Union[float, int, Array1d, Array2d, "Array3d"]): ... def __ipow__(self, other: Union[float, int, Array1d, Array2d, "Array3d"]): ... @overload def argmax(self, keepdims: Fal = False, axis: int = -1, out: Optional[_Array] = None) -> Ints2d: ... @overload def argmax(self, keepdims: Tru, axis: int = -1, out: Optional[_Array] = None) -> "Ints3d": ... def argmax(self, keepdims: bool = False, axis: int = -1, out: Optional[_Array] = None) -> Union[Ints2d, "Ints3d"]: ... class Floats3d(_Array3d, _Floats): """3-dimensional array of floats""" T: "Floats3d" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=3, dtype="f") def __iter__(self) -> Iterator[Floats2d]: ... @overload def __getitem__(self, key: _3_KeyScalar) -> float: ... @overload def __getitem__(self, key: _3_Key1d) -> Floats1d: ... @overload def __getitem__(self, key: _3_Key2d) -> Floats2d: ... @overload def __getitem__(self, key: _3_Key3d) -> "Floats3d": ... def __getitem__(self, key: _3_AllKeys) -> _F3_AllReturns: ... @overload def __setitem__(self, key: _3_KeyScalar, value: float) -> None: ... @overload def __setitem__(self, key: _3_Key1d, value: Floats1d) -> None: ... @overload def __setitem__(self, key: _3_Key2d, value: Floats2d) -> None: ... @overload def __setitem__(self, key: _3_Key3d, value: "Floats3d") -> None: ... def __setitem__(self, key: _3_AllKeys, value: _F3_AllReturns) -> None: ... @overload def sum(self, *, keepdims: Tru, axis: _3_AllAx = None, out: Optional["Floats3d"] = None) -> "Floats3d": ... @overload def sum(self, *, keepdims: Fal, axis: OneAx, out: Optional[Floats2d] = None) -> Floats2d: ... @overload def sum(self, *, keepdims: Fal, axis: TwoAx, out: Optional[Floats1d] = None) -> Floats1d: ... @overload def sum(self, *, keepdims: Fal, axis: Optional[ThreeAx], out = None) -> float: ... def sum(self, *, keepdims: bool = False, axis: _3_AllAx = None, out: Union[None, Floats1d, Floats2d, "Floats3d"] = None) -> _3F_ReduceResults: ... class Ints3d(_Array3d, _Ints): """3-dimensional array of ints.""" T: "Ints3d" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=3, dtype="i") def __iter__(self) -> Iterator[Ints2d]: ... @overload def __getitem__(self, key: _3_KeyScalar) -> int: ... @overload def __getitem__(self, key: _3_Key1d) -> Ints1d: ... @overload def __getitem__(self, key: _3_Key2d) -> Ints2d: ... @overload def __getitem__(self, key: _3_Key3d) -> "Ints3d": ... def __getitem__(self, key: _3_AllKeys) -> _I3_AllReturns: ... @overload def __setitem__(self, key: _3_KeyScalar, value: int) -> None: ... @overload def __setitem__(self, key: _3_Key1d, value: Ints1d) -> None: ... @overload def __setitem__(self, key: _3_Key2d, value: Ints2d) -> None: ... @overload def __setitem__(self, key: _3_Key3d, value: "Ints3d") -> None: ... def __setitem__(self, key: _3_AllKeys, value: _I3_AllReturns) -> None: ... @overload def sum(self, *, keepdims: Tru, axis: _3_AllAx = None, out: Optional["Ints3d"] = None) -> "Ints3d": ... @overload def sum(self, *, keepdims: Fal, axis: OneAx, out: Optional[Ints2d] = None) -> Ints2d: ... @overload def sum(self, *, keepdims: Fal, axis: TwoAx, out: Optional[Ints1d] = None) -> Ints1d: ... @overload def sum(self, *, keepdims: Fal, axis: Optional[ThreeAx], out = None) -> int: ... def sum(self, *, keepdims: bool = False, axis: _3_AllAx = None, out: Union[None, Ints1d, Ints2d, "Ints3d"] = None) -> _3I_ReduceResults: ... class _Array4d(_Array): """4-dimensional array.""" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=4) @property def ndim(self) -> Literal[4]: ... @property def shape(self) -> Tuple[int, int, int, int]: ... def __iter__(self) -> Iterator[Array3d]: ... def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "_Array4d": ... # These is actually a bit too strict: It's legal to say 'array4d + array5d' # That's kind of bad code though; it's better to write array5d + array4d. # We could relax this, but let's try the strict version. def __add__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... def __sub__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... def __mul__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... def __pow__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... def __matmul__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... # These are not too strict though: you can't do += with higher dimensional. def __iadd__(self, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]): ... def __isub__(self, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]): ... def __imul__(self, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]): ... def __ipow__(self, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]): ... class Floats4d(_Array4d, _Floats): """4-dimensional array of floats.""" T: "Floats4d" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=4, dtype="f") def __iter__(self) -> Iterator[Floats3d]: ... @overload def __getitem__(self, key: _4_KeyScalar) -> float: ... @overload def __getitem__(self, key: _4_Key1d) -> Floats1d: ... @overload def __getitem__(self, key: _4_Key2d) -> Floats2d: ... @overload def __getitem__(self, key: _4_Key3d) -> Floats3d: ... @overload def __getitem__(self, key: _4_Key4d) -> "Floats4d": ... def __getitem__(self, key: _4_AllKeys) -> _F4_AllReturns: ... @overload def __setitem__(self, key: _4_KeyScalar, value: float) -> None: ... @overload def __setitem__(self, key: _4_Key1d, value: Floats1d) -> None: ... @overload def __setitem__(self, key: _4_Key2d, value: Floats2d) -> None: ... @overload def __setitem__(self, key: _4_Key3d, value: Floats3d) -> None: ... @overload def __setitem__(self, key: _4_Key4d, value: "Floats4d") -> None: ... def __setitem__(self, key: _4_AllKeys, value: _F4_AllReturns) -> None: ... @overload def sum(self, *, keepdims: Tru, axis: _4_AllAx = None, out: Optional["Floats4d"] = None) -> "Floats4d": ... @overload def sum(self, *, keepdims: Fal = False, axis: OneAx, out: Optional[Floats3d] = None) -> Floats3d: ... @overload def sum(self, *, keepdims: Fal = False, axis: TwoAx, out: Optional[Floats2d] = None) -> Floats2d: ... @overload def sum(self, *, keepdims: Fal = False, axis: ThreeAx, out: Optional[Floats1d] = None) -> Floats1d: ... @overload def sum(self, *, keepdims: Fal = False, axis: Optional[FourAx], out = None) -> float: ... def sum(self, *, keepdims: bool = False, axis: _4_AllAx = None, out: Union[None, Floats1d, Floats2d, Floats3d, "Floats4d"] = None) -> _4F_ReduceResults: ... class Ints4d(_Array4d, _Ints): """4-dimensional array of ints.""" T: "Ints4d" @classmethod def __get_validators__(cls): """Runtime validation for pydantic.""" yield lambda v: validate_array(v, ndim=4, dtype="i") def __iter__(self) -> Iterator[Ints3d]: ... # def __getitem__(self, key: int) -> Ints3d: ... @overload def sum(self, *, keepdims: Tru, axis: _4_AllAx = None, out: Optional["Ints4d"] = None) -> "Ints4d": ... @overload def sum(self, *, keepdims: Fal = False, axis: OneAx, out: Optional[Ints3d] = None) -> Ints3d: ... @overload def sum(self, *, keepdims: Fal = False, axis: TwoAx, out: Optional[Ints2d] = None) -> Ints2d: ... @overload def sum(self, *, keepdims: Fal = False, axis: ThreeAx, out: Optional[Ints1d] = None) -> Ints1d: ... @overload def sum(self, *, keepdims: Fal = False, axis: Optional[FourAx] = None, out = None) -> int: ... def sum(self, *, keepdims: bool = False, axis: _4_AllAx = None, out: Optional[Union[Ints1d, Ints2d, Ints3d, "Ints4d"]] = None) -> _4I_ReduceResults: ... _DIn = TypeVar("_DIn") class Decorator(Protocol): """Protocol to mark a function as returning its child with identical signature.""" def __call__(self, name: str) -> Callable[[_DIn], _DIn]: ... # fmt: on class Generator(Iterator): """Custom generator type. Used to annotate function arguments that accept generators so they can be validated by pydantic (which doesn't support iterators/iterables otherwise). """ @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): if not hasattr(v, "__iter__") and not hasattr(v, "__next__"): raise TypeError("not a valid iterator") return v @dataclass class SizedGenerator: """A generator that has a __len__ and can repeatedly call the generator function. """ get_items: Callable[[], Generator] length: int def __len__(self): return self.length def __iter__(self): yield from self.get_items() @dataclass class Padded: """A batch of padded sequences, sorted by decreasing length. The data array is of shape (step, batch, ...). The auxiliary array size_at_t indicates the length of the batch at each timestep, so you can do data[:, :size_at_t[t]] to shrink the batch. The lengths array indicates the length of each row b, and the indices indicates the original ordering. """ data: Floats3d size_at_t: Ints1d lengths: Ints1d indices: Ints1d def copy(self): return Padded( self.data.copy(), self.size_at_t.copy(), self.lengths.copy(), self.indices.copy() ) def __len__(self) -> int: return self.lengths.shape[0] def __getitem__(self, index: Union[int, slice, Ints1d]) -> "Padded": if isinstance(index, int): # Slice to keep the dimensionality return Padded( self.data[:, index : index + 1], self.lengths[index : index + 1], self.lengths[index : index + 1], self.indices[index : index + 1], ) elif isinstance(index, slice): return Padded( self.data[:, index], self.lengths[index], self.lengths[index], self.indices[index], ) else: # If we get a sequence of indices, we need to be careful that # we maintain the length-sorting, while also keeping the mapping # back to the original order correct. sorted_index = list(sorted(index)) return Padded( self.data[sorted_index], self.size_at_t[sorted_index], self.lengths[sorted_index], self.indices[index], # Use original, to maintain order. ) @dataclass class Ragged: """A batch of concatenated sequences, that vary in the size of their first dimension. Ragged allows variable-length sequence data to be contiguous in memory, without padding. Indexing into Ragged is just like indexing into the *lengths* array, except it returns a Ragged object with the accompanying sequence data. For instance, you can write ragged[1:4] to get a Ragged object with sequences 1, 2 and 3. """ data: Array2d lengths: Ints1d data_shape: Tuple[int, ...] starts_ends: Optional[Ints1d] = None def __init__(self, data: _Array, lengths: Ints1d): self.lengths = lengths # Frustratingly, the -1 dimension doesn't work with 0 size... if data.size: self.data = cast(Array2d, data.reshape((data.shape[0], -1))) else: self.data = cast(Array2d, data.reshape((0, 0))) self.data_shape = (-1,) + data.shape[1:] @property def dataXd(self) -> ArrayXd: if self.data.size: reshaped = self.data.reshape(self.data_shape) else: reshaped = self.data.reshape((self.data.shape[0],) + self.data_shape[1:]) return cast(ArrayXd, reshaped) def __len__(self) -> int: return self.lengths.shape[0] def __getitem__(self, index: Union[int, slice, Array1d]) -> "Ragged": if isinstance(index, tuple): raise IndexError("Ragged arrays do not support 2d indexing.") starts = self._get_starts() ends = self._get_ends() if isinstance(index, int): s = starts[index] e = ends[index] return Ragged(self.data[s:e], self.lengths[index : index + 1]) elif isinstance(index, slice): lengths = self.lengths[index] if len(lengths) == 0: return Ragged(self.data[0:0].reshape(self.data_shape), lengths) start = starts[index][0] if index.start >= 1 else 0 end = ends[index][-1] return Ragged(self.data[start:end].reshape(self.data_shape), lengths) else: # There must be a way to do this "properly" :(. Sigh, hate numpy. xp = get_array_module(self.data) data = xp.vstack([self[int(i)].data for i in index]) return Ragged(data.reshape(self.data_shape), self.lengths[index]) def _get_starts_ends(self) -> Ints1d: if self.starts_ends is None: xp = get_array_module(self.lengths) self.starts_ends = xp.empty(self.lengths.size + 1, dtype="i") self.starts_ends[0] = 0 self.lengths.cumsum(out=self.starts_ends[1:]) return self.starts_ends def _get_starts(self) -> Ints1d: return self._get_starts_ends()[:-1] def _get_ends(self) -> Ints1d: return self._get_starts_ends()[1:] _P = TypeVar("_P", bound=Sequence) @dataclass class Pairs(Generic[_P]): """Dataclass for pairs of sequences that allows indexing into the sequences while keeping them aligned. """ one: _P two: _P def __getitem__(self, index) -> "Pairs[_P]": return Pairs(self.one[index], self.two[index]) def __len__(self) -> int: return len(self.one) @dataclass class ArgsKwargs: """A tuple of (args, kwargs) that can be spread into some function f: f(*args, **kwargs) """ args: Tuple[Any, ...] kwargs: Dict[str, Any] @classmethod def from_items(cls, items: Sequence[Tuple[Union[int, str], Any]]) -> "ArgsKwargs": """Create an ArgsKwargs object from a sequence of (key, value) tuples, such as produced by argskwargs.items(). Each key should be either a string or an integer. Items with int keys are added to the args list, and items with string keys are added to the kwargs list. The args list is determined by sequence order, not the value of the integer. """ args = [] kwargs = {} for key, value in items: if isinstance(key, int): args.append(value) else: kwargs[key] = value return cls(args=tuple(args), kwargs=kwargs) def keys(self) -> Iterable[Union[int, str]]: """Yield indices from self.args, followed by keys from self.kwargs.""" yield from range(len(self.args)) yield from self.kwargs.keys() def values(self) -> Iterable[Any]: """Yield elements of from self.args, followed by values from self.kwargs.""" yield from self.args yield from self.kwargs.values() def items(self) -> Iterable[Tuple[Union[int, str], Any]]: """Yield enumerate(self.args), followed by self.kwargs.items()""" yield from enumerate(self.args) yield from self.kwargs.items() @dataclass class Unserializable: """Wrap a value to prevent it from being serialized by msgpack.""" obj: Any def validate_array(obj, ndim=None, dtype=None): """Runtime validator for pydantic to validate array types.""" xp = get_array_module(obj) if not isinstance(obj, xp.ndarray): raise TypeError("not a valid numpy or cupy array") errors = [] if ndim is not None and obj.ndim != ndim: errors.append(f"wrong array dimensions (expected {ndim}, got {obj.ndim})") if dtype is not None: dtype_mapping = {"f": ["float32"], "i": ["int32", "int64", "uint32", "uint64"]} expected_types = dtype_mapping.get(dtype, []) if obj.dtype not in expected_types: expected = "/".join(expected_types) err = f"wrong array data type (expected {expected}, got {obj.dtype})" errors.append(err) if errors: raise ValueError(", ".join(errors)) return obj
41.378788
321
0.627926
from typing import Union, Tuple, Sized, Container, Any, TypeVar, Callable from typing import Iterable, Iterator, Sequence, Dict, Generic, cast from typing import Optional, List, overload from dataclasses import dataclass import numpy import sys try: import cupy get_array_module = cupy.get_array_module except ImportError: get_array_module = lambda obj: numpy if sys.version_info < (3, 8): from typing_extensions import Protocol, Literal else: from typing import Protocol, Literal XY_YZ_OutT = TypeVar("XY_YZ_OutT") XY_XY_OutT = TypeVar("XY_XY_OutT") DeviceTypes = Literal["cpu", "gpu", "tpu"] Batchable = Union["Pairs", "Ragged", "Padded", "ArrayXd", List, Tuple] Xp = Union["numpy", "cupy"] Shape = Tuple[int, ...] DTypes = Literal["f", "i", "float16", "float32", "float64", "int32", "int64", "uint32", "uint64"] DTypesFloat = Literal["f", "float32", "float16", "float64"] DTypesInt = Literal["i", "int32", "int64", "uint32", "uint64"] Array1d = Union["Floats1d", "Ints1d"] Array2d = Union["Floats2d", "Ints2d"] Array3d = Union["Floats3d", "Ints3d"] Array4d = Union["Floats4d", "Ints4d"] FloatsXd = Union["Floats1d", "Floats2d", "Floats3d", "Floats4d"] IntsXd = Union["Ints1d", "Ints2d", "Ints3d", "Ints4d"] ArrayXd = Union[FloatsXd, IntsXd] List1d = Union[List["Floats1d"], List["Ints1d"]] List2d = Union[List["Floats2d"], List["Ints2d"]] List3d = Union[List["Floats3d"], List["Ints3d"]] List4d = Union[List["Floats4d"], List["Ints4d"]] ListXd = Union[List["FloatsXd"], List["IntsXd"]] ArrayT = TypeVar("ArrayT") SelfT = TypeVar("SelfT") Array1dT = TypeVar("Array1dT", bound="Array1d") Slicish = Union[slice, List[int], "ArrayXd"] _1_KeyScalar = int _1_Key1d = Slicish _1_AllKeys = Union[_1_KeyScalar, _1_Key1d] _F1_AllReturns = Union[float, "Floats1d"] _I1_AllReturns = Union[int, "Ints1d"] _2_KeyScalar = Tuple[int, int] _2_Key1d = Union[int, Tuple[Slicish, int], Tuple[int, Slicish]] _2_Key2d = Union[Tuple[Slicish, Slicish], Slicish] _2_AllKeys = Union[_2_KeyScalar, _2_Key1d, _2_Key2d] _F2_AllReturns = Union[float, "Floats1d", "Floats2d"] _I2_AllReturns = Union[int, "Ints1d", "Ints2d"] _3_KeyScalar = Tuple[int, int, int] _3_Key1d = Union[Tuple[int, int], Tuple[int, int, Slicish], Tuple[int, Slicish, int], Tuple[Slicish, int, int]] _3_Key2d = Union[int, Tuple[int, Slicish], Tuple[Slicish, int], Tuple[int, Slicish, Slicish], Tuple[Slicish, int, Slicish], Tuple[Slicish, Slicish, int]] _3_Key3d = Union[Slicish, Tuple[Slicish, Slicish], Tuple[Slicish, Slicish, Slicish]] _3_AllKeys = Union[_3_KeyScalar, _3_Key1d, _3_Key2d, _3_Key3d] _F3_AllReturns = Union[float, "Floats1d", "Floats2d", "Floats3d"] _I3_AllReturns = Union[int, "Ints1d", "Ints2d", "Ints3d"] _4_KeyScalar = Tuple[int, int, int, int] _4_Key1d = Union[Tuple[int, int, int], Tuple[int, int, int, Slicish], Tuple[int, int, Slicish, int], Tuple[int, Slicish, int, int], Tuple[Slicish, int, int, int]] _4_Key2d = Union[Tuple[int, int], Tuple[int, int, Slicish], Tuple[int, Slicish, int], Tuple[Slicish, int, int], Tuple[int, int, Slicish, Slicish], Tuple[int, Slicish, int, Slicish], Tuple[int, Slicish, Slicish, int], Tuple[Slicish, int, int, Slicish], Tuple[Slicish, int, Slicish, int], Tuple[Slicish, Slicish, int, int]] _4_Key3d = Union[int, Tuple[int, Slicish], Tuple[Slicish, int], Tuple[int, Slicish, Slicish], Tuple[Slicish, int, Slicish], Tuple[Slicish, Slicish, int], Tuple[int, Slicish, Slicish, Slicish], Tuple[Slicish, int, Slicish, Slicish], Tuple[Slicish, Slicish, int, Slicish], Tuple[Slicish, Slicish, Slicish, int]] _4_Key4d = Union[Slicish, Tuple[Slicish, Slicish], Tuple[Slicish, Slicish, Slicish], Tuple[Slicish, Slicish, Slicish, Slicish]] _4_AllKeys = Union[_4_KeyScalar, _4_Key1d, _4_Key2d, _4_Key3d, _4_Key4d] _F4_AllReturns = Union[float, "Floats1d", "Floats2d", "Floats3d", "Floats4d"] _I4_AllReturns = Union[int, "Ints1d", "Ints2d", "Ints3d", "Ints4d"] Tru = Literal[True] Fal = Literal[False] OneAx = Union[int, Tuple[int]] TwoAx = Tuple[int, int] ThreeAx = Tuple[int, int, int] FourAx = Tuple[int, int, int, int] _1_AllAx = Optional[OneAx] _2_AllAx = Union[Optional[TwoAx], OneAx] _3_AllAx = Union[Optional[ThreeAx], TwoAx, OneAx] _4_AllAx = Union[Optional[FourAx], ThreeAx, TwoAx, OneAx] _1F_ReduceResults = Union[float, "Floats1d"] _2F_ReduceResults = Union[float, "Floats1d", "Floats2d"] _3F_ReduceResults = Union[float, "Floats1d", "Floats2d", "Floats3d"] _4F_ReduceResults = Union[float, "Floats1d", "Floats2d", "Floats3d", "Floats4d"] _1I_ReduceResults = Union[int, "Ints1d"] _2I_ReduceResults = Union[int, "Ints1d", "Ints2d"] _3I_ReduceResults = Union[int, "Ints1d", "Ints2d", "Ints3d"] _4I_ReduceResults = Union[int, "Ints1d", "Ints2d", "Ints3d", "Ints4d"] class _Array(Sized, Container): @classmethod def __get_validators__(cls): yield lambda v: validate_array(v) @property def dtype(self) -> DTypes: ... @property def data(self) -> memoryview: ... @property def flags(self) -> Any: ... @property def size(self) -> int: ... @property def itemsize(self) -> int: ... @property def nbytes(self) -> int: ... @property def ndim(self) -> int: ... @property def shape(self) -> Shape: ... @property def strides(self) -> Tuple[int, ...]: ... def astype(self: ArrayT, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> ArrayT: ... def copy(self: ArrayT, order: str = ...) -> ArrayT: ... def fill(self, value: Any) -> None: ... def reshape(self: ArrayT, shape: Shape, *, order: str = ...) -> ArrayT: ... def transpose(self: ArrayT, axes: Shape) -> ArrayT: ... def flatten(self, order: str = ...): ... def ravel(self, order: str = ...): ... def squeeze(self, axis: Union[int, Shape] = ...): ... def __len__(self) -> int: ... def __setitem__(self, key, value): ... def __iter__(self) -> Iterator[Any]: ... def __contains__(self, key) -> bool: ... def __index__(self) -> int: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __complex__(self) -> complex: ... def __bool__(self) -> bool: ... def __bytes__(self) -> bytes: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... def __copy__(self, order: str = ...): ... def __deepcopy__(self, memo: dict) -> ArrayT: ... def __lt__(self, other): ... def __le__(self, other): ... def __eq__(self, other): ... def __ne__(self, other): ... def __gt__(self, other): ... def __ge__(self, other): ... def __add__(self, other): ... def __radd__(self, other): ... def __iadd__(self, other): ... def __sub__(self, other): ... def __rsub__(self, other): ... def __isub__(self, other): ... def __mul__(self, other): ... def __rmul__(self, other): ... def __imul__(self, other): ... def __truediv__(self, other): ... def __rtruediv__(self, other): ... def __itruediv__(self, other): ... def __floordiv__(self, other): ... def __rfloordiv__(self, other): ... def __ifloordiv__(self, other): ... def __mod__(self, other): ... def __rmod__(self, other): ... def __imod__(self, other): ... def __divmod__(self, other): ... def __rdivmod__(self, other): ... def __pow__(self, other): ... def __rpow__(self, other): ... def __ipow__(self, other): ... def __lshift__(self, other): ... def __rlshift__(self, other): ... def __ilshift__(self, other): ... def __rshift__(self, other): ... def __rrshift__(self, other): ... def __irshift__(self, other): ... def __and__(self, other): ... def __rand__(self, other): ... def __iand__(self, other): ... def __xor__(self, other): ... def __rxor__(self, other): ... def __ixor__(self, other): ... def __or__(self, other): ... def __ror__(self, other): ... def __ior__(self, other): ... def __matmul__(self, other): ... def __rmatmul__(self, other): ... def __neg__(self: ArrayT) -> ArrayT: ... def __pos__(self: ArrayT) -> ArrayT: ... def __abs__(self: ArrayT) -> ArrayT: ... def __invert__(self: ArrayT) -> ArrayT: ... def get(self: ArrayT) -> ArrayT: ... def all(self, axis: int = -1, out: Optional[ArrayT] = None, keepdims: bool = False) -> ArrayT: ... def any(self, axis: int = -1, out: Optional[ArrayT] = None, keepdims: bool = False) -> ArrayT: ... def argmin(self, axis: int = -1, out: Optional[ArrayT] = None) -> ArrayT: ... def clip(self, a_min: Any, a_max: Any, out: Optional[ArrayT]) -> ArrayT: ... def max(self, axis: int = -1, out: Optional[ArrayT] = None) -> ArrayT: ... def min(self, axis: int = -1, out: Optional[ArrayT] = None) -> ArrayT: ... def nonzero(self) -> ArrayT: ... def prod(self, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional[ArrayT] = None, keepdims: bool = False) -> ArrayT: ... def round(self, decimals: int = 0, out: Optional[ArrayT] = None) -> ArrayT: ... def tobytes(self, order: str = "C") -> bytes: ... def tolist(self) -> List[Any]: ... def var(self: SelfT, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional[ArrayT] = None, ddof: int = 0, keepdims: bool = False) -> SelfT: ... class _Floats(_Array): @property def dtype(self) -> DTypesFloat: ... def fill(self, value: float) -> None: ... def reshape(self, shape: Shape, *, order: str = ...) -> "_Floats": ... class _Ints(_Array): @property def dtype(self) -> DTypesInt: ... def fill(self, value: int) -> None: ... def reshape(self, shape: Shape, *, order: str = ...) -> "_Ints": ... class _Array1d(_Array): @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=1) @property def ndim(self) -> Literal[1]: ... @property def shape(self) -> Tuple[int]: ... def __iter__(self) -> Iterator[Union[float, int]]: ... def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "_Array1d": ... def flatten(self: SelfT, order: str = ...) -> SelfT: ... def ravel(self: SelfT, order: str = ...) -> SelfT: ... # That's kind of bad code though; it's better to write array2d + array1d. # We could relax this, but let's try the strict version. def __add__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __sub__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __mul__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __pow__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __matmul__(self: SelfT, other: Union[float, int, "Array1d"]) -> SelfT: ... def __iadd__(self, other: Union[float, int, "Array1d"]): ... def __isub__(self, other: Union[float, int, "Array1d"]): ... def __imul__(self, other: Union[float, int, "Array1d"]): ... def __ipow__(self, other: Union[float, int, "Array1d"]): ... @overload def argmax(self, keepdims: Fal = False, axis: int = -1, out: Optional[_Array] = None) -> int: ... @overload def argmax(self, keepdims: Tru, axis: int = -1, out: Optional[_Array] = None) -> "Ints1d": ... def argmax(self, keepdims: bool = False, axis: int = -1, out: Optional[_Array] = None) -> Union[int, "Ints1d"]: ... @overload def mean(self, keepdims: Tru, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... @overload def mean(self, keepdims: Fal = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats1d"] = None) -> float: ... def mean(self, keepdims: bool = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats1d"] = None) -> Union["Floats1d", float]: ... class Floats1d(_Array1d, _Floats): T: "Floats1d" @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=1, dtype="f") def __iter__(self) -> Iterator[float]: ... @overload def __getitem__(self, key: _1_KeyScalar) -> float: ... @overload def __getitem__(self, key: _1_Key1d) -> "Floats1d": ... def __getitem__(self, key: _1_AllKeys) -> _F1_AllReturns: ... @overload def __setitem__(self, key: _1_KeyScalar, value: float) -> None: ... @overload def __setitem__(self, key: _1_Key1d, value: "Floats1d") -> None: ... def __setitem__(self, key: _1_AllKeys, _F1_AllReturns) -> None: ... @overload def cumsum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... @overload # Cumsum is unusual in this def cumsum(self, *, keepdims: Fal, axis: Optional[OneAx] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... def cumsum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... @overload def sum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Floats1d"] = None) -> "Floats1d": ... @overload def sum(self, *, keepdims: Fal, axis: Optional[OneAx] = None, out = None) -> float: ... def sum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Floats1d"] = None) -> _1F_ReduceResults: ... class Ints1d(_Array1d, _Ints): T: "Ints1d" @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=1, dtype="i") def __iter__(self) -> Iterator[int]: ... @overload def __getitem__(self, key: _1_KeyScalar) -> int: ... @overload def __getitem__(self, key: _1_Key1d) -> "Ints1d": ... def __getitem__(self, key: _1_AllKeys) -> _I1_AllReturns: ... @overload def __setitem__(self, key: _1_KeyScalar, value: int) -> None: ... @overload def __setitem__(self, key: _1_Key1d, value: Union[int, "Ints1d"]) -> None: ... def __setitem__(self, key: _1_AllKeys, _I1_AllReturns) -> None: ... @overload def cumsum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Ints1d"] = None) -> "Ints1d": ... @overload def cumsum(self, *, keepdims: Fal = False, axis: Optional[OneAx] = None, out: Optional["Ints1d"] = None) -> "Ints1d": ... def cumsum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Ints1d"] = None) -> "Ints1d": ... @overload def sum(self, *, keepdims: Tru, axis: Optional[OneAx] = None, out: Optional["Ints1d"] = None) -> "Ints1d": ... @overload def sum(self, *, keepdims: Fal = False, axis: Optional[OneAx] = None, out = None) -> int: ... def sum(self, *, keepdims: bool = False, axis: _1_AllAx = None, out: Optional["Ints1d"] = None) -> _1I_ReduceResults: ... class _Array2d(_Array): @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=2) @property def ndim(self) -> Literal[2]: ... @property def shape(self) -> Tuple[int, int]: ... def __iter__(self) -> Iterator[Array1d]: ... def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "Array2d": ... # These is actually a bit too strict: It's legal to say 'array2d + array3d' def __add__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... def __sub__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... def __mul__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... def __pow__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... def __matmul__(self: ArrayT, other: Union[float, int, Array1d, "Array2d"]) -> ArrayT: ... # These are not too strict though: you can't do += with higher dimensional. def __iadd__(self, other: Union[float, int, Array1d, "Array2d"]): ... def __isub__(self, other: Union[float, int, Array1d, "Array2d"]): ... def __imul__(self, other: Union[float, int, Array1d, "Array2d"]): ... def __ipow__(self, other: Union[float, int, Array1d, "Array2d"]): ... @overload def argmax(self, keepdims: Fal = False, axis: int = -1, out: Optional[_Array] = None) -> Ints1d: ... @overload def argmax(self, keepdims: Tru, axis: int = -1, out: Optional[_Array] = None) -> "Ints2d": ... def argmax(self, keepdims: bool = False, axis: int = -1, out: Optional[_Array] = None) -> Union[Ints1d, "Ints2d"]: ... @overload def mean(self, keepdims: Fal = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats2d"] = None) -> Floats1d: ... @overload def mean(self, keepdims: Tru, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats2d"] = None) -> "Floats2d": ... def mean(self, keepdims: bool = False, axis: int = -1, dtype: Optional[DTypes] = None, out: Optional["Floats2d"] = None) -> Union["Floats2d", Floats1d]: ... class Floats2d(_Array2d, _Floats): T: "Floats2d" @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=2, dtype="f") def __iter__(self) -> Iterator[Floats1d]: ... @overload def __getitem__(self, key: _2_KeyScalar) -> float: ... @overload def __getitem__(self, key: _2_Key1d) -> Floats1d: ... @overload def __getitem__(self, key: _2_Key2d) -> "Floats2d": ... def __getitem__(self, key: _2_AllKeys) -> _F2_AllReturns: ... @overload def __setitem__(self, key: _2_KeyScalar, value: float) -> None: ... @overload def __setitem__(self, key: _2_Key1d, value: Union[float, Floats1d]) -> None: ... @overload def __setitem__(self, key: _2_Key2d, value: _F2_AllReturns) -> None: ... def __setitem__(self, key: _2_AllKeys, value: _F2_AllReturns) -> None: ... @overload def sum(self, *, keepdims: Tru, axis: _2_AllAx = None, out: Optional["Floats2d"] = None) -> "Floats2d": ... @overload def sum(self, *, keepdims: Fal = False, axis: OneAx, out: Optional[Floats1d] = None) -> Floats1d: ... @overload def sum(self, *, keepdims: Fal = False, axis: TwoAx, out = None) -> float: ... def sum(self, *, keepdims: bool = False, axis: _2_AllAx = None, out: Union[None, "Floats1d", "Floats2d"] = None) -> _2F_ReduceResults: ... class Ints2d(_Array2d, _Ints): T: "Ints2d" @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=2, dtype="i") def __iter__(self) -> Iterator[Ints1d]: ... @overload def __getitem__(self, key: _2_KeyScalar) -> int: ... @overload def __getitem__(self, key: _2_Key1d) -> Ints1d: ... @overload def __getitem__(self, key: _2_Key2d) -> "Ints2d": ... def __getitem__(self, key: _2_AllKeys) -> _I2_AllReturns: ... @overload def __setitem__(self, key: _2_KeyScalar, value: int) -> None: ... @overload def __setitem__(self, key: _2_Key1d, value: Ints1d) -> None: ... @overload def __setitem__(self, key: _2_Key2d, value: "Ints2d") -> None: ... def __setitem__(self, key: _2_AllKeys, value: _I2_AllReturns) -> None: ... @overload def sum(self, keepdims: Fal = False, axis: int = -1, out: Optional["Ints1d"] = None) -> Ints1d: ... @overload def sum(self, keepdims: Tru, axis: int = -1, out: Optional["Ints2d"] = None) -> "Ints2d": ... def sum(self, keepdims: bool = False, axis: int = -1, out: Optional[Union["Ints1d", "Ints2d"]] = None) -> Union["Ints2d", Ints1d]: ... class _Array3d(_Array): @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=3) @property def ndim(self) -> Literal[3]: ... @property def shape(self) -> Tuple[int, int, int]: ... def __iter__(self) -> Iterator[Array2d]: ... def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "Array3d": ... # That's kind of bad code though; it's better to write array3d + array2d. # We could relax this, but let's try the strict version. def __add__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __sub__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __mul__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __pow__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __matmul__(self: SelfT, other: Union[float, int, Array1d, Array2d, "Array3d"]) -> SelfT: ... def __iadd__(self, other: Union[float, int, Array1d, Array2d, "Array3d"]): ... def __isub__(self, other: Union[float, int, Array1d, Array2d, "Array3d"]): ... def __imul__(self, other: Union[float, int, Array1d, Array2d, "Array3d"]): ... def __ipow__(self, other: Union[float, int, Array1d, Array2d, "Array3d"]): ... @overload def argmax(self, keepdims: Fal = False, axis: int = -1, out: Optional[_Array] = None) -> Ints2d: ... @overload def argmax(self, keepdims: Tru, axis: int = -1, out: Optional[_Array] = None) -> "Ints3d": ... def argmax(self, keepdims: bool = False, axis: int = -1, out: Optional[_Array] = None) -> Union[Ints2d, "Ints3d"]: ... class Floats3d(_Array3d, _Floats): T: "Floats3d" @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=3, dtype="f") def __iter__(self) -> Iterator[Floats2d]: ... @overload def __getitem__(self, key: _3_KeyScalar) -> float: ... @overload def __getitem__(self, key: _3_Key1d) -> Floats1d: ... @overload def __getitem__(self, key: _3_Key2d) -> Floats2d: ... @overload def __getitem__(self, key: _3_Key3d) -> "Floats3d": ... def __getitem__(self, key: _3_AllKeys) -> _F3_AllReturns: ... @overload def __setitem__(self, key: _3_KeyScalar, value: float) -> None: ... @overload def __setitem__(self, key: _3_Key1d, value: Floats1d) -> None: ... @overload def __setitem__(self, key: _3_Key2d, value: Floats2d) -> None: ... @overload def __setitem__(self, key: _3_Key3d, value: "Floats3d") -> None: ... def __setitem__(self, key: _3_AllKeys, value: _F3_AllReturns) -> None: ... @overload def sum(self, *, keepdims: Tru, axis: _3_AllAx = None, out: Optional["Floats3d"] = None) -> "Floats3d": ... @overload def sum(self, *, keepdims: Fal, axis: OneAx, out: Optional[Floats2d] = None) -> Floats2d: ... @overload def sum(self, *, keepdims: Fal, axis: TwoAx, out: Optional[Floats1d] = None) -> Floats1d: ... @overload def sum(self, *, keepdims: Fal, axis: Optional[ThreeAx], out = None) -> float: ... def sum(self, *, keepdims: bool = False, axis: _3_AllAx = None, out: Union[None, Floats1d, Floats2d, "Floats3d"] = None) -> _3F_ReduceResults: ... class Ints3d(_Array3d, _Ints): T: "Ints3d" @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=3, dtype="i") def __iter__(self) -> Iterator[Ints2d]: ... @overload def __getitem__(self, key: _3_KeyScalar) -> int: ... @overload def __getitem__(self, key: _3_Key1d) -> Ints1d: ... @overload def __getitem__(self, key: _3_Key2d) -> Ints2d: ... @overload def __getitem__(self, key: _3_Key3d) -> "Ints3d": ... def __getitem__(self, key: _3_AllKeys) -> _I3_AllReturns: ... @overload def __setitem__(self, key: _3_KeyScalar, value: int) -> None: ... @overload def __setitem__(self, key: _3_Key1d, value: Ints1d) -> None: ... @overload def __setitem__(self, key: _3_Key2d, value: Ints2d) -> None: ... @overload def __setitem__(self, key: _3_Key3d, value: "Ints3d") -> None: ... def __setitem__(self, key: _3_AllKeys, value: _I3_AllReturns) -> None: ... @overload def sum(self, *, keepdims: Tru, axis: _3_AllAx = None, out: Optional["Ints3d"] = None) -> "Ints3d": ... @overload def sum(self, *, keepdims: Fal, axis: OneAx, out: Optional[Ints2d] = None) -> Ints2d: ... @overload def sum(self, *, keepdims: Fal, axis: TwoAx, out: Optional[Ints1d] = None) -> Ints1d: ... @overload def sum(self, *, keepdims: Fal, axis: Optional[ThreeAx], out = None) -> int: ... def sum(self, *, keepdims: bool = False, axis: _3_AllAx = None, out: Union[None, Ints1d, Ints2d, "Ints3d"] = None) -> _3I_ReduceResults: ... class _Array4d(_Array): @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=4) @property def ndim(self) -> Literal[4]: ... @property def shape(self) -> Tuple[int, int, int, int]: ... def __iter__(self) -> Iterator[Array3d]: ... def astype(self, dtype: DTypes, order: str = ..., casting: str = ..., subok: bool = ..., copy: bool = ...) -> "_Array4d": ... # These is actually a bit too strict: It's legal to say 'array4d + array5d' def __add__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... def __sub__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... def __mul__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... def __pow__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... def __matmul__(self: SelfT, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]) -> SelfT: ... # These are not too strict though: you can't do += with higher dimensional. def __iadd__(self, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]): ... def __isub__(self, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]): ... def __imul__(self, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]): ... def __ipow__(self, other: Union[float, int, Array1d, Array2d, Array3d, "Array4d"]): ... class Floats4d(_Array4d, _Floats): T: "Floats4d" @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=4, dtype="f") def __iter__(self) -> Iterator[Floats3d]: ... @overload def __getitem__(self, key: _4_KeyScalar) -> float: ... @overload def __getitem__(self, key: _4_Key1d) -> Floats1d: ... @overload def __getitem__(self, key: _4_Key2d) -> Floats2d: ... @overload def __getitem__(self, key: _4_Key3d) -> Floats3d: ... @overload def __getitem__(self, key: _4_Key4d) -> "Floats4d": ... def __getitem__(self, key: _4_AllKeys) -> _F4_AllReturns: ... @overload def __setitem__(self, key: _4_KeyScalar, value: float) -> None: ... @overload def __setitem__(self, key: _4_Key1d, value: Floats1d) -> None: ... @overload def __setitem__(self, key: _4_Key2d, value: Floats2d) -> None: ... @overload def __setitem__(self, key: _4_Key3d, value: Floats3d) -> None: ... @overload def __setitem__(self, key: _4_Key4d, value: "Floats4d") -> None: ... def __setitem__(self, key: _4_AllKeys, value: _F4_AllReturns) -> None: ... @overload def sum(self, *, keepdims: Tru, axis: _4_AllAx = None, out: Optional["Floats4d"] = None) -> "Floats4d": ... @overload def sum(self, *, keepdims: Fal = False, axis: OneAx, out: Optional[Floats3d] = None) -> Floats3d: ... @overload def sum(self, *, keepdims: Fal = False, axis: TwoAx, out: Optional[Floats2d] = None) -> Floats2d: ... @overload def sum(self, *, keepdims: Fal = False, axis: ThreeAx, out: Optional[Floats1d] = None) -> Floats1d: ... @overload def sum(self, *, keepdims: Fal = False, axis: Optional[FourAx], out = None) -> float: ... def sum(self, *, keepdims: bool = False, axis: _4_AllAx = None, out: Union[None, Floats1d, Floats2d, Floats3d, "Floats4d"] = None) -> _4F_ReduceResults: ... class Ints4d(_Array4d, _Ints): T: "Ints4d" @classmethod def __get_validators__(cls): yield lambda v: validate_array(v, ndim=4, dtype="i") def __iter__(self) -> Iterator[Ints3d]: ... @overload def sum(self, *, keepdims: Tru, axis: _4_AllAx = None, out: Optional["Ints4d"] = None) -> "Ints4d": ... @overload def sum(self, *, keepdims: Fal = False, axis: OneAx, out: Optional[Ints3d] = None) -> Ints3d: ... @overload def sum(self, *, keepdims: Fal = False, axis: TwoAx, out: Optional[Ints2d] = None) -> Ints2d: ... @overload def sum(self, *, keepdims: Fal = False, axis: ThreeAx, out: Optional[Ints1d] = None) -> Ints1d: ... @overload def sum(self, *, keepdims: Fal = False, axis: Optional[FourAx] = None, out = None) -> int: ... def sum(self, *, keepdims: bool = False, axis: _4_AllAx = None, out: Optional[Union[Ints1d, Ints2d, Ints3d, "Ints4d"]] = None) -> _4I_ReduceResults: ... _DIn = TypeVar("_DIn") class Decorator(Protocol): def __call__(self, name: str) -> Callable[[_DIn], _DIn]: ... class Generator(Iterator): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): if not hasattr(v, "__iter__") and not hasattr(v, "__next__"): raise TypeError("not a valid iterator") return v @dataclass class SizedGenerator: get_items: Callable[[], Generator] length: int def __len__(self): return self.length def __iter__(self): yield from self.get_items() @dataclass class Padded: data: Floats3d size_at_t: Ints1d lengths: Ints1d indices: Ints1d def copy(self): return Padded( self.data.copy(), self.size_at_t.copy(), self.lengths.copy(), self.indices.copy() ) def __len__(self) -> int: return self.lengths.shape[0] def __getitem__(self, index: Union[int, slice, Ints1d]) -> "Padded": if isinstance(index, int): return Padded( self.data[:, index : index + 1], self.lengths[index : index + 1], self.lengths[index : index + 1], self.indices[index : index + 1], ) elif isinstance(index, slice): return Padded( self.data[:, index], self.lengths[index], self.lengths[index], self.indices[index], ) else: sorted_index = list(sorted(index)) return Padded( self.data[sorted_index], self.size_at_t[sorted_index], self.lengths[sorted_index], self.indices[index], ) @dataclass class Ragged: data: Array2d lengths: Ints1d data_shape: Tuple[int, ...] starts_ends: Optional[Ints1d] = None def __init__(self, data: _Array, lengths: Ints1d): self.lengths = lengths if data.size: self.data = cast(Array2d, data.reshape((data.shape[0], -1))) else: self.data = cast(Array2d, data.reshape((0, 0))) self.data_shape = (-1,) + data.shape[1:] @property def dataXd(self) -> ArrayXd: if self.data.size: reshaped = self.data.reshape(self.data_shape) else: reshaped = self.data.reshape((self.data.shape[0],) + self.data_shape[1:]) return cast(ArrayXd, reshaped) def __len__(self) -> int: return self.lengths.shape[0] def __getitem__(self, index: Union[int, slice, Array1d]) -> "Ragged": if isinstance(index, tuple): raise IndexError("Ragged arrays do not support 2d indexing.") starts = self._get_starts() ends = self._get_ends() if isinstance(index, int): s = starts[index] e = ends[index] return Ragged(self.data[s:e], self.lengths[index : index + 1]) elif isinstance(index, slice): lengths = self.lengths[index] if len(lengths) == 0: return Ragged(self.data[0:0].reshape(self.data_shape), lengths) start = starts[index][0] if index.start >= 1 else 0 end = ends[index][-1] return Ragged(self.data[start:end].reshape(self.data_shape), lengths) else: # There must be a way to do this "properly" :(. Sigh, hate numpy. xp = get_array_module(self.data) data = xp.vstack([self[int(i)].data for i in index]) return Ragged(data.reshape(self.data_shape), self.lengths[index]) def _get_starts_ends(self) -> Ints1d: if self.starts_ends is None: xp = get_array_module(self.lengths) self.starts_ends = xp.empty(self.lengths.size + 1, dtype="i") self.starts_ends[0] = 0 self.lengths.cumsum(out=self.starts_ends[1:]) return self.starts_ends def _get_starts(self) -> Ints1d: return self._get_starts_ends()[:-1] def _get_ends(self) -> Ints1d: return self._get_starts_ends()[1:] _P = TypeVar("_P", bound=Sequence) @dataclass class Pairs(Generic[_P]): one: _P two: _P def __getitem__(self, index) -> "Pairs[_P]": return Pairs(self.one[index], self.two[index]) def __len__(self) -> int: return len(self.one) @dataclass class ArgsKwargs: args: Tuple[Any, ...] kwargs: Dict[str, Any] @classmethod def from_items(cls, items: Sequence[Tuple[Union[int, str], Any]]) -> "ArgsKwargs": args = [] kwargs = {} for key, value in items: if isinstance(key, int): args.append(value) else: kwargs[key] = value return cls(args=tuple(args), kwargs=kwargs) def keys(self) -> Iterable[Union[int, str]]: yield from range(len(self.args)) yield from self.kwargs.keys() def values(self) -> Iterable[Any]: yield from self.args yield from self.kwargs.values() def items(self) -> Iterable[Tuple[Union[int, str], Any]]: yield from enumerate(self.args) yield from self.kwargs.items() @dataclass class Unserializable: obj: Any def validate_array(obj, ndim=None, dtype=None): xp = get_array_module(obj) if not isinstance(obj, xp.ndarray): raise TypeError("not a valid numpy or cupy array") errors = [] if ndim is not None and obj.ndim != ndim: errors.append(f"wrong array dimensions (expected {ndim}, got {obj.ndim})") if dtype is not None: dtype_mapping = {"f": ["float32"], "i": ["int32", "int64", "uint32", "uint64"]} expected_types = dtype_mapping.get(dtype, []) if obj.dtype not in expected_types: expected = "/".join(expected_types) err = f"wrong array data type (expected {expected}, got {obj.dtype})" errors.append(err) if errors: raise ValueError(", ".join(errors)) return obj
true
true
f711004432df38ae3c8341225cdbbae91d9826b0
10
py
Python
tasks/EPAM/python_course/foundation-python/l7/m7-19-image.py
AleksNeStu/projects
1a4c68dfbdcb77228f0f3617e58fd18fcb1f5dbb
[ "Apache-2.0" ]
2
2022-01-19T18:01:35.000Z
2022-02-06T06:54:38.000Z
tasks/EPAM/python_course/foundation-python/l7/m7-5-logs.py
AleksNeStu/projects
1a4c68dfbdcb77228f0f3617e58fd18fcb1f5dbb
[ "Apache-2.0" ]
null
null
null
tasks/EPAM/python_course/foundation-python/l7/m7-5-logs.py
AleksNeStu/projects
1a4c68dfbdcb77228f0f3617e58fd18fcb1f5dbb
[ "Apache-2.0" ]
null
null
null
"""Talk"""
10
10
0.4
true
true
f711004483da66e51845425fa42d359f23f0af9c
21,264
py
Python
Codes/Python32/Lib/bdb.py
eyantra/FireBird_Swiss_Knife
cac322cf28e2d690b86ba28a75e87551e5e47988
[ "MIT" ]
319
2016-09-22T15:54:48.000Z
2022-03-18T02:36:58.000Z
Codes/Python32/Lib/bdb.py
eyantra/FireBird_Swiss_Knife
cac322cf28e2d690b86ba28a75e87551e5e47988
[ "MIT" ]
9
2016-11-03T21:56:41.000Z
2020-08-09T19:27:37.000Z
Codes/Python32/Lib/bdb.py
eyantra/FireBird_Swiss_Knife
cac322cf28e2d690b86ba28a75e87551e5e47988
[ "MIT" ]
27
2016-10-06T16:05:32.000Z
2022-03-18T02:37:00.000Z
"""Debugger basics""" import fnmatch import sys import os __all__ = ["BdbQuit", "Bdb", "Breakpoint"] class BdbQuit(Exception): """Exception to give up completely.""" class Bdb: """Generic Python debugger base class. This class takes care of details of the trace facility; a derived class should implement user interaction. The standard debugger class (pdb.Pdb) is an example. """ def __init__(self, skip=None): self.skip = set(skip) if skip else None self.breaks = {} self.fncache = {} def canonic(self, filename): if filename == "<" + filename[1:-1] + ">": return filename canonic = self.fncache.get(filename) if not canonic: canonic = os.path.abspath(filename) canonic = os.path.normcase(canonic) self.fncache[filename] = canonic return canonic def reset(self): import linecache linecache.checkcache() self.botframe = None self._set_stopinfo(None, None) def trace_dispatch(self, frame, event, arg): if self.quitting: return # None if event == 'line': return self.dispatch_line(frame) if event == 'call': return self.dispatch_call(frame, arg) if event == 'return': return self.dispatch_return(frame, arg) if event == 'exception': return self.dispatch_exception(frame, arg) if event == 'c_call': return self.trace_dispatch if event == 'c_exception': return self.trace_dispatch if event == 'c_return': return self.trace_dispatch print('bdb.Bdb.dispatch: unknown debugging event:', repr(event)) return self.trace_dispatch def dispatch_line(self, frame): if self.stop_here(frame) or self.break_here(frame): self.user_line(frame) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_call(self, frame, arg): # XXX 'arg' is no longer used if self.botframe is None: # First call of dispatch since reset() self.botframe = frame.f_back # (CT) Note that this may also be None! return self.trace_dispatch if not (self.stop_here(frame) or self.break_anywhere(frame)): # No need to trace this function return # None self.user_call(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_return(self, frame, arg): if self.stop_here(frame) or frame == self.returnframe: self.user_return(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_exception(self, frame, arg): if self.stop_here(frame): self.user_exception(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch # Normally derived classes don't override the following # methods, but they may if they want to redefine the # definition of stopping and breakpoints. def is_skipped_module(self, module_name): for pattern in self.skip: if fnmatch.fnmatch(module_name, pattern): return True return False def stop_here(self, frame): # (CT) stopframe may now also be None, see dispatch_call. # (CT) the former test for None is therefore removed from here. if self.skip and \ self.is_skipped_module(frame.f_globals.get('__name__')): return False if frame is self.stopframe: if self.stoplineno == -1: return False return frame.f_lineno >= self.stoplineno while frame is not None and frame is not self.stopframe: if frame is self.botframe: return True frame = frame.f_back return False def break_here(self, frame): filename = self.canonic(frame.f_code.co_filename) if filename not in self.breaks: return False lineno = frame.f_lineno if lineno not in self.breaks[filename]: # The line itself has no breakpoint, but maybe the line is the # first line of a function with breakpoint set by function name. lineno = frame.f_code.co_firstlineno if lineno not in self.breaks[filename]: return False # flag says ok to delete temp. bp (bp, flag) = effective(filename, lineno, frame) if bp: self.currentbp = bp.number if (flag and bp.temporary): self.do_clear(str(bp.number)) return True else: return False def do_clear(self, arg): raise NotImplementedError("subclass of bdb must implement do_clear()") def break_anywhere(self, frame): return self.canonic(frame.f_code.co_filename) in self.breaks # Derived classes should override the user_* methods # to gain control. def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" pass def user_line(self, frame): """This method is called when we stop or break at this line.""" pass def user_return(self, frame, return_value): """This method is called when a return trap is set here.""" pass def user_exception(self, frame, exc_info): """This method is called if an exception occurs, but only if we are to stop at or just below this level.""" pass def _set_stopinfo(self, stopframe, returnframe, stoplineno=0): self.stopframe = stopframe self.returnframe = returnframe self.quitting = False # stoplineno >= 0 means: stop at line >= the stoplineno # stoplineno -1 means: don't stop at all self.stoplineno = stoplineno # Derived classes and clients can call the following methods # to affect the stepping state. def set_until(self, frame, lineno=None): """Stop when the line with the line no greater than the current one is reached or when returning from current frame""" # the name "until" is borrowed from gdb if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, frame, lineno) def set_step(self): """Stop after one line of code.""" self._set_stopinfo(None, None) def set_next(self, frame): """Stop on the next line in or below the given frame.""" self._set_stopinfo(frame, None) def set_return(self, frame): """Stop when returning from the given frame.""" self._set_stopinfo(frame.f_back, frame) def set_trace(self, frame=None): """Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame. """ if frame is None: frame = sys._getframe().f_back self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self.set_step() sys.settrace(self.trace_dispatch) def set_continue(self): # Don't stop except at breakpoints or when finished self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # no breakpoints; run without debugger overhead sys.settrace(None) frame = sys._getframe().f_back while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back def set_quit(self): self.stopframe = self.botframe self.returnframe = None self.quitting = True sys.settrace(None) # Derived classes and clients can call the following methods # to manipulate breakpoints. These methods return an # error message is something went wrong, None if all is well. # Set_break prints out the breakpoint line and file:lineno. # Call self.get_*break*() to see the breakpoints or better # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint(). def set_break(self, filename, lineno, temporary=False, cond=None, funcname=None): filename = self.canonic(filename) import linecache # Import as late as possible line = linecache.getline(filename, lineno) if not line: return 'Line %s:%d does not exist' % (filename, lineno) list = self.breaks.setdefault(filename, []) if lineno not in list: list.append(lineno) bp = Breakpoint(filename, lineno, temporary, cond, funcname) def _prune_breaks(self, filename, lineno): if (filename, lineno) not in Breakpoint.bplist: self.breaks[filename].remove(lineno) if not self.breaks[filename]: del self.breaks[filename] def clear_break(self, filename, lineno): filename = self.canonic(filename) if filename not in self.breaks: return 'There are no breakpoints in %s' % filename if lineno not in self.breaks[filename]: return 'There is no breakpoint at %s:%d' % (filename, lineno) # If there's only one bp in the list for that file,line # pair, then remove the breaks entry for bp in Breakpoint.bplist[filename, lineno][:]: bp.deleteMe() self._prune_breaks(filename, lineno) def clear_bpbynumber(self, arg): try: bp = self.get_bpbynumber(arg) except ValueError as err: return str(err) bp.deleteMe() self._prune_breaks(bp.file, bp.line) def clear_all_file_breaks(self, filename): filename = self.canonic(filename) if filename not in self.breaks: return 'There are no breakpoints in %s' % filename for line in self.breaks[filename]: blist = Breakpoint.bplist[filename, line] for bp in blist: bp.deleteMe() del self.breaks[filename] def clear_all_breaks(self): if not self.breaks: return 'There are no breakpoints' for bp in Breakpoint.bpbynumber: if bp: bp.deleteMe() self.breaks = {} def get_bpbynumber(self, arg): if not arg: raise ValueError('Breakpoint number expected') try: number = int(arg) except ValueError: raise ValueError('Non-numeric breakpoint number %s' % arg) try: bp = Breakpoint.bpbynumber[number] except IndexError: raise ValueError('Breakpoint number %d out of range' % number) if bp is None: raise ValueError('Breakpoint %d already deleted' % number) return bp def get_break(self, filename, lineno): filename = self.canonic(filename) return filename in self.breaks and \ lineno in self.breaks[filename] def get_breaks(self, filename, lineno): filename = self.canonic(filename) return filename in self.breaks and \ lineno in self.breaks[filename] and \ Breakpoint.bplist[filename, lineno] or [] def get_file_breaks(self, filename): filename = self.canonic(filename) if filename in self.breaks: return self.breaks[filename] else: return [] def get_all_breaks(self): return self.breaks # Derived classes and clients can call the following method # to get a data structure representing a stack trace. def get_stack(self, f, t): stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if f is None: i = max(0, len(stack) - 1) return stack, i def format_stack_entry(self, frame_lineno, lprefix=': '): import linecache, reprlib frame, lineno = frame_lineno filename = self.canonic(frame.f_code.co_filename) s = '%s(%r)' % (filename, lineno) if frame.f_code.co_name: s += frame.f_code.co_name else: s += "<lambda>" if '__args__' in frame.f_locals: args = frame.f_locals['__args__'] else: args = None if args: s += reprlib.repr(args) else: s += '()' if '__return__' in frame.f_locals: rv = frame.f_locals['__return__'] s += '->' s += reprlib.repr(rv) line = linecache.getline(filename, lineno, frame.f_globals) if line: s += lprefix + line.strip() return s # The following methods can be called by clients to use # a debugger to debug a statement or an expression. # Both can be given as a string, or a code object. def run(self, cmd, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() if isinstance(cmd, str): cmd = compile(cmd, "<string>", "exec") sys.settrace(self.trace_dispatch) try: exec(cmd, globals, locals) except BdbQuit: pass finally: self.quitting = True sys.settrace(None) def runeval(self, expr, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() sys.settrace(self.trace_dispatch) try: return eval(expr, globals, locals) except BdbQuit: pass finally: self.quitting = True sys.settrace(None) def runctx(self, cmd, globals, locals): # B/W compatibility self.run(cmd, globals, locals) # This method is more useful to debug a single function call. def runcall(self, func, *args, **kwds): self.reset() sys.settrace(self.trace_dispatch) res = None try: res = func(*args, **kwds) except BdbQuit: pass finally: self.quitting = True sys.settrace(None) return res def set_trace(): Bdb().set_trace() class Breakpoint: """Breakpoint class. Implements temporary breakpoints, ignore counts, disabling and (re)-enabling, and conditionals. Breakpoints are indexed by number through bpbynumber and by the file,line tuple using bplist. The former points to a single instance of class Breakpoint. The latter points to a list of such instances since there may be more than one breakpoint per line. """ # XXX Keeping state in the class is a mistake -- this means # you cannot have more than one active Bdb instance. next = 1 # Next bp to be assigned bplist = {} # indexed by (file, lineno) tuple bpbynumber = [None] # Each entry is None or an instance of Bpt # index 0 is unused, except for marking an # effective break .... see effective() def __init__(self, file, line, temporary=False, cond=None, funcname=None): self.funcname = funcname # Needed if funcname is not None. self.func_first_executable_line = None self.file = file # This better be in canonical form! self.line = line self.temporary = temporary self.cond = cond self.enabled = True self.ignore = 0 self.hits = 0 self.number = Breakpoint.next Breakpoint.next += 1 # Build the two lists self.bpbynumber.append(self) if (file, line) in self.bplist: self.bplist[file, line].append(self) else: self.bplist[file, line] = [self] def deleteMe(self): index = (self.file, self.line) self.bpbynumber[self.number] = None # No longer in list self.bplist[index].remove(self) if not self.bplist[index]: # No more bp for this f:l combo del self.bplist[index] def enable(self): self.enabled = True def disable(self): self.enabled = False def bpprint(self, out=None): if out is None: out = sys.stdout print(self.bpformat(), file=out) def bpformat(self): if self.temporary: disp = 'del ' else: disp = 'keep ' if self.enabled: disp = disp + 'yes ' else: disp = disp + 'no ' ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp, self.file, self.line) if self.cond: ret += '\n\tstop only if %s' % (self.cond,) if self.ignore: ret += '\n\tignore next %d hits' % (self.ignore,) if self.hits: if self.hits > 1: ss = 's' else: ss = '' ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss) return ret def __str__(self): return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line) # -----------end of Breakpoint class---------- def checkfuncname(b, frame): """Check whether we should break here because of `b.funcname`.""" if not b.funcname: # Breakpoint was set via line number. if b.line != frame.f_lineno: # Breakpoint was set at a line with a def statement and the function # defined is called: don't break. return False return True # Breakpoint set via function name. if frame.f_code.co_name != b.funcname: # It's not a function call, but rather execution of def statement. return False # We are in the right frame. if not b.func_first_executable_line: # The function is entered for the 1st time. b.func_first_executable_line = frame.f_lineno if b.func_first_executable_line != frame.f_lineno: # But we are not at the first line number: don't break. return False return True # Determines if there is an effective (active) breakpoint at this # line of code. Returns breakpoint number or 0 if none def effective(file, line, frame): """Determine which breakpoint for this file:line is to be acted upon. Called only if we know there is a bpt at this location. Returns breakpoint that was triggered and a flag that indicates if it is ok to delete a temporary bp. """ possibles = Breakpoint.bplist[file, line] for b in possibles: if not b.enabled: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits += 1 if not b.cond: # If unconditional, and ignoring go on to next, else break if b.ignore > 0: b.ignore -= 1 continue else: # breakpoint and marker that it's ok to delete if temporary return (b, True) else: # Conditional bp. # Ignore count applies only to those bpt hits where the # condition evaluates to true. try: val = eval(b.cond, frame.f_globals, frame.f_locals) if val: if b.ignore > 0: b.ignore -= 1 # continue else: return (b, True) # else: # continue except: # if eval fails, most conservative thing is to stop on # breakpoint regardless of ignore count. Don't delete # temporary, as another hint to user. return (b, False) return (None, None) # -------------------- testing -------------------- class Tdb(Bdb): def user_call(self, frame, args): name = frame.f_code.co_name if not name: name = '???' print('+++ call', name, args) def user_line(self, frame): import linecache name = frame.f_code.co_name if not name: name = '???' fn = self.canonic(frame.f_code.co_filename) line = linecache.getline(fn, frame.f_lineno, frame.f_globals) print('+++', fn, frame.f_lineno, name, ':', line.strip()) def user_return(self, frame, retval): print('+++ return', retval) def user_exception(self, frame, exc_stuff): print('+++ exception', exc_stuff) self.set_continue() def foo(n): print('foo(', n, ')') x = bar(n*10) print('bar returned', x) def bar(a): print('bar(', a, ')') return a/2 def test(): t = Tdb() t.run('import bdb; bdb.foo(10)')
33.486614
80
0.581358
import fnmatch import sys import os __all__ = ["BdbQuit", "Bdb", "Breakpoint"] class BdbQuit(Exception): class Bdb: def __init__(self, skip=None): self.skip = set(skip) if skip else None self.breaks = {} self.fncache = {} def canonic(self, filename): if filename == "<" + filename[1:-1] + ">": return filename canonic = self.fncache.get(filename) if not canonic: canonic = os.path.abspath(filename) canonic = os.path.normcase(canonic) self.fncache[filename] = canonic return canonic def reset(self): import linecache linecache.checkcache() self.botframe = None self._set_stopinfo(None, None) def trace_dispatch(self, frame, event, arg): if self.quitting: return if event == 'line': return self.dispatch_line(frame) if event == 'call': return self.dispatch_call(frame, arg) if event == 'return': return self.dispatch_return(frame, arg) if event == 'exception': return self.dispatch_exception(frame, arg) if event == 'c_call': return self.trace_dispatch if event == 'c_exception': return self.trace_dispatch if event == 'c_return': return self.trace_dispatch print('bdb.Bdb.dispatch: unknown debugging event:', repr(event)) return self.trace_dispatch def dispatch_line(self, frame): if self.stop_here(frame) or self.break_here(frame): self.user_line(frame) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_call(self, frame, arg): if self.botframe is None: self.botframe = frame.f_back return self.trace_dispatch if not (self.stop_here(frame) or self.break_anywhere(frame)): return self.user_call(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_return(self, frame, arg): if self.stop_here(frame) or frame == self.returnframe: self.user_return(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch def dispatch_exception(self, frame, arg): if self.stop_here(frame): self.user_exception(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch # methods, but they may if they want to redefine the # definition of stopping and breakpoints. def is_skipped_module(self, module_name): for pattern in self.skip: if fnmatch.fnmatch(module_name, pattern): return True return False def stop_here(self, frame): # (CT) stopframe may now also be None, see dispatch_call. # (CT) the former test for None is therefore removed from here. if self.skip and \ self.is_skipped_module(frame.f_globals.get('__name__')): return False if frame is self.stopframe: if self.stoplineno == -1: return False return frame.f_lineno >= self.stoplineno while frame is not None and frame is not self.stopframe: if frame is self.botframe: return True frame = frame.f_back return False def break_here(self, frame): filename = self.canonic(frame.f_code.co_filename) if filename not in self.breaks: return False lineno = frame.f_lineno if lineno not in self.breaks[filename]: # The line itself has no breakpoint, but maybe the line is the # first line of a function with breakpoint set by function name. lineno = frame.f_code.co_firstlineno if lineno not in self.breaks[filename]: return False # flag says ok to delete temp. bp (bp, flag) = effective(filename, lineno, frame) if bp: self.currentbp = bp.number if (flag and bp.temporary): self.do_clear(str(bp.number)) return True else: return False def do_clear(self, arg): raise NotImplementedError("subclass of bdb must implement do_clear()") def break_anywhere(self, frame): return self.canonic(frame.f_code.co_filename) in self.breaks # Derived classes should override the user_* methods # to gain control. def user_call(self, frame, argument_list): pass def user_line(self, frame): pass def user_return(self, frame, return_value): pass def user_exception(self, frame, exc_info): pass def _set_stopinfo(self, stopframe, returnframe, stoplineno=0): self.stopframe = stopframe self.returnframe = returnframe self.quitting = False # stoplineno >= 0 means: stop at line >= the stoplineno # stoplineno -1 means: don't stop at all self.stoplineno = stoplineno def set_until(self, frame, lineno=None): if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, frame, lineno) def set_step(self): self._set_stopinfo(None, None) def set_next(self, frame): self._set_stopinfo(frame, None) def set_return(self, frame): self._set_stopinfo(frame.f_back, frame) def set_trace(self, frame=None): if frame is None: frame = sys._getframe().f_back self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self.set_step() sys.settrace(self.trace_dispatch) def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # no breakpoints; run without debugger overhead sys.settrace(None) frame = sys._getframe().f_back while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back def set_quit(self): self.stopframe = self.botframe self.returnframe = None self.quitting = True sys.settrace(None) # Derived classes and clients can call the following methods # to manipulate breakpoints. These methods return an # error message is something went wrong, None if all is well. # Set_break prints out the breakpoint line and file:lineno. # Call self.get_*break*() to see the breakpoints or better # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint(). def set_break(self, filename, lineno, temporary=False, cond=None, funcname=None): filename = self.canonic(filename) import linecache # Import as late as possible line = linecache.getline(filename, lineno) if not line: return 'Line %s:%d does not exist' % (filename, lineno) list = self.breaks.setdefault(filename, []) if lineno not in list: list.append(lineno) bp = Breakpoint(filename, lineno, temporary, cond, funcname) def _prune_breaks(self, filename, lineno): if (filename, lineno) not in Breakpoint.bplist: self.breaks[filename].remove(lineno) if not self.breaks[filename]: del self.breaks[filename] def clear_break(self, filename, lineno): filename = self.canonic(filename) if filename not in self.breaks: return 'There are no breakpoints in %s' % filename if lineno not in self.breaks[filename]: return 'There is no breakpoint at %s:%d' % (filename, lineno) # If there's only one bp in the list for that file,line for bp in Breakpoint.bplist[filename, lineno][:]: bp.deleteMe() self._prune_breaks(filename, lineno) def clear_bpbynumber(self, arg): try: bp = self.get_bpbynumber(arg) except ValueError as err: return str(err) bp.deleteMe() self._prune_breaks(bp.file, bp.line) def clear_all_file_breaks(self, filename): filename = self.canonic(filename) if filename not in self.breaks: return 'There are no breakpoints in %s' % filename for line in self.breaks[filename]: blist = Breakpoint.bplist[filename, line] for bp in blist: bp.deleteMe() del self.breaks[filename] def clear_all_breaks(self): if not self.breaks: return 'There are no breakpoints' for bp in Breakpoint.bpbynumber: if bp: bp.deleteMe() self.breaks = {} def get_bpbynumber(self, arg): if not arg: raise ValueError('Breakpoint number expected') try: number = int(arg) except ValueError: raise ValueError('Non-numeric breakpoint number %s' % arg) try: bp = Breakpoint.bpbynumber[number] except IndexError: raise ValueError('Breakpoint number %d out of range' % number) if bp is None: raise ValueError('Breakpoint %d already deleted' % number) return bp def get_break(self, filename, lineno): filename = self.canonic(filename) return filename in self.breaks and \ lineno in self.breaks[filename] def get_breaks(self, filename, lineno): filename = self.canonic(filename) return filename in self.breaks and \ lineno in self.breaks[filename] and \ Breakpoint.bplist[filename, lineno] or [] def get_file_breaks(self, filename): filename = self.canonic(filename) if filename in self.breaks: return self.breaks[filename] else: return [] def get_all_breaks(self): return self.breaks def get_stack(self, f, t): stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if f is None: i = max(0, len(stack) - 1) return stack, i def format_stack_entry(self, frame_lineno, lprefix=': '): import linecache, reprlib frame, lineno = frame_lineno filename = self.canonic(frame.f_code.co_filename) s = '%s(%r)' % (filename, lineno) if frame.f_code.co_name: s += frame.f_code.co_name else: s += "<lambda>" if '__args__' in frame.f_locals: args = frame.f_locals['__args__'] else: args = None if args: s += reprlib.repr(args) else: s += '()' if '__return__' in frame.f_locals: rv = frame.f_locals['__return__'] s += '->' s += reprlib.repr(rv) line = linecache.getline(filename, lineno, frame.f_globals) if line: s += lprefix + line.strip() return s def run(self, cmd, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() if isinstance(cmd, str): cmd = compile(cmd, "<string>", "exec") sys.settrace(self.trace_dispatch) try: exec(cmd, globals, locals) except BdbQuit: pass finally: self.quitting = True sys.settrace(None) def runeval(self, expr, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() sys.settrace(self.trace_dispatch) try: return eval(expr, globals, locals) except BdbQuit: pass finally: self.quitting = True sys.settrace(None) def runctx(self, cmd, globals, locals): self.run(cmd, globals, locals) def runcall(self, func, *args, **kwds): self.reset() sys.settrace(self.trace_dispatch) res = None try: res = func(*args, **kwds) except BdbQuit: pass finally: self.quitting = True sys.settrace(None) return res def set_trace(): Bdb().set_trace() class Breakpoint: next = 1 bplist = {} bpbynumber = [None] def __init__(self, file, line, temporary=False, cond=None, funcname=None): self.funcname = funcname self.func_first_executable_line = None self.file = file self.line = line self.temporary = temporary self.cond = cond self.enabled = True self.ignore = 0 self.hits = 0 self.number = Breakpoint.next Breakpoint.next += 1 self.bpbynumber.append(self) if (file, line) in self.bplist: self.bplist[file, line].append(self) else: self.bplist[file, line] = [self] def deleteMe(self): index = (self.file, self.line) self.bpbynumber[self.number] = None self.bplist[index].remove(self) if not self.bplist[index]: del self.bplist[index] def enable(self): self.enabled = True def disable(self): self.enabled = False def bpprint(self, out=None): if out is None: out = sys.stdout print(self.bpformat(), file=out) def bpformat(self): if self.temporary: disp = 'del ' else: disp = 'keep ' if self.enabled: disp = disp + 'yes ' else: disp = disp + 'no ' ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp, self.file, self.line) if self.cond: ret += '\n\tstop only if %s' % (self.cond,) if self.ignore: ret += '\n\tignore next %d hits' % (self.ignore,) if self.hits: if self.hits > 1: ss = 's' else: ss = '' ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss) return ret def __str__(self): return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line) def checkfuncname(b, frame): if not b.funcname: if b.line != frame.f_lineno: return False return True # Breakpoint set via function name. if frame.f_code.co_name != b.funcname: # It's not a function call, but rather execution of def statement. return False if not b.func_first_executable_line: b.func_first_executable_line = frame.f_lineno if b.func_first_executable_line != frame.f_lineno: return False return True # Determines if there is an effective (active) breakpoint at this # line of code. Returns breakpoint number or 0 if none def effective(file, line, frame): possibles = Breakpoint.bplist[file, line] for b in possibles: if not b.enabled: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits += 1 if not b.cond: # If unconditional, and ignoring go on to next, else break if b.ignore > 0: b.ignore -= 1 continue else: # breakpoint and marker that it's ok to delete if temporary return (b, True) else: try: val = eval(b.cond, frame.f_globals, frame.f_locals) if val: if b.ignore > 0: b.ignore -= 1 else: return (b, True) except: # temporary, as another hint to user. return (b, False) return (None, None) # -------------------- testing -------------------- class Tdb(Bdb): def user_call(self, frame, args): name = frame.f_code.co_name if not name: name = '???' print('+++ call', name, args) def user_line(self, frame): import linecache name = frame.f_code.co_name if not name: name = '???' fn = self.canonic(frame.f_code.co_filename) line = linecache.getline(fn, frame.f_lineno, frame.f_globals) print('+++', fn, frame.f_lineno, name, ':', line.strip()) def user_return(self, frame, retval): print('+++ return', retval) def user_exception(self, frame, exc_stuff): print('+++ exception', exc_stuff) self.set_continue() def foo(n): print('foo(', n, ')') x = bar(n*10) print('bar returned', x) def bar(a): print('bar(', a, ')') return a/2 def test(): t = Tdb() t.run('import bdb; bdb.foo(10)')
true
true
f71100cc93e49fc798cb8d6af96b7df25b5c0b0f
1,424
py
Python
terraform/terraform-swarm-inventory.py
swipswaps/hcloud_swarm
63f861c4daadc3a01fc646371cd71503353e7693
[ "Unlicense" ]
null
null
null
terraform/terraform-swarm-inventory.py
swipswaps/hcloud_swarm
63f861c4daadc3a01fc646371cd71503353e7693
[ "Unlicense" ]
null
null
null
terraform/terraform-swarm-inventory.py
swipswaps/hcloud_swarm
63f861c4daadc3a01fc646371cd71503353e7693
[ "Unlicense" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import os ANSIBLE_SSH_PORT = '2222' def get_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('--list', action='store_true') parser.add_argument('--host') return parser.parse_args() def wd_to_script_dir(): import os path = os.path.abspath(__file__) dir = os.path.dirname(path) os.chdir(dir) def terraform_output(key): ret = os.popen('terraform output -json ' + key).read() return json.loads(ret) def main(): args = get_args() wd_to_script_dir() primary_managers = terraform_output('swarm-primary-managers') secondary_managers = terraform_output('swarm-secondary-managers') workers = terraform_output('swarm-workers') ssh_public_key = terraform_output('ssh-public-key') if args.list: inventory = { 'swarm-primary-managers': list(primary_managers.keys()), 'swarm-secondary-managers': list(secondary_managers.keys()), 'swarm-workers': list(workers.keys()) } print(json.dumps(inventory)) if args.host: hosts = {**primary_managers, **secondary_managers, **workers} print(json.dumps({ 'ansible_host': hosts[args.host], 'ansible_port': ANSIBLE_SSH_PORT, 'ssh_public_key': ssh_public_key })) if __name__ == "__main__": main()
28.48
72
0.64677
import json import os ANSIBLE_SSH_PORT = '2222' def get_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('--list', action='store_true') parser.add_argument('--host') return parser.parse_args() def wd_to_script_dir(): import os path = os.path.abspath(__file__) dir = os.path.dirname(path) os.chdir(dir) def terraform_output(key): ret = os.popen('terraform output -json ' + key).read() return json.loads(ret) def main(): args = get_args() wd_to_script_dir() primary_managers = terraform_output('swarm-primary-managers') secondary_managers = terraform_output('swarm-secondary-managers') workers = terraform_output('swarm-workers') ssh_public_key = terraform_output('ssh-public-key') if args.list: inventory = { 'swarm-primary-managers': list(primary_managers.keys()), 'swarm-secondary-managers': list(secondary_managers.keys()), 'swarm-workers': list(workers.keys()) } print(json.dumps(inventory)) if args.host: hosts = {**primary_managers, **secondary_managers, **workers} print(json.dumps({ 'ansible_host': hosts[args.host], 'ansible_port': ANSIBLE_SSH_PORT, 'ssh_public_key': ssh_public_key })) if __name__ == "__main__": main()
true
true
f71100d20d055f23e34b99c487028c18495bced0
1,954
py
Python
tcex/threat_intelligence/mappings/indicator/indicator_types/address.py
kdeltared/tcex
818c0d09256764f871e42d9ca5916f92d941d882
[ "Apache-2.0" ]
null
null
null
tcex/threat_intelligence/mappings/indicator/indicator_types/address.py
kdeltared/tcex
818c0d09256764f871e42d9ca5916f92d941d882
[ "Apache-2.0" ]
null
null
null
tcex/threat_intelligence/mappings/indicator/indicator_types/address.py
kdeltared/tcex
818c0d09256764f871e42d9ca5916f92d941d882
[ "Apache-2.0" ]
null
null
null
"""ThreatConnect TI Address""" from ..indicator import Indicator class Address(Indicator): """Unique API calls for Address API Endpoints""" def __init__(self, tcex, **kwargs): """Initialize Class Properties. Args: ip (str): The value for this Indicator. active (bool, kwargs): If False the indicator is marked "inactive" in TC. confidence (str, kwargs): The threat confidence for this Indicator. date_added (str, kwargs): [Read-Only] The date timestamp the Indicator was created. last_modified (str, kwargs): [Read-Only] The date timestamp the Indicator was last modified. private_flag (bool, kwargs): If True the indicator is marked as private in TC. rating (str, kwargs): The threat rating for this Indicator. """ super().__init__( tcex, sub_type='Address', api_entity='address', api_branch='addresses', **kwargs ) self.unique_id = kwargs.get('unique_id', kwargs.get('ip')) self.data['ip'] = self.unique_id def _set_unique_id(self, json_response): """Set the unique_id provided a json response. Args: json_response: """ self.unique_id = json_response.get('ip', '') def can_create(self): """Return True if address can be created. If the ip address has been provided returns that the address can be created, otherwise returns that the address cannot be created. """ return not self.data.get('ip') is None # TODO: @burdy - is this correct for address? def dns_resolution(self): """Update the DNS resolution. Returns: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) return self.tc_requests.dns_resolution( self.api_type, self.api_branch, self.unique_id, owner=self.owner )
35.527273
95
0.616684
from ..indicator import Indicator class Address(Indicator): def __init__(self, tcex, **kwargs): super().__init__( tcex, sub_type='Address', api_entity='address', api_branch='addresses', **kwargs ) self.unique_id = kwargs.get('unique_id', kwargs.get('ip')) self.data['ip'] = self.unique_id def _set_unique_id(self, json_response): self.unique_id = json_response.get('ip', '') def can_create(self): return not self.data.get('ip') is None def dns_resolution(self): if not self.can_update(): self._tcex.handle_error(910, [self.type]) return self.tc_requests.dns_resolution( self.api_type, self.api_branch, self.unique_id, owner=self.owner )
true
true
f71100eca98bd65fe173f8abaf89f414cac01ae0
11,299
py
Python
pysnmp/A3COM-HUAWEI-LswIGSP-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/A3COM-HUAWEI-LswIGSP-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/A3COM-HUAWEI-LswIGSP-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 A3COM-HUAWEI-LswIGSP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-LswIGSP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:51:01 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) # lswCommon, = mibBuilder.importSymbols("A3COM-HUAWEI-OID-MIB", "lswCommon") ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Unsigned32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, iso, TimeTicks, NotificationType, Counter32, Integer32, ObjectIdentity, Gauge32, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Unsigned32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "iso", "TimeTicks", "NotificationType", "Counter32", "Integer32", "ObjectIdentity", "Gauge32", "Bits") RowStatus, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString") hwLswIgmpsnoopingMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7)) hwLswIgmpsnoopingMib.setRevisions(('2001-06-29 00:00',)) if mibBuilder.loadTexts: hwLswIgmpsnoopingMib.setLastUpdated('200106290000Z') if mibBuilder.loadTexts: hwLswIgmpsnoopingMib.setOrganization('') class EnabledStatus(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("enabled", 1), ("disabled", 2)) hwLswIgmpsnoopingMibObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1)) hwIgmpSnoopingStatus = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingStatus.setStatus('current') hwIgmpSnoopingRouterPortAge = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)).clone(105)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingRouterPortAge.setStatus('current') hwIgmpSnoopingResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(10)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingResponseTime.setStatus('current') hwIgmpSnoopingHostTime = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(200, 1000)).clone(260)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingHostTime.setStatus('current') hwIgmpSnoopingGroupLimitTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5), ) if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitTable.setStatus('current') hwIgmpSnoopingGroupLimitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupIfIndex")) if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitEntry.setStatus('current') hwIgmpSnoopingGroupIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingGroupIfIndex.setStatus('current') hwIgmpSnoopingGroupLimitNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1, 2), Unsigned32().clone(4294967295)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitNumber.setStatus('current') hwIgmpSnoopingFastLeaveTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6), ) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveTable.setStatus('current') hwIgmpSnoopingFastLeaveEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingFastLeaveIfIndex")) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveEntry.setStatus('current') hwIgmpSnoopingFastLeaveIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveIfIndex.setStatus('current') hwIgmpSnoopingFastLeaveStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1, 2), EnabledStatus().clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveStatus.setStatus('current') hwIgmpSnoopingGroupPolicyTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7), ) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyTable.setStatus('current') hwIgmpSnoopingGroupPolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupPolicyIfIndex"), (0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupPolicyVlanID")) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyEntry.setStatus('current') hwIgmpSnoopingGroupPolicyIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyIfIndex.setStatus('current') hwIgmpSnoopingGroupPolicyVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyVlanID.setStatus('current') hwIgmpSnoopingGroupPolicyParameter = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2000, 2999))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyParameter.setStatus('current') hwIgmpSnoopingGroupPolicyStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyStatus.setStatus('current') hwIgmpSnoopingNonFloodingStatus = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 8), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingNonFloodingStatus.setStatus('current') hwIgmpSnoopingVlanStatusTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9), ) if mibBuilder.loadTexts: hwIgmpSnoopingVlanStatusTable.setStatus('current') hwIgmpSnoopingVlanStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingVlanID")) if mibBuilder.loadTexts: hwIgmpSnoopingVlanStatusEntry.setStatus('current') hwIgmpSnoopingVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))) if mibBuilder.loadTexts: hwIgmpSnoopingVlanID.setStatus('current') hwIgmpSnoopingVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1, 2), EnabledStatus().clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingVlanEnabled.setStatus('current') hwIgmpSnoopingStatsObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10)) hwRecvIGMPGQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPGQueryNum.setStatus('current') hwRecvIGMPSQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPSQueryNum.setStatus('current') hwRecvIGMPV1ReportNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPV1ReportNum.setStatus('current') hwRecvIGMPV2ReportNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPV2ReportNum.setStatus('current') hwRecvIGMPLeaveNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPLeaveNum.setStatus('current') hwRecvErrorIGMPPacketNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvErrorIGMPPacketNum.setStatus('current') hwSentIGMPSQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwSentIGMPSQueryNum.setStatus('current') hwIgmpSnoopingClearStats = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("clear", 1), ("counting", 2))).clone('counting')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingClearStats.setStatus('current') mibBuilder.exportSymbols("A3COM-HUAWEI-LswIGSP-MIB", hwIgmpSnoopingStatus=hwIgmpSnoopingStatus, hwIgmpSnoopingResponseTime=hwIgmpSnoopingResponseTime, hwIgmpSnoopingGroupPolicyParameter=hwIgmpSnoopingGroupPolicyParameter, hwIgmpSnoopingRouterPortAge=hwIgmpSnoopingRouterPortAge, hwIgmpSnoopingHostTime=hwIgmpSnoopingHostTime, hwRecvIGMPV2ReportNum=hwRecvIGMPV2ReportNum, hwIgmpSnoopingGroupPolicyEntry=hwIgmpSnoopingGroupPolicyEntry, hwIgmpSnoopingGroupPolicyVlanID=hwIgmpSnoopingGroupPolicyVlanID, hwIgmpSnoopingGroupLimitEntry=hwIgmpSnoopingGroupLimitEntry, hwSentIGMPSQueryNum=hwSentIGMPSQueryNum, hwIgmpSnoopingGroupPolicyStatus=hwIgmpSnoopingGroupPolicyStatus, hwLswIgmpsnoopingMibObject=hwLswIgmpsnoopingMibObject, hwRecvIGMPSQueryNum=hwRecvIGMPSQueryNum, hwIgmpSnoopingGroupIfIndex=hwIgmpSnoopingGroupIfIndex, hwLswIgmpsnoopingMib=hwLswIgmpsnoopingMib, hwIgmpSnoopingVlanEnabled=hwIgmpSnoopingVlanEnabled, hwIgmpSnoopingClearStats=hwIgmpSnoopingClearStats, hwIgmpSnoopingStatsObjects=hwIgmpSnoopingStatsObjects, hwRecvErrorIGMPPacketNum=hwRecvErrorIGMPPacketNum, PYSNMP_MODULE_ID=hwLswIgmpsnoopingMib, hwIgmpSnoopingFastLeaveIfIndex=hwIgmpSnoopingFastLeaveIfIndex, hwRecvIGMPLeaveNum=hwRecvIGMPLeaveNum, hwIgmpSnoopingGroupLimitNumber=hwIgmpSnoopingGroupLimitNumber, hwIgmpSnoopingNonFloodingStatus=hwIgmpSnoopingNonFloodingStatus, hwIgmpSnoopingGroupLimitTable=hwIgmpSnoopingGroupLimitTable, hwIgmpSnoopingFastLeaveTable=hwIgmpSnoopingFastLeaveTable, hwRecvIGMPGQueryNum=hwRecvIGMPGQueryNum, EnabledStatus=EnabledStatus, hwIgmpSnoopingVlanStatusEntry=hwIgmpSnoopingVlanStatusEntry, hwIgmpSnoopingGroupPolicyIfIndex=hwIgmpSnoopingGroupPolicyIfIndex, hwIgmpSnoopingFastLeaveStatus=hwIgmpSnoopingFastLeaveStatus, hwIgmpSnoopingVlanID=hwIgmpSnoopingVlanID, hwIgmpSnoopingGroupPolicyTable=hwIgmpSnoopingGroupPolicyTable, hwIgmpSnoopingVlanStatusTable=hwIgmpSnoopingVlanStatusTable, hwIgmpSnoopingFastLeaveEntry=hwIgmpSnoopingFastLeaveEntry, hwRecvIGMPV1ReportNum=hwRecvIGMPV1ReportNum)
125.544444
1,988
0.775113
lswCommon, = mibBuilder.importSymbols("A3COM-HUAWEI-OID-MIB", "lswCommon") ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Unsigned32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, iso, TimeTicks, NotificationType, Counter32, Integer32, ObjectIdentity, Gauge32, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Unsigned32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "iso", "TimeTicks", "NotificationType", "Counter32", "Integer32", "ObjectIdentity", "Gauge32", "Bits") RowStatus, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString") hwLswIgmpsnoopingMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7)) hwLswIgmpsnoopingMib.setRevisions(('2001-06-29 00:00',)) if mibBuilder.loadTexts: hwLswIgmpsnoopingMib.setLastUpdated('200106290000Z') if mibBuilder.loadTexts: hwLswIgmpsnoopingMib.setOrganization('') class EnabledStatus(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("enabled", 1), ("disabled", 2)) hwLswIgmpsnoopingMibObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1)) hwIgmpSnoopingStatus = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingStatus.setStatus('current') hwIgmpSnoopingRouterPortAge = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)).clone(105)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingRouterPortAge.setStatus('current') hwIgmpSnoopingResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(10)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingResponseTime.setStatus('current') hwIgmpSnoopingHostTime = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(200, 1000)).clone(260)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingHostTime.setStatus('current') hwIgmpSnoopingGroupLimitTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5), ) if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitTable.setStatus('current') hwIgmpSnoopingGroupLimitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupIfIndex")) if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitEntry.setStatus('current') hwIgmpSnoopingGroupIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingGroupIfIndex.setStatus('current') hwIgmpSnoopingGroupLimitNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 5, 1, 2), Unsigned32().clone(4294967295)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingGroupLimitNumber.setStatus('current') hwIgmpSnoopingFastLeaveTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6), ) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveTable.setStatus('current') hwIgmpSnoopingFastLeaveEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingFastLeaveIfIndex")) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveEntry.setStatus('current') hwIgmpSnoopingFastLeaveIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveIfIndex.setStatus('current') hwIgmpSnoopingFastLeaveStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 6, 1, 2), EnabledStatus().clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingFastLeaveStatus.setStatus('current') hwIgmpSnoopingGroupPolicyTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7), ) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyTable.setStatus('current') hwIgmpSnoopingGroupPolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupPolicyIfIndex"), (0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingGroupPolicyVlanID")) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyEntry.setStatus('current') hwIgmpSnoopingGroupPolicyIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyIfIndex.setStatus('current') hwIgmpSnoopingGroupPolicyVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))) if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyVlanID.setStatus('current') hwIgmpSnoopingGroupPolicyParameter = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2000, 2999))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyParameter.setStatus('current') hwIgmpSnoopingGroupPolicyStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 7, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hwIgmpSnoopingGroupPolicyStatus.setStatus('current') hwIgmpSnoopingNonFloodingStatus = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 8), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingNonFloodingStatus.setStatus('current') hwIgmpSnoopingVlanStatusTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9), ) if mibBuilder.loadTexts: hwIgmpSnoopingVlanStatusTable.setStatus('current') hwIgmpSnoopingVlanStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1), ).setIndexNames((0, "A3COM-HUAWEI-LswIGSP-MIB", "hwIgmpSnoopingVlanID")) if mibBuilder.loadTexts: hwIgmpSnoopingVlanStatusEntry.setStatus('current') hwIgmpSnoopingVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))) if mibBuilder.loadTexts: hwIgmpSnoopingVlanID.setStatus('current') hwIgmpSnoopingVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 9, 1, 2), EnabledStatus().clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingVlanEnabled.setStatus('current') hwIgmpSnoopingStatsObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10)) hwRecvIGMPGQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPGQueryNum.setStatus('current') hwRecvIGMPSQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPSQueryNum.setStatus('current') hwRecvIGMPV1ReportNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPV1ReportNum.setStatus('current') hwRecvIGMPV2ReportNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPV2ReportNum.setStatus('current') hwRecvIGMPLeaveNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvIGMPLeaveNum.setStatus('current') hwRecvErrorIGMPPacketNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwRecvErrorIGMPPacketNum.setStatus('current') hwSentIGMPSQueryNum = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwSentIGMPSQueryNum.setStatus('current') hwIgmpSnoopingClearStats = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 2, 23, 1, 7, 1, 10, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("clear", 1), ("counting", 2))).clone('counting')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwIgmpSnoopingClearStats.setStatus('current') mibBuilder.exportSymbols("A3COM-HUAWEI-LswIGSP-MIB", hwIgmpSnoopingStatus=hwIgmpSnoopingStatus, hwIgmpSnoopingResponseTime=hwIgmpSnoopingResponseTime, hwIgmpSnoopingGroupPolicyParameter=hwIgmpSnoopingGroupPolicyParameter, hwIgmpSnoopingRouterPortAge=hwIgmpSnoopingRouterPortAge, hwIgmpSnoopingHostTime=hwIgmpSnoopingHostTime, hwRecvIGMPV2ReportNum=hwRecvIGMPV2ReportNum, hwIgmpSnoopingGroupPolicyEntry=hwIgmpSnoopingGroupPolicyEntry, hwIgmpSnoopingGroupPolicyVlanID=hwIgmpSnoopingGroupPolicyVlanID, hwIgmpSnoopingGroupLimitEntry=hwIgmpSnoopingGroupLimitEntry, hwSentIGMPSQueryNum=hwSentIGMPSQueryNum, hwIgmpSnoopingGroupPolicyStatus=hwIgmpSnoopingGroupPolicyStatus, hwLswIgmpsnoopingMibObject=hwLswIgmpsnoopingMibObject, hwRecvIGMPSQueryNum=hwRecvIGMPSQueryNum, hwIgmpSnoopingGroupIfIndex=hwIgmpSnoopingGroupIfIndex, hwLswIgmpsnoopingMib=hwLswIgmpsnoopingMib, hwIgmpSnoopingVlanEnabled=hwIgmpSnoopingVlanEnabled, hwIgmpSnoopingClearStats=hwIgmpSnoopingClearStats, hwIgmpSnoopingStatsObjects=hwIgmpSnoopingStatsObjects, hwRecvErrorIGMPPacketNum=hwRecvErrorIGMPPacketNum, PYSNMP_MODULE_ID=hwLswIgmpsnoopingMib, hwIgmpSnoopingFastLeaveIfIndex=hwIgmpSnoopingFastLeaveIfIndex, hwRecvIGMPLeaveNum=hwRecvIGMPLeaveNum, hwIgmpSnoopingGroupLimitNumber=hwIgmpSnoopingGroupLimitNumber, hwIgmpSnoopingNonFloodingStatus=hwIgmpSnoopingNonFloodingStatus, hwIgmpSnoopingGroupLimitTable=hwIgmpSnoopingGroupLimitTable, hwIgmpSnoopingFastLeaveTable=hwIgmpSnoopingFastLeaveTable, hwRecvIGMPGQueryNum=hwRecvIGMPGQueryNum, EnabledStatus=EnabledStatus, hwIgmpSnoopingVlanStatusEntry=hwIgmpSnoopingVlanStatusEntry, hwIgmpSnoopingGroupPolicyIfIndex=hwIgmpSnoopingGroupPolicyIfIndex, hwIgmpSnoopingFastLeaveStatus=hwIgmpSnoopingFastLeaveStatus, hwIgmpSnoopingVlanID=hwIgmpSnoopingVlanID, hwIgmpSnoopingGroupPolicyTable=hwIgmpSnoopingGroupPolicyTable, hwIgmpSnoopingVlanStatusTable=hwIgmpSnoopingVlanStatusTable, hwIgmpSnoopingFastLeaveEntry=hwIgmpSnoopingFastLeaveEntry, hwRecvIGMPV1ReportNum=hwRecvIGMPV1ReportNum)
true
true
f71101a1784782e57cee2028ca80b2be898cb6d5
13,153
py
Python
libs/telegram/ext/picklepersistence.py
rocketbot-cl/Telegram
e44713f6eb15460d4609d844ed5cccbbc84d4309
[ "MIT" ]
null
null
null
libs/telegram/ext/picklepersistence.py
rocketbot-cl/Telegram
e44713f6eb15460d4609d844ed5cccbbc84d4309
[ "MIT" ]
null
null
null
libs/telegram/ext/picklepersistence.py
rocketbot-cl/Telegram
e44713f6eb15460d4609d844ed5cccbbc84d4309
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2020 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. """This module contains the PicklePersistence class.""" import pickle from collections import defaultdict from copy import deepcopy from typing import Any, DefaultDict, Dict, Optional, Tuple from telegram.ext import BasePersistence from telegram.utils.types import ConversationDict class PicklePersistence(BasePersistence): """Using python's builtin pickle for making you bot persistent. Warning: :class:`PicklePersistence` will try to replace :class:`telegram.Bot` instances by :attr:`REPLACED_BOT` and insert the bot set with :meth:`telegram.ext.BasePersistence.set_bot` upon loading of the data. This is to ensure that changes to the bot apply to the saved objects, too. If you change the bots token, this may lead to e.g. ``Chat not found`` errors. For the limitations on replacing bots see :meth:`telegram.ext.BasePersistence.replace_bot` and :meth:`telegram.ext.BasePersistence.insert_bot`. Attributes: filename (:obj:`str`): The filename for storing the pickle files. When :attr:`single_file` is :obj:`False` this will be used as a prefix. store_user_data (:obj:`bool`): Optional. Whether user_data should be saved by this persistence class. store_chat_data (:obj:`bool`): Optional. Whether user_data should be saved by this persistence class. store_bot_data (:obj:`bool`): Optional. Whether bot_data should be saved by this persistence class. single_file (:obj:`bool`): Optional. When :obj:`False` will store 3 separate files of `filename_user_data`, `filename_chat_data` and `filename_conversations`. Default is :obj:`True`. on_flush (:obj:`bool`, optional): When :obj:`True` will only save to file when :meth:`flush` is called and keep data in memory until that happens. When :obj:`False` will store data on any transaction *and* on call to :meth:`flush`. Default is :obj:`False`. Args: filename (:obj:`str`): The filename for storing the pickle files. When :attr:`single_file` is :obj:`False` this will be used as a prefix. store_user_data (:obj:`bool`, optional): Whether user_data should be saved by this persistence class. Default is :obj:`True`. store_chat_data (:obj:`bool`, optional): Whether user_data should be saved by this persistence class. Default is :obj:`True`. store_bot_data (:obj:`bool`, optional): Whether bot_data should be saved by this persistence class. Default is :obj:`True` . single_file (:obj:`bool`, optional): When :obj:`False` will store 3 separate files of `filename_user_data`, `filename_chat_data` and `filename_conversations`. Default is :obj:`True`. on_flush (:obj:`bool`, optional): When :obj:`True` will only save to file when :meth:`flush` is called and keep data in memory until that happens. When :obj:`False` will store data on any transaction *and* on call to :meth:`flush`. Default is :obj:`False`. """ def __init__( self, filename: str, store_user_data: bool = True, store_chat_data: bool = True, store_bot_data: bool = True, single_file: bool = True, on_flush: bool = False, ): super().__init__( store_user_data=store_user_data, store_chat_data=store_chat_data, store_bot_data=store_bot_data, ) self.filename = filename self.single_file = single_file self.on_flush = on_flush self.user_data: Optional[DefaultDict[int, Dict]] = None self.chat_data: Optional[DefaultDict[int, Dict]] = None self.bot_data: Optional[Dict] = None self.conversations: Optional[Dict[str, Dict[Tuple, Any]]] = None def load_singlefile(self) -> None: try: filename = self.filename with open(self.filename, "rb") as file: data = pickle.load(file) self.user_data = defaultdict(dict, data['user_data']) self.chat_data = defaultdict(dict, data['chat_data']) # For backwards compatibility with files not containing bot data self.bot_data = data.get('bot_data', {}) self.conversations = data['conversations'] except IOError: self.conversations = dict() self.user_data = defaultdict(dict) self.chat_data = defaultdict(dict) self.bot_data = {} except pickle.UnpicklingError as exc: raise TypeError(f"File {filename} does not contain valid pickle data") from exc except Exception as exc: raise TypeError(f"Something went wrong unpickling {filename}") from exc @staticmethod def load_file(filename: str) -> Any: try: with open(filename, "rb") as file: return pickle.load(file) except IOError: return None except pickle.UnpicklingError as exc: raise TypeError(f"File {filename} does not contain valid pickle data") from exc except Exception as exc: raise TypeError(f"Something went wrong unpickling {filename}") from exc def dump_singlefile(self) -> None: with open(self.filename, "wb") as file: data = { 'conversations': self.conversations, 'user_data': self.user_data, 'chat_data': self.chat_data, 'bot_data': self.bot_data, } pickle.dump(data, file) @staticmethod def dump_file(filename: str, data: Any) -> None: with open(filename, "wb") as file: pickle.dump(data, file) def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]: """Returns the user_data from the pickle file if it exists or an empty :obj:`defaultdict`. Returns: :obj:`defaultdict`: The restored user data. """ if self.user_data: pass elif not self.single_file: filename = f"{self.filename}_user_data" data = self.load_file(filename) if not data: data = defaultdict(dict) else: data = defaultdict(dict, data) self.user_data = data else: self.load_singlefile() return deepcopy(self.user_data) # type: ignore[arg-type] def get_chat_data(self) -> DefaultDict[int, Dict[Any, Any]]: """Returns the chat_data from the pickle file if it exists or an empty :obj:`defaultdict`. Returns: :obj:`defaultdict`: The restored chat data. """ if self.chat_data: pass elif not self.single_file: filename = f"{self.filename}_chat_data" data = self.load_file(filename) if not data: data = defaultdict(dict) else: data = defaultdict(dict, data) self.chat_data = data else: self.load_singlefile() return deepcopy(self.chat_data) # type: ignore[arg-type] def get_bot_data(self) -> Dict[Any, Any]: """Returns the bot_data from the pickle file if it exists or an empty :obj:`dict`. Returns: :obj:`dict`: The restored bot data. """ if self.bot_data: pass elif not self.single_file: filename = f"{self.filename}_bot_data" data = self.load_file(filename) if not data: data = {} self.bot_data = data else: self.load_singlefile() return deepcopy(self.bot_data) # type: ignore[arg-type] def get_conversations(self, name: str) -> ConversationDict: """Returns the conversations from the pickle file if it exsists or an empty dict. Args: name (:obj:`str`): The handlers name. Returns: :obj:`dict`: The restored conversations for the handler. """ if self.conversations: pass elif not self.single_file: filename = f"{self.filename}_conversations" data = self.load_file(filename) if not data: data = {name: {}} self.conversations = data else: self.load_singlefile() return self.conversations.get(name, {}).copy() # type: ignore[union-attr] def update_conversation( self, name: str, key: Tuple[int, ...], new_state: Optional[object] ) -> None: """Will update the conversations for the given handler and depending on :attr:`on_flush` save the pickle file. Args: name (:obj:`str`): The handler's name. key (:obj:`tuple`): The key the state is changed for. new_state (:obj:`tuple` | :obj:`any`): The new state for the given key. """ if not self.conversations: self.conversations = dict() if self.conversations.setdefault(name, {}).get(key) == new_state: return self.conversations[name][key] = new_state if not self.on_flush: if not self.single_file: filename = f"{self.filename}_conversations" self.dump_file(filename, self.conversations) else: self.dump_singlefile() def update_user_data(self, user_id: int, data: Dict) -> None: """Will update the user_data and depending on :attr:`on_flush` save the pickle file. Args: user_id (:obj:`int`): The user the data might have been changed for. data (:obj:`dict`): The :attr:`telegram.ext.dispatcher.user_data` [user_id]. """ if self.user_data is None: self.user_data = defaultdict(dict) if self.user_data.get(user_id) == data: return self.user_data[user_id] = data if not self.on_flush: if not self.single_file: filename = f"{self.filename}_user_data" self.dump_file(filename, self.user_data) else: self.dump_singlefile() def update_chat_data(self, chat_id: int, data: Dict) -> None: """Will update the chat_data and depending on :attr:`on_flush` save the pickle file. Args: chat_id (:obj:`int`): The chat the data might have been changed for. data (:obj:`dict`): The :attr:`telegram.ext.dispatcher.chat_data` [chat_id]. """ if self.chat_data is None: self.chat_data = defaultdict(dict) if self.chat_data.get(chat_id) == data: return self.chat_data[chat_id] = data if not self.on_flush: if not self.single_file: filename = f"{self.filename}_chat_data" self.dump_file(filename, self.chat_data) else: self.dump_singlefile() def update_bot_data(self, data: Dict) -> None: """Will update the bot_data and depending on :attr:`on_flush` save the pickle file. Args: data (:obj:`dict`): The :attr:`telegram.ext.dispatcher.bot_data`. """ if self.bot_data == data: return self.bot_data = data.copy() if not self.on_flush: if not self.single_file: filename = f"{self.filename}_bot_data" self.dump_file(filename, self.bot_data) else: self.dump_singlefile() def flush(self) -> None: """Will save all data in memory to pickle file(s).""" if self.single_file: if self.user_data or self.chat_data or self.bot_data or self.conversations: self.dump_singlefile() else: if self.user_data: self.dump_file(f"{self.filename}_user_data", self.user_data) if self.chat_data: self.dump_file(f"{self.filename}_chat_data", self.chat_data) if self.bot_data: self.dump_file(f"{self.filename}_bot_data", self.bot_data) if self.conversations: self.dump_file(f"{self.filename}_conversations", self.conversations)
41.755556
99
0.606402
import pickle from collections import defaultdict from copy import deepcopy from typing import Any, DefaultDict, Dict, Optional, Tuple from telegram.ext import BasePersistence from telegram.utils.types import ConversationDict class PicklePersistence(BasePersistence): def __init__( self, filename: str, store_user_data: bool = True, store_chat_data: bool = True, store_bot_data: bool = True, single_file: bool = True, on_flush: bool = False, ): super().__init__( store_user_data=store_user_data, store_chat_data=store_chat_data, store_bot_data=store_bot_data, ) self.filename = filename self.single_file = single_file self.on_flush = on_flush self.user_data: Optional[DefaultDict[int, Dict]] = None self.chat_data: Optional[DefaultDict[int, Dict]] = None self.bot_data: Optional[Dict] = None self.conversations: Optional[Dict[str, Dict[Tuple, Any]]] = None def load_singlefile(self) -> None: try: filename = self.filename with open(self.filename, "rb") as file: data = pickle.load(file) self.user_data = defaultdict(dict, data['user_data']) self.chat_data = defaultdict(dict, data['chat_data']) self.bot_data = data.get('bot_data', {}) self.conversations = data['conversations'] except IOError: self.conversations = dict() self.user_data = defaultdict(dict) self.chat_data = defaultdict(dict) self.bot_data = {} except pickle.UnpicklingError as exc: raise TypeError(f"File {filename} does not contain valid pickle data") from exc except Exception as exc: raise TypeError(f"Something went wrong unpickling {filename}") from exc @staticmethod def load_file(filename: str) -> Any: try: with open(filename, "rb") as file: return pickle.load(file) except IOError: return None except pickle.UnpicklingError as exc: raise TypeError(f"File {filename} does not contain valid pickle data") from exc except Exception as exc: raise TypeError(f"Something went wrong unpickling {filename}") from exc def dump_singlefile(self) -> None: with open(self.filename, "wb") as file: data = { 'conversations': self.conversations, 'user_data': self.user_data, 'chat_data': self.chat_data, 'bot_data': self.bot_data, } pickle.dump(data, file) @staticmethod def dump_file(filename: str, data: Any) -> None: with open(filename, "wb") as file: pickle.dump(data, file) def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]: if self.user_data: pass elif not self.single_file: filename = f"{self.filename}_user_data" data = self.load_file(filename) if not data: data = defaultdict(dict) else: data = defaultdict(dict, data) self.user_data = data else: self.load_singlefile() return deepcopy(self.user_data) def get_chat_data(self) -> DefaultDict[int, Dict[Any, Any]]: if self.chat_data: pass elif not self.single_file: filename = f"{self.filename}_chat_data" data = self.load_file(filename) if not data: data = defaultdict(dict) else: data = defaultdict(dict, data) self.chat_data = data else: self.load_singlefile() return deepcopy(self.chat_data) def get_bot_data(self) -> Dict[Any, Any]: if self.bot_data: pass elif not self.single_file: filename = f"{self.filename}_bot_data" data = self.load_file(filename) if not data: data = {} self.bot_data = data else: self.load_singlefile() return deepcopy(self.bot_data) def get_conversations(self, name: str) -> ConversationDict: if self.conversations: pass elif not self.single_file: filename = f"{self.filename}_conversations" data = self.load_file(filename) if not data: data = {name: {}} self.conversations = data else: self.load_singlefile() return self.conversations.get(name, {}).copy() def update_conversation( self, name: str, key: Tuple[int, ...], new_state: Optional[object] ) -> None: if not self.conversations: self.conversations = dict() if self.conversations.setdefault(name, {}).get(key) == new_state: return self.conversations[name][key] = new_state if not self.on_flush: if not self.single_file: filename = f"{self.filename}_conversations" self.dump_file(filename, self.conversations) else: self.dump_singlefile() def update_user_data(self, user_id: int, data: Dict) -> None: if self.user_data is None: self.user_data = defaultdict(dict) if self.user_data.get(user_id) == data: return self.user_data[user_id] = data if not self.on_flush: if not self.single_file: filename = f"{self.filename}_user_data" self.dump_file(filename, self.user_data) else: self.dump_singlefile() def update_chat_data(self, chat_id: int, data: Dict) -> None: if self.chat_data is None: self.chat_data = defaultdict(dict) if self.chat_data.get(chat_id) == data: return self.chat_data[chat_id] = data if not self.on_flush: if not self.single_file: filename = f"{self.filename}_chat_data" self.dump_file(filename, self.chat_data) else: self.dump_singlefile() def update_bot_data(self, data: Dict) -> None: if self.bot_data == data: return self.bot_data = data.copy() if not self.on_flush: if not self.single_file: filename = f"{self.filename}_bot_data" self.dump_file(filename, self.bot_data) else: self.dump_singlefile() def flush(self) -> None: if self.single_file: if self.user_data or self.chat_data or self.bot_data or self.conversations: self.dump_singlefile() else: if self.user_data: self.dump_file(f"{self.filename}_user_data", self.user_data) if self.chat_data: self.dump_file(f"{self.filename}_chat_data", self.chat_data) if self.bot_data: self.dump_file(f"{self.filename}_bot_data", self.bot_data) if self.conversations: self.dump_file(f"{self.filename}_conversations", self.conversations)
true
true
f71101f5b978b56c3a06bde91ef74d4fd7739c4f
1,811
py
Python
main.py
arthurvergacas/lineuzinho
6505b8b576cf6b8935fba0fab979e71bd454f8c3
[ "MIT" ]
null
null
null
main.py
arthurvergacas/lineuzinho
6505b8b576cf6b8935fba0fab979e71bd454f8c3
[ "MIT" ]
null
null
null
main.py
arthurvergacas/lineuzinho
6505b8b576cf6b8935fba0fab979e71bd454f8c3
[ "MIT" ]
null
null
null
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import logging from lineuzinho import Lineuzinho def main(): logging.getLogger(__name__) logging.basicConfig(format='%(asctime)s [%(levelname)s]: %(message)s', level=logging.INFO) lineuzinho = Lineuzinho() updater = Updater(lineuzinho.API_TOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler("start", lineuzinho.start)) dp.add_handler(CommandHandler("links", lineuzinho.getGeneralRelevantLinks)) dp.add_handler(CommandHandler("repo", lineuzinho.getRepo)) dp.add_handler(CommandHandler("contatinhos", lineuzinho.getContatinhosLink)) dp.add_handler(CommandHandler("feijao", lineuzinho.getBeanFlavor)) dp.add_handler(CommandHandler("docs", lineuzinho.getDocsChannel)) dp.add_handler(CommandHandler("save", lineuzinho.saveMessage)) dp.add_handler(CommandHandler("help", lineuzinho.getHelpText)) dp.add_handler(CommandHandler("pi_rank", lineuzinho.getPiRanking)) dp.add_handler(CommandHandler("pi_index", lineuzinho.publishUserPiRanking)) dp.add_handler(CommandHandler("birthday", lineuzinho.getBirthdaySongAudio)) dp.add_handler(CommandHandler("beni", lineuzinho.getBeniSongAudio)) dp.add_handler(CommandHandler("ain", lineuzinho.getRandomAin)) dp.add_handler(CommandHandler("grupos", lineuzinho.getSubjectsGroupsLinks)) dp.add_handler(CommandHandler("meet", lineuzinho.getSubjectMeetLinks)) dp.add_handler(MessageHandler(Filters.text, lineuzinho.agiotar)) dp.add_handler(MessageHandler(Filters.status_update.new_chat_members, lineuzinho.greet)) updater.start_polling() logging.info("=== Lineuzinho up&running! ===") updater.idle() logging.info("=== Lineuzinho shutting down :( ===") if __name__ == "__main__": main()
45.275
94
0.764771
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import logging from lineuzinho import Lineuzinho def main(): logging.getLogger(__name__) logging.basicConfig(format='%(asctime)s [%(levelname)s]: %(message)s', level=logging.INFO) lineuzinho = Lineuzinho() updater = Updater(lineuzinho.API_TOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler("start", lineuzinho.start)) dp.add_handler(CommandHandler("links", lineuzinho.getGeneralRelevantLinks)) dp.add_handler(CommandHandler("repo", lineuzinho.getRepo)) dp.add_handler(CommandHandler("contatinhos", lineuzinho.getContatinhosLink)) dp.add_handler(CommandHandler("feijao", lineuzinho.getBeanFlavor)) dp.add_handler(CommandHandler("docs", lineuzinho.getDocsChannel)) dp.add_handler(CommandHandler("save", lineuzinho.saveMessage)) dp.add_handler(CommandHandler("help", lineuzinho.getHelpText)) dp.add_handler(CommandHandler("pi_rank", lineuzinho.getPiRanking)) dp.add_handler(CommandHandler("pi_index", lineuzinho.publishUserPiRanking)) dp.add_handler(CommandHandler("birthday", lineuzinho.getBirthdaySongAudio)) dp.add_handler(CommandHandler("beni", lineuzinho.getBeniSongAudio)) dp.add_handler(CommandHandler("ain", lineuzinho.getRandomAin)) dp.add_handler(CommandHandler("grupos", lineuzinho.getSubjectsGroupsLinks)) dp.add_handler(CommandHandler("meet", lineuzinho.getSubjectMeetLinks)) dp.add_handler(MessageHandler(Filters.text, lineuzinho.agiotar)) dp.add_handler(MessageHandler(Filters.status_update.new_chat_members, lineuzinho.greet)) updater.start_polling() logging.info("=== Lineuzinho up&running! ===") updater.idle() logging.info("=== Lineuzinho shutting down :( ===") if __name__ == "__main__": main()
true
true
f711029eeb4b839cbf58c517115a6b12f9456c73
1,128
py
Python
sample-viewer-api/src/static/data/exploratory_scripts/2019-06-03_bonnie_plasmasamples.py
cvisb/cvisb_data
81ebf22782f2c44f8aa8ab9437cc4fb54248c3ed
[ "MIT" ]
2
2020-02-18T08:16:45.000Z
2021-04-11T18:58:02.000Z
sample-viewer-api/src/static/data/exploratory_scripts/2019-06-03_bonnie_plasmasamples.py
cvisb/cvisb_data
81ebf22782f2c44f8aa8ab9437cc4fb54248c3ed
[ "MIT" ]
47
2019-09-30T22:26:36.000Z
2021-11-17T00:34:38.000Z
sample-viewer-api/src/static/data/exploratory_scripts/2019-06-03_bonnie_plasmasamples.py
cvisb/cvisb_data
81ebf22782f2c44f8aa8ab9437cc4fb54248c3ed
[ "MIT" ]
1
2020-07-01T21:15:18.000Z
2020-07-01T21:15:18.000Z
# Goal: get ebola/Lassa for Bonnie's plasma samples. # Simple clean and merge import pandas as pd import os os.chdir("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/") import helpers df = pd.read_excel("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/input_data/sample_rosters/one_offs/CViSB Plasma Samples_Bonnie_2019-06-03.xlsx") df.shape df['privatePatientID'] = df["Sample ID"].apply(helpers.interpretID) # id dictionary ids = pd.read_json("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/output_data/patients/patients_2019-06-03_PRIVATE_dict.json") ids.reset_index(inplace=True) ids.head() merged = pd.merge(df, ids, how="left", left_on="privatePatientID", right_on="index", indicator=True) merged._merge.value_counts() merged[merged._merge == "left_only"] merged = merged[['Sample ID', "Date of collection", "Sample type", "cohort", "elisa", "sID", "gID", "patientID"]] merged.to_csv("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/input_data/sample_rosters/one_offs/2019-06-03_CViSBplasma_Bonnie.csv", index = False)
38.896552
171
0.777482
# Simple clean and merge import pandas as pd import os os.chdir("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/") import helpers df = pd.read_excel("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/input_data/sample_rosters/one_offs/CViSB Plasma Samples_Bonnie_2019-06-03.xlsx") df.shape df['privatePatientID'] = df["Sample ID"].apply(helpers.interpretID) # id dictionary ids = pd.read_json("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/output_data/patients/patients_2019-06-03_PRIVATE_dict.json") ids.reset_index(inplace=True) ids.head() merged = pd.merge(df, ids, how="left", left_on="privatePatientID", right_on="index", indicator=True) merged._merge.value_counts() merged[merged._merge == "left_only"] merged = merged[['Sample ID', "Date of collection", "Sample type", "cohort", "elisa", "sID", "gID", "patientID"]] merged.to_csv("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/input_data/sample_rosters/one_offs/2019-06-03_CViSBplasma_Bonnie.csv", index = False)
true
true
f711030e9cb47d589d7ef40dd62c7ee7b174a532
27,663
py
Python
src/tests/Common/scripts/run-pmi-diffs.py
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
9,402
2019-11-25T23:26:24.000Z
2022-03-31T23:19:41.000Z
src/tests/Common/scripts/run-pmi-diffs.py
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
37,522
2019-11-25T23:30:32.000Z
2022-03-31T23:58:30.000Z
src/tests/Common/scripts/run-pmi-diffs.py
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
3,629
2019-11-25T23:29:16.000Z
2022-03-31T21:52:28.000Z
#!/usr/bin/env python # # Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. # ## # Title :run-pmi-diffs.py # # Notes: # # TODO: Instead of downloading and extracting the dotnet CLI, can we convert # to using init-tools.cmd/sh and the Tools/dotnetcli "last known good" # version? (This maybe should be done for format.py as well.) # # Script to automate running PMI diffs on a pull request # ########################################################################## ########################################################################## import argparse import distutils.dir_util import os import re import shutil import subprocess import urllib import sys import tarfile import zipfile # Version specific imports if sys.version_info.major < 3: import urllib else: import urllib.request sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "scripts")) from coreclr_arguments import * ########################################################################## # Globals ########################################################################## testing = False Coreclr_url = 'https://github.com/dotnet/coreclr.git' Jitutils_url = 'https://github.com/dotnet/jitutils.git' # The Docker file and possibly options should be hoisted out to a text file to be shared between scripts. Docker_name_arm32 = 'mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-14.04-cross-e435274-20180426002420' Docker_opts_arm32 = '-e ROOTFS_DIR=/crossrootfs/arm' Docker_name_arm64 = 'mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-16.04-cross-arm64-a3ae44b-20180315221921' Docker_opts_arm64 = '-e ROOTFS_DIR=/crossrootfs/arm64' Is_illumos = ('illumos' in subprocess.Popen(["uname", "-o"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode('utf-8')) # This should be factored out of build.sh Unix_name_map = { 'Linux': 'Linux', 'Darwin': 'OSX', 'FreeBSD': 'FreeBSD', 'OpenBSD': 'OpenBSD', 'NetBSD': 'NetBSD', 'SunOS': 'illumos' if Is_illumos else 'Solaris' } Is_windows = (os.name == 'nt') Clr_os = 'windows' if Is_windows else Unix_name_map[os.uname()[0]] ########################################################################## # Delete protocol ########################################################################## def del_rw(action, name, exc): os.chmod(name, 0o651) os.remove(name) ########################################################################## # Argument Parser ########################################################################## description = 'Tool to generate JIT assembly diffs from the CoreCLR repo' parser = argparse.ArgumentParser(description=description) # base_root is normally expected to be None, in which case we'll clone the # coreclr tree and build it. If base_root is passed, we'll use it, and not # clone or build the base. parser.add_argument('-arch', dest='arch', default='x64') parser.add_argument('-ci_arch', dest='ci_arch', default=None) parser.add_argument('-build_type', dest='build_type', default='Checked') parser.add_argument('-base_root', dest='base_root', default=None) parser.add_argument('-diff_root', dest='diff_root', default=None) parser.add_argument('-scratch_root', dest='scratch_root', default=None) parser.add_argument('--skip_baseline_build', dest='skip_baseline_build', action='store_true', default=False) parser.add_argument('--skip_diffs', dest='skip_diffs', action='store_true', default=False) parser.add_argument('-target_branch', dest='target_branch', default='main') parser.add_argument('-commit_hash', dest='commit_hash', default=None) ########################################################################## # Class to change the current directory, and automatically restore the # directory back to what it used to be, on exit. ########################################################################## class ChangeDir: def __init__(self, dir): self.dir = dir self.cwd = None def __enter__(self): self.cwd = os.getcwd() log('[cd] %s' % self.dir) if not testing: os.chdir(self.dir) def __exit__(self, exc_type, exc_val, exc_tb): log('[cd] %s' % self.cwd) if not testing: os.chdir(self.cwd) ########################################################################## # Helper Functions ########################################################################## def validate_args(args): """ Validate all of the arguments parsed. Args: args (argparser.ArgumentParser) : Args parsed by the argument parser. Returns: args (CoreclrArguments) : Args parsed Notes: If the arguments are valid then return them all in a tuple. If not, raise an exception stating x argument is incorrect. """ coreclr_setup_args = CoreclrArguments(args, require_built_test_dir=False, require_built_core_root=True, require_built_product_dir=False) coreclr_setup_args.verify(args, "base_root", lambda directory: os.path.isdir(directory) if directory is not None else True, "Base root is not a valid directory") coreclr_setup_args.verify(args, "diff_root", lambda directory: os.path.isdir(directory) if directory is not None else True, "Diff root is not a valid directory", modify_arg=lambda directory: nth_dirname(os.path.abspath(sys.argv[0]), 3) if directory is None else os.path.abspath(directory)) coreclr_setup_args.verify(args, "scratch_root", lambda unused: True, "Error setting scratch_root", modify_arg=lambda directory: os.path.join(coreclr_setup_args.diff_root, '_', 'pmi') if directory is None else os.path.abspath(directory)) coreclr_setup_args.verify(args, "skip_baseline_build", lambda unused: True, "Error setting baseline build") coreclr_setup_args.verify(args, "skip_diffs", lambda unused: True, "Error setting skip_diffs") coreclr_setup_args.verify(args, "target_branch", lambda unused: True, "Error setting target_branch") coreclr_setup_args.verify(args, "commit_hash", lambda unused: True, "Error setting commit_hash") coreclr_setup_args.verify(args, "ci_arch", lambda ci_arch: ci_arch in coreclr_setup_args.valid_arches + ['x86_arm_altjit', 'x64_arm64_altjit'], "Error setting ci_arch") args = ( coreclr_setup_args.arch, coreclr_setup_args.ci_arch, coreclr_setup_args.build_type, coreclr_setup_args.base_root, coreclr_setup_args.diff_root, coreclr_setup_args.scratch_root, coreclr_setup_args.skip_baseline_build, coreclr_setup_args.skip_diffs, coreclr_setup_args.target_branch, coreclr_setup_args.commit_hash ) log('Configuration:') log(' arch: %s' % coreclr_setup_args.arch) log(' ci_arch: %s' % coreclr_setup_args.ci_arch) log(' build_type: %s' % coreclr_setup_args.build_type) log(' base_root: %s' % coreclr_setup_args.base_root) log(' diff_root: %s' % coreclr_setup_args.diff_root) log(' scratch_root: %s' % coreclr_setup_args.scratch_root) log(' skip_baseline_build: %s' % coreclr_setup_args.skip_baseline_build) log(' skip_diffs: %s' % coreclr_setup_args.skip_diffs) log(' target_branch: %s' % coreclr_setup_args.target_branch) log(' commit_hash: %s' % coreclr_setup_args.commit_hash) return args def nth_dirname(path, n): """ Find the Nth parent directory of the given path Args: path (str): path name containing at least N components n (int): num of basenames to remove Returns: outpath (str): path with the last n components removed Notes: If n is 0, path is returned unmodified """ assert n >= 0 for i in range(0, n): path = os.path.dirname(path) return path def log(message): """ Print logging information Args: message (str): message to be printed """ print('[%s]: %s' % (sys.argv[0], message)) def copy_files(source_dir, target_dir): """ Copy any files in the source_dir to the target_dir. The copy is not recursive. The directories must already exist. Args: source_dir (str): source directory path target_dir (str): target directory path Returns: Nothing """ global testing assert os.path.isdir(source_dir) assert os.path.isdir(target_dir) for source_filename in os.listdir(source_dir): source_pathname = os.path.join(source_dir, source_filename) if os.path.isfile(source_pathname): target_pathname = os.path.join(target_dir, source_filename) log('Copy: %s => %s' % (source_pathname, target_pathname)) if not testing: shutil.copy2(source_pathname, target_pathname) def run_command(command, command_env): """ Run a command (process) in a given environment. stdout/stderr are output piped through. Args: command (array): the command to run, with components of the command as separate elements. command_env (map): environment in which the command should be run Returns: The return code of the command. """ returncode = 0 log('Invoking: %s' % (' '.join(command))) if not testing: proc = subprocess.Popen(command, env=command_env) output,error = proc.communicate() returncode = proc.returncode if returncode != 0: log('Return code = %s' % returncode) return returncode ########################################################################## # Do baseline build: # 1. determine appropriate commit, # 2. clone coreclr, # 3. do build ########################################################################## def baseline_build(): if not testing: if os.path.isdir(baseCoreClrPath): log('Removing existing tree: %s' % baseCoreClrPath) shutil.rmtree(baseCoreClrPath, onerror=del_rw) # Find the baseline commit # Clone at that commit command = 'git clone -b %s --single-branch %s %s' % ( target_branch, Coreclr_url, baseCoreClrPath) log(command) returncode = 0 if testing else os.system(command) if returncode != 0: log('ERROR: git clone failed') return 1 # Change directory to the baseline root with ChangeDir(baseCoreClrPath): # Set up for possible docker usage scriptPath = '.' buildOpts = '' dockerCmd = '' if not Is_windows and (arch == 'arm' or arch == 'arm64'): # Linux arm and arm64 builds are cross-compilation builds using Docker. if arch == 'arm': dockerFile = Docker_name_arm32 dockerOpts = Docker_opts_arm32 else: # arch == 'arm64' dockerFile = Docker_name_arm64 dockerOpts = Docker_opts_arm64 dockerCmd = 'docker run -i --rm -v %s:%s -w %s %s %s ' % (baseCoreClrPath, baseCoreClrPath, baseCoreClrPath, dockerOpts, dockerFile) buildOpts = 'cross' scriptPath = baseCoreClrPath # Build a checked baseline jit if Is_windows: command = 'set __TestIntermediateDir=int&&build.cmd %s checked skiptests skipbuildpackages' % arch else: command = '%s%s/build.sh %s checked skipbuildpackages %s' % (dockerCmd, scriptPath, arch, buildOpts) log(command) returncode = 0 if testing else os.system(command) if returncode != 0: log('ERROR: build failed') return 1 # Build the layout (Core_Root) directory # For Windows, invoke build-test.cmd to restore packages before generating the layout. if Is_windows: command = 'build-test.cmd %s %s skipmanaged skipnative' % (build_type, arch) log(command) returncode = 0 if testing else os.system(command) if returncode != 0: log('ERROR: restoring packages failed') return 1 if Is_windows: command = 'tests\\runtest.cmd %s checked GenerateLayoutOnly' % arch else: command = '%s%s/build-test.sh %s checked generatelayoutonly' % (dockerCmd, scriptPath, arch) log(command) returncode = 0 if testing else os.system(command) if returncode != 0: log('ERROR: generating layout failed') return 1 return 0 ########################################################################## # Do PMI diff run: # 1. download dotnet CLI (needed by jitutils) # 2. clone jitutils repo # 3. build jitutils # 4. run PMI asm generation on baseline and diffs # 5. run jit-analyze to compare baseline and diff ########################################################################## def do_pmi_diffs(): global baseCoreClrPath # Setup scratch directories. Names are short to avoid path length problems on Windows. dotnetcliPath = os.path.abspath(os.path.join(scratch_root, 'cli')) jitutilsPath = os.path.abspath(os.path.join(scratch_root, 'jitutils')) asmRootPath = os.path.abspath(os.path.join(scratch_root, 'asm')) dotnet_tool = 'dotnet.exe' if Is_windows else 'dotnet' # Make sure the temporary directories do not exist. If they do already, delete them. if not testing: # If we can't delete the dotnet tree, it might be because a previous run failed or was # cancelled, and the build servers are still running. Try to stop it if that happens. if os.path.isdir(dotnetcliPath): try: log('Removing existing tree: %s' % dotnetcliPath) shutil.rmtree(dotnetcliPath, onerror=del_rw) except OSError: if os.path.isfile(os.path.join(dotnetcliPath, dotnet_tool)): log('Failed to remove existing tree; trying to shutdown the dotnet build servers before trying again.') # Looks like the dotnet too is still there; try to run it to shut down the build servers. temp_env = my_env temp_env["PATH"] = dotnetcliPath + os.pathsep + my_env["PATH"] log('Shutting down build servers') command = ["dotnet", "build-server", "shutdown"] returncode = run_command(command, temp_env) # Try again log('Trying again to remove existing tree: %s' % dotnetcliPath) shutil.rmtree(dotnetcliPath, onerror=del_rw) else: log('Failed to remove existing tree') return 1 if os.path.isdir(jitutilsPath): log('Removing existing tree: %s' % jitutilsPath) shutil.rmtree(jitutilsPath, onerror=del_rw) if os.path.isdir(asmRootPath): log('Removing existing tree: %s' % asmRootPath) shutil.rmtree(asmRootPath, onerror=del_rw) try: os.makedirs(dotnetcliPath) os.makedirs(jitutilsPath) os.makedirs(asmRootPath) except OSError: if not os.path.isdir(dotnetcliPath): log('ERROR: cannot create CLI install directory %s' % dotnetcliPath) return 1 if not os.path.isdir(jitutilsPath): log('ERROR: cannot create jitutils install directory %s' % jitutilsPath) return 1 if not os.path.isdir(asmRootPath): log('ERROR: cannot create asm directory %s' % asmRootPath) return 1 log('dotnet CLI install directory: %s' % dotnetcliPath) log('jitutils install directory: %s' % jitutilsPath) log('asm directory: %s' % asmRootPath) # Download .NET CLI log('Downloading .NET CLI') dotnetcliUrl = "" dotnetcliFilename = "" if Clr_os == 'Linux' and arch == 'x64': dotnetcliUrl = "https://dotnetcli.azureedge.net/dotnet/Sdk/2.1.402/dotnet-sdk-2.1.402-linux-x64.tar.gz" elif Clr_os == 'Linux' and arch == 'arm': dotnetcliUrl = "https://dotnetcli.blob.core.windows.net/dotnet/Sdk/release/2.1.4xx/dotnet-sdk-latest-linux-arm.tar.gz" elif Clr_os == 'Linux' and arch == 'arm64': # Use the latest (3.0) dotnet SDK. Earlier versions don't work. dotnetcliUrl = "https://dotnetcli.blob.core.windows.net/dotnet/Sdk/master/dotnet-sdk-latest-linux-arm64.tar.gz" elif Clr_os == 'OSX': dotnetcliUrl = "https://dotnetcli.azureedge.net/dotnet/Sdk/2.1.402/dotnet-sdk-2.1.402-osx-x64.tar.gz" elif Clr_os == 'windows': dotnetcliUrl = "https://dotnetcli.azureedge.net/dotnet/Sdk/2.1.402/dotnet-sdk-2.1.402-win-x64.zip" else: log('ERROR: unknown or unsupported OS (%s) architecture (%s) combination' % (Clr_os, arch)) return 1 if Is_windows: dotnetcliFilename = os.path.join(dotnetcliPath, 'dotnetcli-jitutils.zip') else: dotnetcliFilename = os.path.join(dotnetcliPath, 'dotnetcli-jitutils.tar.gz') log('Downloading: %s => %s' % (dotnetcliUrl, dotnetcliFilename)) if not testing: urlretrieve = urllib.urlretrieve if sys.version_info.major < 3 else urllib.request.urlretrieve urlretrieve(dotnetcliUrl, dotnetcliFilename) if not os.path.isfile(dotnetcliFilename): log('ERROR: Did not download .NET CLI') return 1 # Install .NET CLI log('Unpacking .NET CLI') if not testing: if Is_windows: with zipfile.ZipFile(dotnetcliFilename, "r") as z: z.extractall(dotnetcliPath) else: tar = tarfile.open(dotnetcliFilename) tar.extractall(dotnetcliPath) tar.close() if not os.path.isfile(os.path.join(dotnetcliPath, dotnet_tool)): log('ERROR: did not extract .NET CLI from download') return 1 # Add dotnet CLI to PATH we'll use to spawn processes. log('Add %s to my PATH' % dotnetcliPath) my_env["PATH"] = dotnetcliPath + os.pathsep + my_env["PATH"] # To aid diagnosing problems, do "dotnet --info" to output to any capturing logfile. command = ["dotnet", "--info"] returncode = run_command(command, my_env) # Clone jitutils command = 'git clone -b main --single-branch %s %s' % (Jitutils_url, jitutilsPath) log(command) returncode = 0 if testing else os.system(command) if returncode != 0: log('ERROR: cannot clone jitutils'); return 1 # We're going to start running dotnet CLI commands. Unfortunately, once you've done that, # the dotnet CLI sticks around with a set of build server processes running. Put all this # in a try/finally, and stop the build servers under any circumstance. try: # # Build jitutils, including "dotnet restore" # # Change directory to the jitutils root with ChangeDir(jitutilsPath): # Do "dotnet restore" command = ["dotnet", "restore"] returncode = run_command(command, my_env) # Do build command = ['build.cmd', '-p'] if Is_windows else ['bash', './build.sh', '-p'] returncode = run_command(command, my_env) if returncode != 0: log('ERROR: jitutils build failed') return 1 jitutilsBin = os.path.join(jitutilsPath, "bin") if not testing and not os.path.isdir(jitutilsBin): log("ERROR: jitutils not correctly built") return 1 jitDiffPath = os.path.join(jitutilsBin, "jit-diff.dll") if not testing and not os.path.isfile(jitDiffPath): log("ERROR: jit-diff.dll not built") return 1 jitAnalyzePath = os.path.join(jitutilsBin, "jit-analyze.dll") if not testing and not os.path.isfile(jitAnalyzePath): log("ERROR: jit-analyze.dll not built") return 1 # Add jitutils bin to path for spawned processes log('Add %s to my PATH' % jitutilsBin) my_env["PATH"] = jitutilsBin + os.pathsep + my_env["PATH"] # # Run PMI asm diffs # # We want this script as a whole to return 0 if it succeeds (even if there are diffs) and only # return non-zero if there are any fatal errors. # # TO DO: figure out how to differentiate fatal errors and a return code indicating there are diffs, # and have the invoking netci.groovy code act differently for each case. # Generate the diffs # # Invoke command like: # dotnet c:\gh\jitutils\artifacts\jit-diff.dll diff --pmi --base --base_root f:\gh\coreclr12 --diff --diff_root f:\gh\coreclr10 --arch x64 --build Checked --tag 1 --noanalyze --output f:\output --corelib # # We pass --noanalyze and call jit-analyze manually. This isn't really necessary, but it does give us better output # due to https://github.com/dotnet/jitutils/issues/175. altjit_args = [] if ci_arch is not None and (ci_arch == 'x86_arm_altjit' or ci_arch == 'x64_arm64_altjit'): altjit_args = ["--altjit", "protononjit.dll"] # Over which set of assemblies should we generate asm? # TODO: parameterize this asm_source_args = ["--frameworks", "--benchmarks"] command = ["dotnet", jitDiffPath, "diff", "--pmi", "--base", "--base_root", baseCoreClrPath, "--diff", "--diff_root", diff_root, "--arch", arch, "--build", build_type, "--tag", "1", "--noanalyze", "--output", asmRootPath] + asm_source_args + altjit_args returncode = run_command(command, my_env) # We ignore the return code: it is non-zero if there are any diffs. If there are fatal errors here, we will miss them. # Question: does jit-diff distinguish between non-zero fatal error code and the existence of diffs? # Did we get any diffs? baseOutputDir = os.path.join(asmRootPath, "1", "base") if not testing and not os.path.isdir(baseOutputDir): log("ERROR: base asm not generated") return 1 diffOutputDir = os.path.join(asmRootPath, "1", "diff") if not testing and not os.path.isdir(diffOutputDir): log("ERROR: diff asm not generated") return 1 # Do the jit-analyze comparison: # dotnet c:\gh\jitutils\artifacts\jit-analyze.dll --base f:\output\diffs\1\base --recursive --diff f:\output\diffs\1\diff command = ["dotnet", jitAnalyzePath, "--recursive", "--base", baseOutputDir, "--diff", diffOutputDir] returncode = run_command(command, my_env) if returncode != 0: # This is not a fatal error. log('Compare: %s %s' % (baseOutputDir, diffOutputDir)) finally: # Shutdown the dotnet build servers before cleaning things up # TODO: make this shutdown happen anytime after we've run any 'dotnet' commands. I.e., try/finally style. log('Shutting down build servers') command = ["dotnet", "build-server", "shutdown"] returncode = run_command(command, my_env) return 0 ########################################################################## # Main ########################################################################## def main(args): global arch, ci_arch, build_type, base_root, diff_root, scratch_root, skip_baseline_build, skip_diffs, target_branch, commit_hash global my_env global base_layout_root global diff_layout_root global baseCoreClrPath global testing arch, ci_arch, build_type, base_root, diff_root, scratch_root, skip_baseline_build, skip_diffs, target_branch, commit_hash = validate_args(args) my_env = os.environ if not testing and not os.path.isdir(diff_root): log('ERROR: root directory for coreclr diff tree not found: %s' % diff_root) return 1 # Check the diff layout directory before going too far. diff_layout_root = os.path.join(diff_root, 'bin', 'tests', '%s.%s.%s' % (Clr_os, arch, build_type), 'Tests', 'Core_Root') if not testing and not os.path.isdir(diff_layout_root): log('ERROR: diff test overlay not found or is not a directory: %s' % diff_layout_root) return 1 # Create the scratch root directory if not testing: try: os.makedirs(scratch_root) except OSError: if not os.path.isdir(scratch_root): log('ERROR: cannot create scratch directory %s' % scratch_root) return 1 # Set up baseline root directory. If one is passed to us, we use it. Otherwise, we create # a temporary directory. if base_root is None: # Setup scratch directories. Names are short to avoid path length problems on Windows. # No need to create this directory now, as the "git clone" will do it later. baseCoreClrPath = os.path.abspath(os.path.join(scratch_root, 'base')) else: baseCoreClrPath = os.path.abspath(base_root) if not testing and not os.path.isdir(baseCoreClrPath): log('ERROR: base root directory not found or is not a directory: %s' % baseCoreClrPath) return 1 # Do the baseline build, if needed if not skip_baseline_build and base_root is None: returncode = baseline_build() if returncode != 0: return 1 # Check that the baseline root directory was created. base_layout_root = os.path.join(baseCoreClrPath, 'bin', 'tests', '%s.%s.%s' % (Clr_os, arch, build_type), 'Tests', 'Core_Root') if not testing and not os.path.isdir(base_layout_root): log('ERROR: baseline test overlay not found or is not a directory: %s' % base_layout_root) return 1 # Do the diff run, if needed if not skip_diffs: returncode = do_pmi_diffs() if returncode != 0: return 1 return 0 ########################################################################## # setup for Main ########################################################################## if __name__ == '__main__': Args = parser.parse_args(sys.argv[1:]) return_code = main(Args) log('Exit code: %s' % return_code) sys.exit(return_code)
38.420833
261
0.58468
true
true
f71103c169d8571edba137653f135725898352b3
4,523
py
Python
huaweicloud-sdk-apig/huaweicloudsdkapig/v2/model/list_apis_binded_to_request_throttling_policy_v2_response.py
githubmilesma/huaweicloud-sdk-python-v3
9d9449ed68a609ca65f0aa50b5b2a1c28445bf03
[ "Apache-2.0" ]
1
2021-04-16T07:59:28.000Z
2021-04-16T07:59:28.000Z
huaweicloud-sdk-apig/huaweicloudsdkapig/v2/model/list_apis_binded_to_request_throttling_policy_v2_response.py
Lencof/huaweicloud-sdk-python-v3
d13dc4e2830a83e295be6e4de021999b3376e34e
[ "Apache-2.0" ]
null
null
null
huaweicloud-sdk-apig/huaweicloudsdkapig/v2/model/list_apis_binded_to_request_throttling_policy_v2_response.py
Lencof/huaweicloud-sdk-python-v3
d13dc4e2830a83e295be6e4de021999b3376e34e
[ "Apache-2.0" ]
1
2022-01-17T02:24:18.000Z
2022-01-17T02:24:18.000Z
# coding: utf-8 import pprint import re import six from huaweicloudsdkcore.sdk_response import SdkResponse class ListApisBindedToRequestThrottlingPolicyV2Response(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'total': 'int', 'size': 'int', 'apis': 'list[ThrottleBindingApiResp]' } attribute_map = { 'total': 'total', 'size': 'size', 'apis': 'apis' } def __init__(self, total=None, size=None, apis=None): """ListApisBindedToRequestThrottlingPolicyV2Response - a model defined in huaweicloud sdk""" super().__init__() self._total = None self._size = None self._apis = None self.discriminator = None if total is not None: self.total = total if size is not None: self.size = size if apis is not None: self.apis = apis @property def total(self): """Gets the total of this ListApisBindedToRequestThrottlingPolicyV2Response. 满足条件的API总数 :return: The total of this ListApisBindedToRequestThrottlingPolicyV2Response. :rtype: int """ return self._total @total.setter def total(self, total): """Sets the total of this ListApisBindedToRequestThrottlingPolicyV2Response. 满足条件的API总数 :param total: The total of this ListApisBindedToRequestThrottlingPolicyV2Response. :type: int """ self._total = total @property def size(self): """Gets the size of this ListApisBindedToRequestThrottlingPolicyV2Response. 本次返回的API列表长度 :return: The size of this ListApisBindedToRequestThrottlingPolicyV2Response. :rtype: int """ return self._size @size.setter def size(self, size): """Sets the size of this ListApisBindedToRequestThrottlingPolicyV2Response. 本次返回的API列表长度 :param size: The size of this ListApisBindedToRequestThrottlingPolicyV2Response. :type: int """ self._size = size @property def apis(self): """Gets the apis of this ListApisBindedToRequestThrottlingPolicyV2Response. 本次查询返回的API列表 :return: The apis of this ListApisBindedToRequestThrottlingPolicyV2Response. :rtype: list[ThrottleBindingApiResp] """ return self._apis @apis.setter def apis(self, apis): """Sets the apis of this ListApisBindedToRequestThrottlingPolicyV2Response. 本次查询返回的API列表 :param apis: The apis of this ListApisBindedToRequestThrottlingPolicyV2Response. :type: list[ThrottleBindingApiResp] """ self._apis = apis def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ListApisBindedToRequestThrottlingPolicyV2Response): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
27.412121
100
0.588547
import pprint import re import six from huaweicloudsdkcore.sdk_response import SdkResponse class ListApisBindedToRequestThrottlingPolicyV2Response(SdkResponse): sensitive_list = [] openapi_types = { 'total': 'int', 'size': 'int', 'apis': 'list[ThrottleBindingApiResp]' } attribute_map = { 'total': 'total', 'size': 'size', 'apis': 'apis' } def __init__(self, total=None, size=None, apis=None): super().__init__() self._total = None self._size = None self._apis = None self.discriminator = None if total is not None: self.total = total if size is not None: self.size = size if apis is not None: self.apis = apis @property def total(self): return self._total @total.setter def total(self, total): self._total = total @property def size(self): return self._size @size.setter def size(self, size): self._size = size @property def apis(self): return self._apis @apis.setter def apis(self, apis): self._apis = apis def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, ListApisBindedToRequestThrottlingPolicyV2Response): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f71103cb3e09b1d069f05d1ab89f1c850ef5a0d5
626
py
Python
datasets/RTFM/rtfm/dynamics/item/weapon/clubs.py
kapikantzari/MultiBench
44ab6ea028682040a0c04de68239ce5cdf15123f
[ "MIT" ]
148
2021-03-06T06:54:13.000Z
2022-03-29T19:27:21.000Z
datasets/RTFM/rtfm/dynamics/item/weapon/clubs.py
kapikantzari/MultiBench
44ab6ea028682040a0c04de68239ce5cdf15123f
[ "MIT" ]
10
2021-07-19T22:57:49.000Z
2022-02-04T03:12:29.000Z
datasets/RTFM/rtfm/dynamics/item/weapon/clubs.py
kapikantzari/MultiBench
44ab6ea028682040a0c04de68239ce5cdf15123f
[ "MIT" ]
18
2021-07-22T07:17:27.000Z
2022-03-27T16:11:40.000Z
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .base_weapon import Weapon from ... import dice as D, material as M class BaseClub(Weapon): pass class Club(BaseClub): def __init__(self): super().__init__('club', weight=30, damage=D.Dice.from_str('d3'), material=M.Wood, hit=0) class Aklys(BaseClub): def __init__(self): super().__init__('aklys', weight=15, damage=D.Dice.from_str('d3'), material=M.Iron, hit=0)
24.076923
97
0.667732
from .base_weapon import Weapon from ... import dice as D, material as M class BaseClub(Weapon): pass class Club(BaseClub): def __init__(self): super().__init__('club', weight=30, damage=D.Dice.from_str('d3'), material=M.Wood, hit=0) class Aklys(BaseClub): def __init__(self): super().__init__('aklys', weight=15, damage=D.Dice.from_str('d3'), material=M.Iron, hit=0)
true
true
f71104b9710f6705b538a9fe0341ae2f581c20b5
7,343
py
Python
isi_sdk_8_1_1/isi_sdk_8_1_1/models/audit_progress_progress.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
24
2018-06-22T14:13:23.000Z
2022-03-23T01:21:26.000Z
isi_sdk_8_1_1/isi_sdk_8_1_1/models/audit_progress_progress.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
46
2018-04-30T13:28:22.000Z
2022-03-21T21:11:07.000Z
isi_sdk_8_1_1/isi_sdk_8_1_1/models/audit_progress_progress.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
29
2018-06-19T00:14:04.000Z
2022-02-08T17:51:19.000Z
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 6 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class AuditProgressProgress(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'protocol_audit_cee_time': 'int', 'protocol_audit_log_time': 'int', 'protocol_audit_syslog_time': 'int' } attribute_map = { 'protocol_audit_cee_time': 'protocol_audit_cee_time', 'protocol_audit_log_time': 'protocol_audit_log_time', 'protocol_audit_syslog_time': 'protocol_audit_syslog_time' } def __init__(self, protocol_audit_cee_time=None, protocol_audit_log_time=None, protocol_audit_syslog_time=None): # noqa: E501 """AuditProgressProgress - a model defined in Swagger""" # noqa: E501 self._protocol_audit_cee_time = None self._protocol_audit_log_time = None self._protocol_audit_syslog_time = None self.discriminator = None if protocol_audit_cee_time is not None: self.protocol_audit_cee_time = protocol_audit_cee_time if protocol_audit_log_time is not None: self.protocol_audit_log_time = protocol_audit_log_time if protocol_audit_syslog_time is not None: self.protocol_audit_syslog_time = protocol_audit_syslog_time @property def protocol_audit_cee_time(self): """Gets the protocol_audit_cee_time of this AuditProgressProgress. # noqa: E501 Specifies the last protocol audit event time consumed by the CEE forwarder. # noqa: E501 :return: The protocol_audit_cee_time of this AuditProgressProgress. # noqa: E501 :rtype: int """ return self._protocol_audit_cee_time @protocol_audit_cee_time.setter def protocol_audit_cee_time(self, protocol_audit_cee_time): """Sets the protocol_audit_cee_time of this AuditProgressProgress. Specifies the last protocol audit event time consumed by the CEE forwarder. # noqa: E501 :param protocol_audit_cee_time: The protocol_audit_cee_time of this AuditProgressProgress. # noqa: E501 :type: int """ if protocol_audit_cee_time is not None and protocol_audit_cee_time > 4294967295: # noqa: E501 raise ValueError("Invalid value for `protocol_audit_cee_time`, must be a value less than or equal to `4294967295`") # noqa: E501 if protocol_audit_cee_time is not None and protocol_audit_cee_time < 0: # noqa: E501 raise ValueError("Invalid value for `protocol_audit_cee_time`, must be a value greater than or equal to `0`") # noqa: E501 self._protocol_audit_cee_time = protocol_audit_cee_time @property def protocol_audit_log_time(self): """Gets the protocol_audit_log_time of this AuditProgressProgress. # noqa: E501 Specifies the last logged audit protocol event time. # noqa: E501 :return: The protocol_audit_log_time of this AuditProgressProgress. # noqa: E501 :rtype: int """ return self._protocol_audit_log_time @protocol_audit_log_time.setter def protocol_audit_log_time(self, protocol_audit_log_time): """Sets the protocol_audit_log_time of this AuditProgressProgress. Specifies the last logged audit protocol event time. # noqa: E501 :param protocol_audit_log_time: The protocol_audit_log_time of this AuditProgressProgress. # noqa: E501 :type: int """ if protocol_audit_log_time is not None and protocol_audit_log_time > 4294967295: # noqa: E501 raise ValueError("Invalid value for `protocol_audit_log_time`, must be a value less than or equal to `4294967295`") # noqa: E501 if protocol_audit_log_time is not None and protocol_audit_log_time < 0: # noqa: E501 raise ValueError("Invalid value for `protocol_audit_log_time`, must be a value greater than or equal to `0`") # noqa: E501 self._protocol_audit_log_time = protocol_audit_log_time @property def protocol_audit_syslog_time(self): """Gets the protocol_audit_syslog_time of this AuditProgressProgress. # noqa: E501 Specifies the last protocol audit event time consumed by the Syslog forwarder. # noqa: E501 :return: The protocol_audit_syslog_time of this AuditProgressProgress. # noqa: E501 :rtype: int """ return self._protocol_audit_syslog_time @protocol_audit_syslog_time.setter def protocol_audit_syslog_time(self, protocol_audit_syslog_time): """Sets the protocol_audit_syslog_time of this AuditProgressProgress. Specifies the last protocol audit event time consumed by the Syslog forwarder. # noqa: E501 :param protocol_audit_syslog_time: The protocol_audit_syslog_time of this AuditProgressProgress. # noqa: E501 :type: int """ if protocol_audit_syslog_time is not None and protocol_audit_syslog_time > 4294967295: # noqa: E501 raise ValueError("Invalid value for `protocol_audit_syslog_time`, must be a value less than or equal to `4294967295`") # noqa: E501 if protocol_audit_syslog_time is not None and protocol_audit_syslog_time < 0: # noqa: E501 raise ValueError("Invalid value for `protocol_audit_syslog_time`, must be a value greater than or equal to `0`") # noqa: E501 self._protocol_audit_syslog_time = protocol_audit_syslog_time def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AuditProgressProgress): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
40.125683
144
0.669617
import pprint import re import six class AuditProgressProgress(object): swagger_types = { 'protocol_audit_cee_time': 'int', 'protocol_audit_log_time': 'int', 'protocol_audit_syslog_time': 'int' } attribute_map = { 'protocol_audit_cee_time': 'protocol_audit_cee_time', 'protocol_audit_log_time': 'protocol_audit_log_time', 'protocol_audit_syslog_time': 'protocol_audit_syslog_time' } def __init__(self, protocol_audit_cee_time=None, protocol_audit_log_time=None, protocol_audit_syslog_time=None): self._protocol_audit_cee_time = None self._protocol_audit_log_time = None self._protocol_audit_syslog_time = None self.discriminator = None if protocol_audit_cee_time is not None: self.protocol_audit_cee_time = protocol_audit_cee_time if protocol_audit_log_time is not None: self.protocol_audit_log_time = protocol_audit_log_time if protocol_audit_syslog_time is not None: self.protocol_audit_syslog_time = protocol_audit_syslog_time @property def protocol_audit_cee_time(self): return self._protocol_audit_cee_time @protocol_audit_cee_time.setter def protocol_audit_cee_time(self, protocol_audit_cee_time): if protocol_audit_cee_time is not None and protocol_audit_cee_time > 4294967295: raise ValueError("Invalid value for `protocol_audit_cee_time`, must be a value less than or equal to `4294967295`") if protocol_audit_cee_time is not None and protocol_audit_cee_time < 0: raise ValueError("Invalid value for `protocol_audit_cee_time`, must be a value greater than or equal to `0`") self._protocol_audit_cee_time = protocol_audit_cee_time @property def protocol_audit_log_time(self): return self._protocol_audit_log_time @protocol_audit_log_time.setter def protocol_audit_log_time(self, protocol_audit_log_time): if protocol_audit_log_time is not None and protocol_audit_log_time > 4294967295: raise ValueError("Invalid value for `protocol_audit_log_time`, must be a value less than or equal to `4294967295`") if protocol_audit_log_time is not None and protocol_audit_log_time < 0: raise ValueError("Invalid value for `protocol_audit_log_time`, must be a value greater than or equal to `0`") self._protocol_audit_log_time = protocol_audit_log_time @property def protocol_audit_syslog_time(self): return self._protocol_audit_syslog_time @protocol_audit_syslog_time.setter def protocol_audit_syslog_time(self, protocol_audit_syslog_time): if protocol_audit_syslog_time is not None and protocol_audit_syslog_time > 4294967295: raise ValueError("Invalid value for `protocol_audit_syslog_time`, must be a value less than or equal to `4294967295`") if protocol_audit_syslog_time is not None and protocol_audit_syslog_time < 0: raise ValueError("Invalid value for `protocol_audit_syslog_time`, must be a value greater than or equal to `0`") self._protocol_audit_syslog_time = protocol_audit_syslog_time def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, AuditProgressProgress): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f711052633a45b9a3f3392f20a494f4bd70c01ab
11,316
py
Python
lorawan/lorawan_conformance/functionality/td_lorawan_fun_02.py
pablomodernell/lorawan_conformance_testing
3e6b9028ee7a6a614e52bac684e396ecd04fd10c
[ "MIT" ]
1
2020-09-10T14:12:07.000Z
2020-09-10T14:12:07.000Z
lorawan/lorawan_conformance/functionality/td_lorawan_fun_02.py
pablomodernell/lorawan_conformance_testing
3e6b9028ee7a6a614e52bac684e396ecd04fd10c
[ "MIT" ]
null
null
null
lorawan/lorawan_conformance/functionality/td_lorawan_fun_02.py
pablomodernell/lorawan_conformance_testing
3e6b9028ee7a6a614e52bac684e396ecd04fd10c
[ "MIT" ]
null
null
null
""" LoRaWAN Specification v1.0.2 Test Case Group: Functionality Test Name: FUN_02 """ ################################################################################# # MIT License # # Copyright (c) 2018, Pablo D. Modernell, Universitat Oberta de Catalunya (UOC), # Universidad de la Republica Oriental del Uruguay (UdelaR). # # 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 lorawan.lorawan_conformance.lorawan_steps as lorawan_steps import conformance_testing.test_step_sequence import conformance_testing.test_errors as test_errors class ActokToPingDelay(lorawan_steps.ActokToPing): """ Checks the tolerance to delays in timing from the specified start of the reception windows. Expected reception: Activation Ok. Sends after check: Ping message with an extra delay. """ def __init__(self, ctx_test_manager, step_name, delay, next_step, default_rx1_window=True): """ :param ctx_test_manager: Test Manager of the Test Case. :param step_name: string representation of the step name. :param delay: extra delay in microseconds (positive or negative). :param next_step: next step of the test. :param default_rx1_window: flag to indicate if the default behaviour should be sending downlink in RX1 (or RX2). """ super().__init__(ctx_test_manager=ctx_test_manager, step_name=step_name, default_rx1_window=default_rx1_window, next_step=next_step) self.delay = delay def step_handler(self, ch, method, properties, body): self.ctx_test_manager.device_under_test.loramac_params.rx1_delay += self.delay try: super().step_handler(ch, method, properties, body) except test_errors.TestingToolError as tt_e: raise tt_e finally: self.ctx_test_manager.device_under_test.loramac_params.rx1_delay -= self.delay class TestAppManager(conformance_testing.test_step_sequence.TestManager): """ The TestAppManager (Test Application Manager) is a TestManager defined in each test, it specifies the different steps that the test performs. LoRaWAN Test FUN 02: Test the node's tolerance to timing errors in the download reception windows. PRECONDITION: DUT (Device Under Test) is already in TEST MODE. """ def __init__(self, test_session_coordinator): super().__init__(test_name=__name__.split(".")[-1], ctx_test_session_coordinator=test_session_coordinator) # ----------------------------------------------------------------------------------------- self.s8_check_pong = lorawan_steps.PongFinalStep(ctx_test_manager=self, step_name="S8WaitPong", next_step=None) self.add_step_description(step_name="Step 8: 8WaitPong", description=( "Checks the reception of the PONG message.\n" "- Reception from DUT: PONG message.\n" "- TAS sends: None.\n")) # ----------------------------------------------------------------------------------------- self.s7_actok_to_ping_m20rx2 = ActokToPingDelay(ctx_test_manager=self, step_name="S7ActokToPingDelayMinus20", delay=-20, next_step=self.s8_check_pong, default_rx1_window=False) self.add_step_description( step_name="Step 7: S7ActokToPingDelayMinus20", description=( "Waits and Activation Ok message with the current downlink counter of " "the session and after it's received a PING PONG exchange will be initiated, " "using RX2 with a timing error of -20 micro seconds.\n" "- Reception from DUT: TAOK message with the downlink counter.\n" "- TAS sends: PING message with a -20 micro seconds delay in RX2.\n")) # ----------------------------------------------------------------------------------------- self.s6_check_pong = lorawan_steps.ProcessPong(ctx_test_manager=self, step_name="S6WaitPong", next_step=self.s7_actok_to_ping_m20rx2) self.add_step_description(step_name="Step 6: 6WaitPong", description=( "Checks the reception of the PONG message.\n" "- Reception from DUT: PONG message.\n" "- TAS sends: None.\n")) # ----------------------------------------------------------------------------------------- self.s5_actok_to_ping_m20rx1 = ActokToPingDelay(ctx_test_manager=self, step_name="S5ActokToPingDelay", delay=-20, next_step=self.s6_check_pong, default_rx1_window=True) self.add_step_description( step_name="Step 5: S5ActokToPingDelayMinus20", description=( "Waits and Activation Ok message with the current downlink counter of " "the session and after it's received a PING PONG exchange will be initiated, " "using RX1 with a timing error of -20 micro seconds.\n" "- Reception from DUT: TAOK message with the downlink counter.\n" "- TAS sends: PING message with a -20 micro seconds delay in RX1.\n")) # ----------------------------------------------------------------------------------------- self.s4_check_pong = lorawan_steps.ProcessPong(ctx_test_manager=self, step_name="S4WaitPong", next_step=self.s5_actok_to_ping_m20rx1) self.add_step_description(step_name="Step 4: S4WaitPong", description=( "Checks the reception of the PONG message.\n" "- Reception from DUT: PONG message.\n" "- TAS sends: None.\n")) # ----------------------------------------------------------------------------------------- self.s3_actok_to_ping_20rx2 = ActokToPingDelay(ctx_test_manager=self, step_name="S3ActokToPingDelayPlus20", delay=20, next_step=self.s4_check_pong, default_rx1_window=False) self.add_step_description( step_name="Step 2: S3ActokToPingDelayPlus20", description=( "Waits and Activation Ok message with the current downlink counter of " "the session and after it's received a PING PONG exchange will be initiated, " "using RX2 with a timing error of +20 micro seconds.\n" "- Reception from DUT: TAOK message with the downlink counter.\n" "- TAS sends: PING message with a +20 micro seconds delay in RX2.\n")) # ----------------------------------------------------------------------------------------- self.s2_check_pong = lorawan_steps.ProcessPong(ctx_test_manager=self, step_name="S2WaitPong", next_step=self.s3_actok_to_ping_20rx2) self.add_step_description(step_name="Step 2: S2WaitPong", description=( "Checks the reception of the PONG message.\n" "- Reception from DUT: PONG message.\n" "- TAS sends: None.\n")) # ----------------------------------------------------------------------------------------- self.s1_actok_to_ping_20rx1 = ActokToPingDelay(ctx_test_manager=self, step_name="S1ActokToPingDelayPlus20", delay=20, next_step=self.s2_check_pong, default_rx1_window=True) self.add_step_description( step_name="Step 1: S1ActokToPingDelayPlus20", description=( "Waits and Activation Ok message with the current downlink counter of " "the session and after it's received a PING PONG exchange will be " "initiated, using RX1 with a timing error of +20 micro seconds.\n" "- Reception from DUT: TAOK message with the downlink counter.\n" "- TAS sends: PING message with a +20 micro seconds delay in RX1.\n")) # ----------------------------------------------------------------------------------------- # Set Initial Step self.current_step = self.s1_actok_to_ping_20rx1 self.add_step_description( step_name="Test ID: TD_LoRaWAN_FUN_02", description=( "Objective: Test the node's tolerance to timing errors in the download " "reception windows. Verifies that downlink messages with +/- 20us in RX1 " "and RX2 are correctly received.\n" "References: LoRaWAN Specification v1.0.2.\n" "Pre-test conditions: The DUT is in Test Mode and supports " "Over The Air Activation (OTAA).\n"))
58.329897
99
0.514316
Pong", description=( "Checks the reception of the PONG message.\n" "- Reception from DUT: PONG message.\n" "- TAS sends: None.\n")) # ----------------------------------------------------------------------------------------- self.s1_actok_to_ping_20rx1 = ActokToPingDelay(ctx_test_manager=self, step_name="S1ActokToPingDelayPlus20", delay=20, next_step=self.s2_check_pong, default_rx1_window=True) self.add_step_description( step_name="Step 1: S1ActokToPingDelayPlus20", description=( "Waits and Activation Ok message with the current downlink counter of " "the session and after it's received a PING PONG exchange will be " "initiated, using RX1 with a timing error of +20 micro seconds.\n" "- Reception from DUT: TAOK message with the downlink counter.\n" "- TAS sends: PING message with a +20 micro seconds delay in RX1.\n")) self.current_step = self.s1_actok_to_ping_20rx1 self.add_step_description( step_name="Test ID: TD_LoRaWAN_FUN_02", description=( "Objective: Test the node's tolerance to timing errors in the download " "reception windows. Verifies that downlink messages with +/- 20us in RX1 " "and RX2 are correctly received.\n" "References: LoRaWAN Specification v1.0.2.\n" "Pre-test conditions: The DUT is in Test Mode and supports " "Over The Air Activation (OTAA).\n"))
true
true
f71105cea0163d953e3acd8928b9d0414789cbfb
366
py
Python
settings.py
anirvan90/conference_central
7379022bb31ed44cd2dbe75b40ed7808c6127bd7
[ "Apache-2.0" ]
null
null
null
settings.py
anirvan90/conference_central
7379022bb31ed44cd2dbe75b40ed7808c6127bd7
[ "Apache-2.0" ]
null
null
null
settings.py
anirvan90/conference_central
7379022bb31ed44cd2dbe75b40ed7808c6127bd7
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """settings.py Udacity conference server-side Python App Engine app user settings $Id$ created/forked from conference.py by wesc on 2014 may 24 """ # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = '1006324622497-9qlhtun5go635oe57l2vevfrq3f16u57.apps.googleusercontent.com'
21.529412
91
0.789617
WEB_CLIENT_ID = '1006324622497-9qlhtun5go635oe57l2vevfrq3f16u57.apps.googleusercontent.com'
true
true
f7110777aa0eb0df6694e887f697099eb4135fd0
130
py
Python
stuntcat/__main__.py
JTRHACKER/StuntCat
1c581df8971113838219dc98c35207925e6b9228
[ "MIT" ]
null
null
null
stuntcat/__main__.py
JTRHACKER/StuntCat
1c581df8971113838219dc98c35207925e6b9228
[ "MIT" ]
null
null
null
stuntcat/__main__.py
JTRHACKER/StuntCat
1c581df8971113838219dc98c35207925e6b9228
[ "MIT" ]
null
null
null
""" Another Main module. """ if __name__ == "__main__": import stuntcat.cli cli = stuntcat.cli.Cli() cli.cli_main()
13
28
0.615385
if __name__ == "__main__": import stuntcat.cli cli = stuntcat.cli.Cli() cli.cli_main()
true
true
f711087fc49d8d2d1e4f621050569c812ce59cb7
123
py
Python
CursoIntensivoPython/curso-intensivo-python-master/capitulo_09/my_electric_car.py
SweydAbdul/estudos-python
b052708d0566a0afb9a1c04d035467d45f820879
[ "MIT" ]
null
null
null
CursoIntensivoPython/curso-intensivo-python-master/capitulo_09/my_electric_car.py
SweydAbdul/estudos-python
b052708d0566a0afb9a1c04d035467d45f820879
[ "MIT" ]
null
null
null
CursoIntensivoPython/curso-intensivo-python-master/capitulo_09/my_electric_car.py
SweydAbdul/estudos-python
b052708d0566a0afb9a1c04d035467d45f820879
[ "MIT" ]
null
null
null
import electric_car my_tesla = electric_car.ElectricCar('tesla', 'roadster', 2016) print(my_tesla.get_descriptive_name())
24.6
62
0.804878
import electric_car my_tesla = electric_car.ElectricCar('tesla', 'roadster', 2016) print(my_tesla.get_descriptive_name())
true
true
f71108f2dc22cced6e0edca17dae51190cd8f33d
1,105
py
Python
build/lib/biosteam/units/_enzyme_treatment.py
rjhanes/biosteam
ee345ac0b14ce4de9b38ac5a467588d2f854da71
[ "MIT" ]
1
2019-11-17T13:14:19.000Z
2019-11-17T13:14:19.000Z
build/lib/biosteam/units/_enzyme_treatment.py
lilanyu/biosteam
b025bbe138bfd0b016af58583792fb4f3ff9186e
[ "MIT" ]
null
null
null
build/lib/biosteam/units/_enzyme_treatment.py
lilanyu/biosteam
b025bbe138bfd0b016af58583792fb4f3ff9186e
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Thu Aug 23 22:07:01 2018 @author: yoelr """ from ._tank import MixTank from ._hx import HXutility class EnzymeTreatment(MixTank): """Create an EnzymeTreatment unit that is cost as a MixTank with a heat exchanger.""" _N_outs = 1 #: Residence time (hr) _tau = 1 def __init__(self, ID='', ins=None, outs=(), *, T): super().__init__(ID, ins, outs) self.T = T #: Operating temperature self._heat_exchanger = he = HXutility(None, None, T=T) self._heat_utilities = he._heat_utilities he._ins = self._ins he._outs = self._outs def _run(self): feed = self.ins[0] out = self.outs[0] out._mol[:] = self._mol_in out.phase = feed.phase out.P = feed.P out.T = self.T def _design(self): super()._design() self._heat_exchanger._design() def _cost(self): super()._cost() he = self._heat_exchanger he._cost() self._Cost['Heat exchanger'] = he._Cost['Heat exchanger']
26.309524
89
0.567421
from ._tank import MixTank from ._hx import HXutility class EnzymeTreatment(MixTank): _N_outs = 1 _tau = 1 def __init__(self, ID='', ins=None, outs=(), *, T): super().__init__(ID, ins, outs) self.T = T self._heat_exchanger = he = HXutility(None, None, T=T) self._heat_utilities = he._heat_utilities he._ins = self._ins he._outs = self._outs def _run(self): feed = self.ins[0] out = self.outs[0] out._mol[:] = self._mol_in out.phase = feed.phase out.P = feed.P out.T = self.T def _design(self): super()._design() self._heat_exchanger._design() def _cost(self): super()._cost() he = self._heat_exchanger he._cost() self._Cost['Heat exchanger'] = he._Cost['Heat exchanger']
true
true
f71108f98a82dd40b3eff767d34aa0acebabcc22
72,622
py
Python
metadata/metadata_service/proxy/atlas_proxy.py
defendercrypt/amundsen
83c728b646020f60cf2270c12e766fe4af8c9948
[ "Apache-2.0" ]
2,072
2020-08-11T20:16:48.000Z
2022-03-31T07:04:05.000Z
metadata/metadata_service/proxy/atlas_proxy.py
defendercrypt/amundsen
83c728b646020f60cf2270c12e766fe4af8c9948
[ "Apache-2.0" ]
795
2020-08-11T15:24:39.000Z
2022-03-31T18:56:13.000Z
metadata/metadata_service/proxy/atlas_proxy.py
defendercrypt/amundsen
83c728b646020f60cf2270c12e766fe4af8c9948
[ "Apache-2.0" ]
671
2020-08-11T20:39:56.000Z
2022-03-31T08:39:07.000Z
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 import datetime import logging import re from collections import defaultdict from operator import attrgetter from random import randint from typing import (Any, Dict, Generator, List, Optional, Set, Tuple, Type, Union) from amundsen_common.entity.resource_type import ResourceType from amundsen_common.models.dashboard import DashboardSummary from amundsen_common.models.feature import Feature from amundsen_common.models.generation_code import GenerationCode from amundsen_common.models.lineage import Lineage, LineageItem from amundsen_common.models.popular_table import PopularTable from amundsen_common.models.table import (Application, Badge, Column, ProgrammaticDescription, Reader, ResourceReport, Stat, Table, Tag, User, Watermark) from amundsen_common.models.user import User as UserEntity from amundsen_common.utils.atlas import (AtlasColumnKey, AtlasCommonParams, AtlasCommonTypes, AtlasDashboardTypes, AtlasStatus, AtlasTableKey, AtlasTableTypes) from apache_atlas.client.base_client import AtlasClient from apache_atlas.model.glossary import (AtlasGlossary, AtlasGlossaryHeader, AtlasGlossaryTerm) from apache_atlas.model.instance import (AtlasEntitiesWithExtInfo, AtlasEntity, AtlasEntityHeader, AtlasEntityWithExtInfo, AtlasRelatedObjectId) from apache_atlas.model.relationship import AtlasRelationship from apache_atlas.utils import type_coerce from beaker.cache import CacheManager from beaker.util import parse_cache_config_options from flask import current_app as app from werkzeug.exceptions import BadRequest from metadata_service.entity.dashboard_detail import \ DashboardDetail as DashboardDetailEntity from metadata_service.entity.dashboard_query import DashboardQuery from metadata_service.entity.description import Description from metadata_service.entity.tag_detail import TagDetail from metadata_service.exception import NotFoundException from metadata_service.proxy import BaseProxy from metadata_service.util import UserResourceRel LOGGER = logging.getLogger(__name__) # Expire cache every 11 hours + jitter _ATLAS_PROXY_CACHE_EXPIRY_SEC = 11 * 60 * 60 + randint(0, 3600) # noinspection PyMethodMayBeStatic class AtlasProxy(BaseProxy): """ Atlas Proxy client for the amundsen metadata {ATLAS_API_DOCS} = https://atlas.apache.org/api/v2/ """ DB_ATTRIBUTE = 'db' STATISTICS_FORMAT_SPEC = app.config['STATISTICS_FORMAT_SPEC'] # Qualified Name of the Glossary, that holds the user defined terms. # For Amundsen, we are using Glossary Terms as the Tags. AMUNDSEN_USER_TAGS = 'amundsen_user_tags' _CACHE = CacheManager(**parse_cache_config_options({'cache.regions': 'atlas_proxy', 'cache.atlas_proxy.type': 'memory', 'cache.atlas_proxy.expire': _ATLAS_PROXY_CACHE_EXPIRY_SEC})) def __init__(self, *, host: str, port: int, user: str = 'admin', password: str = '', encrypted: bool = False, validate_ssl: bool = False, client_kwargs: dict = dict()) -> None: """ Initiate the Apache Atlas client with the provided credentials """ protocol = 'https' if encrypted else 'http' self.client = AtlasClient(f'{protocol}://{host}:{port}', (user, password)) self.client.session.verify = validate_ssl def _parse_dashboard_bookmark_qn(self, bookmark_qn: str) -> Dict: """ Parse bookmark qualifiedName and extract the info :param bookmark_qn: Qualified Name of Bookmark entity :return: Dictionary object containing following information: product: dashboard product cluster: cluster information dashboard_group: Dashboard group name dashboard_id: Dashboard identifier user_id: User id """ pattern = re.compile(r""" ^(?P<product>[^.]*)_dashboard :// (?P<cluster>[^.]*) \. (?P<dashboard_group>[^.]*) / (?P<dashboard_id>[^.]*) / (?P<type>[^.]*) / bookmark / (?P<user_id>[^.]*) $ """, re.X) result = pattern.match(bookmark_qn) return result.groupdict() if result else dict() def _parse_table_bookmark_qn(self, bookmark_qn: str) -> Dict: """ Parse bookmark qualifiedName and extract the info :param bookmark_qn: Qualified Name of Bookmark entity :return: Dictionary object containing following information: cluster: cluster information db: Database name name: Table name """ pattern = re.compile(r""" ^(?P<db>[^.]*) \. (?P<table>[^.]*) \. (?P<entity_type>[^.]*) \. (?P<user_id>[^.]*)\.bookmark \@ (?P<cluster>.*) $ """, re.X) result = pattern.match(bookmark_qn) return result.groupdict() if result else dict() @classmethod def _filter_active(cls, entities: List[dict]) -> List[dict]: """ Filter out active entities based on entity end relationship status. """ result = [e for e in entities if e.get('relationshipStatus') == AtlasStatus.ACTIVE and e.get('entityStatus') == AtlasStatus.ACTIVE] return result def _get_table_entity(self, *, table_uri: str) -> AtlasEntityWithExtInfo: """ Fetch information from table_uri and then find the appropriate entity :param table_uri: The table URI coming from Amundsen Frontend :return: A table entity matching the Qualified Name derived from table_uri """ key = AtlasTableKey(table_uri) try: return self.client.entity.get_entity_by_attribute(type_name=key.entity_type, uniq_attributes=[ (AtlasCommonParams.qualified_name, key.qualified_name)]) except Exception as ex: LOGGER.exception(f'Table not found. {str(ex)}') raise NotFoundException(f'Table URI( {table_uri} ) does not exist') def _get_user_entity(self, user_id: str) -> AtlasEntityWithExtInfo: """ Fetches an user entity from an id :param user_id: User ID :return: A User entity matching the user_id """ try: return self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.user, uniq_attributes=[ (AtlasCommonParams.qualified_name, user_id)]) except Exception: raise NotFoundException(f'(User {user_id}) does not exist') def _create_bookmark(self, entity: AtlasEntityWithExtInfo, user_guid: str, bookmark_qn: str, entity_uri: str) -> None: """ Creates a bookmark entity for a specific user and entity uri. :param entity: bookmarked entity :param user_guid: User's guid :param bookmark_qn: Bookmark qualifiedName :param entity_uri: uri of bookmarked entity :return: """ bookmark_entity = { 'entity': { 'typeName': AtlasCommonTypes.bookmark, AtlasCommonParams.attributes: { AtlasCommonParams.qualified_name: bookmark_qn, AtlasStatus.ACTIVE.lower(): True, 'entityUri': entity_uri, 'entityName': entity.entity[AtlasCommonParams.attributes]['name'], 'user': {AtlasCommonParams.guid: user_guid}, 'entity': {AtlasCommonParams.guid: entity.entity[AtlasCommonParams.guid]}} } } bookmark_entity = type_coerce(bookmark_entity, AtlasEntityWithExtInfo) self.client.entity.create_entity(bookmark_entity) def _get_bookmark_entity(self, entity_uri: str, user_id: str, resource_type: ResourceType) -> AtlasEntityWithExtInfo: """ Fetch a Bookmark entity from parsing entity uri and user id. If Bookmark is not present, create one for the user. :param entity_uri: :param user_id: Qualified Name of a user :return: """ if resource_type == ResourceType.Table: entity_info = AtlasTableKey(entity_uri).get_details() schema = entity_info.get('schema') table = entity_info.get('table') database = entity_info.get('database', 'hive_table') cluster = entity_info.get('cluster') bookmark_qn = f'{schema}.{table}.{database}.{user_id}.bookmark@{cluster}' else: bookmark_qn = f'{entity_uri}/{resource_type.name.lower()}/bookmark/{user_id}' try: bookmark_entity = self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.bookmark, uniq_attributes=[ (AtlasCommonParams.qualified_name, bookmark_qn)]) except Exception as ex: LOGGER.exception(f'Bookmark not found. {str(ex)}') if resource_type == ResourceType.Table: bookmarked_entity = self._get_table_entity(table_uri=entity_uri) elif resource_type == ResourceType.Dashboard: bookmarked_entity = self._get_dashboard(qualified_name=entity_uri) else: raise NotImplementedError(f'Bookmarks for Resource Type ({resource_type}) are not yet implemented') # Fetch user entity from user_id for relation user_entity = self._get_user_entity(user_id) # Create bookmark entity with the user relation. self._create_bookmark(bookmarked_entity, user_entity.entity[AtlasCommonParams.guid], bookmark_qn, entity_uri) # Fetch bookmark entity after creating it. bookmark_entity = self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.bookmark, uniq_attributes=[ (AtlasCommonParams.qualified_name, bookmark_qn)]) return bookmark_entity def _get_column(self, *, table_uri: str, column_name: str) -> Dict: """ Fetch the column information from referredEntities of the table entity :param table_uri: :param column_name: :return: A dictionary containing the column details """ try: table_entity = self._get_table_entity(table_uri=table_uri) columns = table_entity.entity[AtlasCommonParams.relationships].get('columns') for column in columns or list(): col_details = table_entity.referredEntities[column[AtlasCommonParams.guid]] if column_name == col_details[AtlasCommonParams.attributes]['name']: return col_details raise NotFoundException(f'Column not found: {column_name}') except KeyError as ex: LOGGER.exception(f'Column not found: {str(ex)}') raise NotFoundException(f'Column not found: {column_name}') def _serialize_columns(self, *, entity: AtlasEntityWithExtInfo) -> \ Union[List[Column], List]: """ Helper function to fetch the columns from entity and serialize them using Column and Stat model. :param entity: AtlasEntityWithExtInfo object, along with relationshipAttributes :return: A list of Column objects, if there are any columns available, else an empty list. """ columns = list() for column in entity.entity[AtlasCommonParams.relationships].get('columns') or list(): column_status = column.get('entityStatus', 'inactive').lower() if column_status != 'active': continue col_entity = entity.referredEntities[column[AtlasCommonParams.guid]] col_attrs = col_entity[AtlasCommonParams.attributes] statistics = list() badges = list() for column_classification in col_entity.get('classifications') or list(): if column_classification.get('entityStatus') == AtlasStatus.ACTIVE: name = column_classification.get('typeName') badges.append(Badge(badge_name=name, category='default')) for stats in col_attrs.get('statistics') or list(): stats_attrs = stats[AtlasCommonParams.attributes] stat_type = stats_attrs.get('stat_name') stat_format = self.STATISTICS_FORMAT_SPEC.get(stat_type, dict()) if not stat_format.get('drop', False): stat_type = stat_format.get('new_name', stat_type) stat_val = stats_attrs.get('stat_val') format_val = stat_format.get('format') if format_val: stat_val = format_val.format(stat_val) else: stat_val = str(stat_val) start_epoch = stats_attrs.get('start_epoch') end_epoch = stats_attrs.get('end_epoch') statistics.append( Stat( stat_type=stat_type, stat_val=stat_val, start_epoch=start_epoch, end_epoch=end_epoch, ) ) columns.append( Column( name=col_attrs.get('name'), description=col_attrs.get('description') or col_attrs.get('comment'), col_type=col_attrs.get('type') or col_attrs.get('dataType') or col_attrs.get('data_type'), sort_order=col_attrs.get('position') or 9999, stats=statistics, badges=badges ) ) return sorted(columns, key=lambda item: item.sort_order) def _get_reports(self, guids: List[str]) -> List[ResourceReport]: reports = [] if guids: report_entities = self.client.entity.get_entities_by_guids(guids=guids) for report_entity in report_entities.entities: try: if report_entity.status == AtlasStatus.ACTIVE: report_attrs = report_entity.attributes reports.append( ResourceReport( name=report_attrs['name'], url=report_attrs['url'] ) ) except (KeyError, AttributeError): LOGGER.exception(f'Error while accessing table report: {str(report_entity)}', exc_info=True) parsed_reports = app.config['RESOURCE_REPORT_CLIENT'](reports) \ if app.config['RESOURCE_REPORT_CLIENT'] else reports return sorted(parsed_reports) def _get_owners(self, data_owners: list, fallback_owner: str = None) -> List[User]: owners_detail = list() active_owners_list = list() for owner in self._filter_active(data_owners): owner_qn = owner['displayText'] owner_data = self._get_user_details(owner_qn) owners_detail.append(User(**owner_data)) active_owners_list.append(owner_qn) # To avoid the duplication, # we are checking if the fallback is not in data_owners if fallback_owner and (fallback_owner not in active_owners_list): owners_detail.append(User(**self._get_user_details(fallback_owner))) return owners_detail def get_user(self, *, id: str) -> Union[UserEntity, None]: pass def create_update_user(self, *, user: User) -> Tuple[User, bool]: pass def get_users(self) -> List[UserEntity]: pass def _serialize_badges(self, entity: AtlasEntityWithExtInfo) -> List[Badge]: """ Return list of Badges for entity. Badges in Amundsen <> Atlas integration are based on Atlas Classification. :param entity: entity for which badges should be collected :return : List of Amundsen Badge objects. """ result = [] classifications = entity.get('classifications') for classification in classifications or list(): result.append(Badge(badge_name=classification.get('typeName'), category='default')) return result def _serialize_tags(self, entity: AtlasEntityWithExtInfo) -> List[Tag]: """ Return list of Tags for entity. Tags in Amundsen <> Atlas integration are based on Atlas Glossary. :param entity: entity for which tags should be collected :return : List of Amundsen Tag objects. """ result = [] meanings = self._filter_active(entity.get(AtlasCommonParams.relationships, dict()).get('meanings', [])) for term in meanings or list(): result.append(Tag(tag_name=term.get('displayText', ''), tag_type='default')) return result def get_table(self, *, table_uri: str) -> Table: """ Gathers all the information needed for the Table Detail Page. :param table_uri: :return: A Table object with all the information available or gathered from different entities. """ entity = self._get_table_entity(table_uri=table_uri) table_details = entity.entity try: attrs = table_details[AtlasCommonParams.attributes] programmatic_descriptions = self._get_programmatic_descriptions(attrs.get('parameters', dict()) or dict()) table_info = AtlasTableKey(attrs.get(AtlasCommonParams.qualified_name)).get_details() badges = self._serialize_badges(table_details) tags = self._serialize_tags(table_details) columns = self._serialize_columns(entity=entity) reports_guids = [report.get("guid") for report in attrs.get("reports") or list()] table_type = attrs.get('tableType') or 'table' is_view = 'view' in table_type.lower() readers = self._get_readers(table_details, Reader) application = self._get_application(table_details) table = Table( table_writer=application, database=AtlasTableKey(table_uri).get_details()['database'], cluster=table_info.get('cluster', ''), schema=table_info.get('schema', ''), name=attrs.get('name') or table_info.get('table', ''), badges=badges, tags=tags, description=attrs.get('description') or attrs.get('comment'), owners=self._get_owners( table_details[AtlasCommonParams.relationships].get('ownedBy', []), attrs.get('owner')), resource_reports=self._get_reports(guids=reports_guids), columns=columns, is_view=is_view, table_readers=readers, last_updated_timestamp=self._parse_date(table_details.get('updateTime')), programmatic_descriptions=programmatic_descriptions, watermarks=self._get_table_watermarks(table_details)) return table except KeyError: LOGGER.exception('Error while accessing table information. {}', exc_info=True) raise BadRequest(f'Some of the required attributes are missing in: {table_uri}') @staticmethod def _validate_date(text_date: str, date_format: str) -> Tuple[Optional[datetime.datetime], Optional[str]]: try: return datetime.datetime.strptime(text_date, date_format), date_format except (ValueError, TypeError): return None, None @staticmethod def _select_watermark_format(partition_names: Optional[List[Any]]) -> Optional[str]: result = None if partition_names: for partition_name in partition_names: # Assume that all partitions for given table have the same date format. Only thing that needs to be done # is establishing which format out of the supported ones it is and then we validate every partition # against it. for df in app.config['WATERMARK_DATE_FORMATS']: _, result = AtlasProxy._validate_date(partition_name, df) if result: LOGGER.debug('Established date format', extra=dict(date_format=result)) return result return result @staticmethod def _render_partition_key_name(entity: AtlasEntityWithExtInfo) -> Optional[str]: _partition_keys = [] for partition_key in entity.get(AtlasCommonParams.attributes, dict()).get('partitionKeys', []): partition_key_column_name = partition_key.get('displayName') if partition_key_column_name: _partition_keys.append(partition_key_column_name) partition_key = ' '.join(_partition_keys).strip() return partition_key def _get_table_watermarks(self, entity: AtlasEntityWithExtInfo) -> List[Watermark]: partition_value_format = '%Y-%m-%d %H:%M:%S' _partitions = entity.get(AtlasCommonParams.relationships, dict()).get('partitions', list()) names = [_partition.get('displayText') for _partition in self._filter_active(_partitions)] if not names: return [] partition_key = self._render_partition_key_name(entity) watermark_date_format = self._select_watermark_format(names) partitions = {} for _partition in _partitions: partition_name = _partition.get('displayText') if partition_name and watermark_date_format: partition_date, _ = self._validate_date(partition_name, watermark_date_format) if partition_date: common_values = {'partition_value': datetime.datetime.strftime(partition_date, partition_value_format), 'create_time': 0, 'partition_key': partition_key} partitions[partition_date] = common_values if partitions: low_watermark_date = min(partitions.keys()) high_watermark_date = max(partitions.keys()) low_watermark = Watermark(watermark_type='low_watermark', **partitions.get(low_watermark_date)) high_watermark = Watermark(watermark_type='high_watermark', **partitions.get(high_watermark_date)) return [low_watermark, high_watermark] else: return [] def delete_owner(self, *, table_uri: str, owner: str) -> None: """ :param table_uri: :param owner: :return: """ table = self._get_table_entity(table_uri=table_uri) table_entity = table.entity if table_entity[AtlasCommonParams.relationships].get("ownedBy"): try: active_owner = next(filter(lambda item: item['relationshipStatus'] == AtlasStatus.ACTIVE and item['displayText'] == owner, table_entity[AtlasCommonParams.relationships]['ownedBy']), None) if active_owner: self.client.relationship.delete_relationship_by_guid( guid=active_owner.get('relationshipGuid') ) else: raise BadRequest('You can not delete this owner.') except Exception: LOGGER.exception('Error while removing table data owner.', exc_info=True) def add_owner(self, *, table_uri: str, owner: str) -> None: """ Query on Atlas User entity to find if the entity exist for the owner string in parameter, if not create one. And then use that User entity's GUID and add a relationship between Table and User, on ownedBy field. :param table_uri: :param owner: Email address of the owner :return: None, as it simply adds the owner. """ owner_info = self._get_user_details(owner) if not owner_info: raise NotFoundException(f'User "{owner}" does not exist.') user_dict = type_coerce({ "entity": { "typeName": "User", "attributes": {"qualifiedName": owner}, } }, AtlasEntityWithExtInfo) # Get or Create a User user_entity = self.client.entity.create_entity(user_dict) user_guid = next(iter(user_entity.guidAssignments.values())) table = self._get_table_entity(table_uri=table_uri) entity_def = { "typeName": "DataSet_Users_Owner", "end1": { "guid": table.entity.get("guid"), "typeName": "Table", }, "end2": { "guid": user_guid, "typeName": "User", }, } try: relationship = type_coerce(entity_def, AtlasRelationship) self.client.relationship.create_relationship(relationship=relationship) except Exception: LOGGER.exception('Error while adding the owner information. {}', exc_info=True) raise BadRequest(f'User {owner} is already added as a data owner for table {table_uri}.') def get_table_description(self, *, table_uri: str) -> Union[str, None]: """ :param table_uri: :return: The description of the table as a string """ entity = self._get_table_entity(table_uri=table_uri) return entity.entity[AtlasCommonParams.attributes].get('description') def put_table_description(self, *, table_uri: str, description: str) -> None: """ Update the description of the given table. :param table_uri: :param description: Description string :return: None """ table = self._get_table_entity(table_uri=table_uri) self.client.entity.partial_update_entity_by_guid( entity_guid=table.entity.get("guid"), attr_value=description, attr_name='description' ) @_CACHE.cache('_get_user_defined_glossary_guid') def _get_user_defined_glossary_guid(self) -> str: """ This function look for a user defined glossary i.e., self.ATLAS_USER_DEFINED_TERMS If there is not one available, this will create a new glossary. The main reason to put this functionality into a separate function is to avoid the lookup each time someone assigns a tag to a data source. :return: Glossary object, that holds the user defined terms. """ # Check if the user glossary already exists glossaries = self.client.glossary.get_all_glossaries() for glossary in glossaries: if glossary.get(AtlasCommonParams.qualified_name) == self.AMUNDSEN_USER_TAGS: return glossary[AtlasCommonParams.guid] # If not already exists, create one glossary_def = AtlasGlossary({"name": self.AMUNDSEN_USER_TAGS, "shortDescription": "Amundsen User Defined Terms"}) glossary = self.client.glossary.create_glossary(glossary_def) return glossary.guid @_CACHE.cache('_get_create_glossary_term') def _get_create_glossary_term(self, term_name: str) -> Union[AtlasGlossaryTerm, AtlasEntityHeader]: """ Since Atlas does not provide any API to find a term directly by a qualified name, we need to look for AtlasGlossaryTerm via basic search, if found then return, else create a new glossary term under the user defined glossary. :param term_name: Name of the term. NOTE: this is different from qualified name. :return: Term Object. """ params = { 'typeName': "AtlasGlossaryTerm", 'excludeDeletedEntities': True, 'includeSubTypes': True, AtlasCommonParams.attributes: ["assignedEntities", ], 'entityFilters': {'condition': "AND", 'criterion': [{'attributeName': "name", 'operator': "=", 'attributeValue': term_name}] } } result = self.client.discovery.faceted_search(search_parameters=params) if result.approximateCount: term = result.entities[0] else: glossary_guid = self._get_user_defined_glossary_guid() glossary_def = AtlasGlossaryHeader({'glossaryGuid': glossary_guid}) term_def = AtlasGlossaryTerm({'name': term_name, 'anchor': glossary_def}) term = self.client.glossary.create_glossary_term(term_def) return term def add_tag(self, *, id: str, tag: str, tag_type: str = "default", resource_type: ResourceType = ResourceType.Table) -> None: """ Assign the Glossary Term to the give table. If the term is not there, it will create a new term under the Glossary self.ATLAS_USER_DEFINED_TERMS :param id: Table URI / Dashboard ID etc. :param tag: Tag Name :param tag_type :return: None """ entity = self._get_table_entity(table_uri=id) term = self._get_create_glossary_term(tag) related_entity = AtlasRelatedObjectId({AtlasCommonParams.guid: entity.entity[AtlasCommonParams.guid], "typeName": resource_type.name}) self.client.glossary.assign_term_to_entities(term.guid, [related_entity]) def add_badge(self, *, id: str, badge_name: str, category: str = '', resource_type: ResourceType) -> None: # Not implemented raise NotImplementedError def delete_tag(self, *, id: str, tag: str, tag_type: str, resource_type: ResourceType = ResourceType.Table) -> None: """ Removes the Glossary Term assignment from the provided source. :param id: Table URI / Dashboard ID etc. :param tag: Tag Name :return:None """ entity = self._get_table_entity(table_uri=id) term = self._get_create_glossary_term(tag) if not term: return assigned_entities = self.client.glossary.get_entities_assigned_with_term(term.guid, "ASC", -1, 0) for item in assigned_entities or list(): if item.get(AtlasCommonParams.guid) == entity.entity[AtlasCommonParams.guid]: related_entity = AtlasRelatedObjectId(item) return self.client.glossary.disassociate_term_from_entities(term.guid, [related_entity]) def delete_badge(self, *, id: str, badge_name: str, category: str, resource_type: ResourceType) -> None: # Not implemented raise NotImplementedError def put_column_description(self, *, table_uri: str, column_name: str, description: str) -> None: """ :param table_uri: :param column_name: Name of the column to update the description :param description: The description string :return: None, as it simply updates the description of a column """ column_detail = self._get_column( table_uri=table_uri, column_name=column_name) col_guid = column_detail[AtlasCommonParams.guid] self.client.entity.partial_update_entity_by_guid( entity_guid=col_guid, attr_value=description, attr_name='description' ) def get_column_description(self, *, table_uri: str, column_name: str) -> Union[str, None]: """ :param table_uri: :param column_name: :return: The column description using the referredEntities information of a table entity """ column_detail = self._get_column( table_uri=table_uri, column_name=column_name) return column_detail[AtlasCommonParams.attributes].get('description') def _serialize_popular_tables(self, entities: AtlasEntitiesWithExtInfo) -> List[PopularTable]: """ Gets a list of entities and serialize the popular tables. :param entities: List of entities from atlas client :return: a list of PopularTable objects """ popular_tables = list() for table in entities.entities or []: table_attrs = table.attributes table_info = AtlasTableKey(table_attrs.get(AtlasCommonParams.qualified_name)).get_details() table_name = table_info.get('table') or table_attrs.get('name') schema_name = table_info.get('schema', '') db_cluster = table_info.get('cluster', '') popular_table = PopularTable( database=table_info.get('database') or table.typeName, cluster=db_cluster, schema=schema_name, name=table_name, description=table_attrs.get('description') or table_attrs.get('comment')) popular_tables.append(popular_table) return popular_tables def get_popular_tables(self, *, num_entries: int, user_id: Optional[str] = None) -> List[PopularTable]: """ Generates a list of Popular tables to be shown on the home page of Amundsen. :param num_entries: Number of popular tables to fetch :return: A List of popular tables instances """ popular_query_params = {'typeName': AtlasTableTypes.table, 'sortBy': 'popularityScore', 'sortOrder': 'DESCENDING', 'excludeDeletedEntities': True, 'limit': num_entries} search_results = self.client.discovery.faceted_search(search_parameters=popular_query_params) return self._serialize_popular_tables(search_results) def get_latest_updated_ts(self) -> int: date = None metrics = self.client.admin.get_metrics() try: date = self._parse_date(metrics.general.get('stats', {}).get('Notification:lastMessageProcessedTime')) except AttributeError: pass return date or 0 def get_statistics(self) -> Dict[str, Any]: # Not implemented pass @_CACHE.cache('get_tags') def get_tags(self) -> List: """ Fetch all the glossary terms from atlas, along with their assigned entities as this will be used to generate the autocomplete on the table detail page :return: A list of TagDetail Objects """ tags = [] params = { 'typeName': "AtlasGlossaryTerm", 'limit': 1000, 'offset': 0, 'excludeDeletedEntities': True, 'includeSubTypes': True, AtlasCommonParams.attributes: ["assignedEntities", ] } glossary_terms = self.client.discovery.faceted_search(search_parameters=params) for item in glossary_terms.entities or list(): tags.append( TagDetail( tag_name=item.attributes.get("name"), tag_count=len(item.attributes.get("assignedEntities")) ) ) return tags @_CACHE.cache('get_badges') def get_badges(self) -> List: badges = list() metrics = self.client.admin.get_metrics() try: system_badges = metrics["tag"].get("tagEntities").keys() for item in system_badges: badges.append( Badge(badge_name=item, category="default") ) except AttributeError: LOGGER.info("No badges/classifications available in the system.") return badges def _get_resources_followed_by_user(self, user_id: str, resource_type: str) \ -> List[Union[PopularTable, DashboardSummary]]: """ Helper function to get the resource, table, dashboard etc followed by a user. :param user_id: User ID of a user :param resource_type: Type of a resource that returns, could be table, dashboard etc. :return: A list of PopularTable, DashboardSummary or any other resource. """ if resource_type == ResourceType.Table.name: bookmark_qn_search_pattern = f'_{resource_type.lower()}.{user_id}.bookmark' else: bookmark_qn_search_pattern = f'/{resource_type.lower()}/bookmark/{user_id}' params = { 'typeName': AtlasCommonTypes.bookmark, 'offset': '0', 'limit': '1000', 'excludeDeletedEntities': True, 'entityFilters': { 'condition': 'AND', 'criterion': [ { 'attributeName': AtlasCommonParams.qualified_name, 'operator': 'contains', 'attributeValue': bookmark_qn_search_pattern }, { 'attributeName': AtlasStatus.ACTIVE.lower(), 'operator': 'eq', 'attributeValue': 'true' } ] }, AtlasCommonParams.attributes: ['count', AtlasCommonParams.qualified_name, AtlasCommonParams.uri, 'entityName'] } # Fetches the bookmark entities based on filters search_results = self.client.discovery.faceted_search(search_parameters=params) resources: List[Union[PopularTable, DashboardSummary]] = [] for record in search_results.entities or []: if resource_type == ResourceType.Table.name: table_info = AtlasTableKey(record.attributes[AtlasCommonParams.uri]).get_details() res = self._parse_table_bookmark_qn(record.attributes[AtlasCommonParams.qualified_name]) resources.append(PopularTable( database=table_info['database'], cluster=res['cluster'], schema=res['db'], name=res['table'])) elif resource_type == ResourceType.Dashboard.name: dashboard_info = self._parse_dashboard_bookmark_qn(record.attributes[AtlasCommonParams.qualified_name]) resources.append(DashboardSummary( uri=record.attributes[AtlasCommonParams.uri], cluster=dashboard_info['cluster'], name=record.attributes['entityName'], group_name=dashboard_info['dashboard_group'], group_url='', product=dashboard_info['product'], url='' )) else: raise NotImplementedError(f'resource type {resource_type} is not supported') return resources def _get_resources_owned_by_user(self, user_id: str, resource_type: str) \ -> List[Union[PopularTable, DashboardSummary, Any]]: """ Helper function to get the resource, table, dashboard etc owned by a user. :param user_id: User ID of a user :param resource_type: Type of a resource that returns, could be table, dashboard etc. :return: A list of PopularTable, DashboardSummary or any other resource. """ resources: List[Union[PopularTable, DashboardSummary, Any]] = list() if resource_type == ResourceType.Table.name: type_regex = "(.*)_table$" entity_type = AtlasTableTypes.table serialize_function = self._serialize_popular_tables elif resource_type == ResourceType.Dashboard.name: type_regex = 'Dashboard' entity_type = AtlasDashboardTypes.metadata serialize_function = self._serialize_dashboard_summaries else: raise NotImplementedError(f'Resource Type ({resource_type}) is not yet implemented') user_entity = self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.user, uniq_attributes=[ ( AtlasCommonParams.qualified_name, user_id)]).entity if not user_entity: raise NotFoundException(f'User {user_id} not found.') resource_guids = set() for item in self._filter_active(user_entity[AtlasCommonParams.relationships].get('owns')) or list(): if re.compile(type_regex).match(item['typeName']): resource_guids.add(item[AtlasCommonParams.guid]) owned_resources_query = f'{entity_type} where owner like "{user_id.lower()}*" and __state = "ACTIVE"' entities = self.client.discovery.dsl_search(owned_resources_query) for entity in entities.entities or list(): resource_guids.add(entity.guid) if resource_guids: resource_guids_chunks = AtlasProxy.split_list_to_chunks(list(resource_guids), 100) for chunk in resource_guids_chunks: entities = self.client.entity.get_entities_by_guids(guids=list(chunk), ignore_relationships=True) resources += serialize_function(entities) else: LOGGER.info(f'User ({user_id}) does not own any "{resource_type}"') return resources @staticmethod def split_list_to_chunks(input_list: List[Any], n: int) -> Generator: """Yield successive n-sized chunks from lst.""" for i in range(0, len(input_list), n): yield input_list[i:i + n] def _get_resource_by_user_relation(self, user_email: str, relation_type: UserResourceRel, resource_type: ResourceType) -> Dict[str, Any]: resources: List[Union[PopularTable, DashboardSummary]] = list() if resource_type.name == ResourceType.Table.name: resource = ResourceType.Table.name.lower() elif resource_type.name == ResourceType.Dashboard.name: resource = ResourceType.Dashboard.name.lower() else: raise NotImplementedError(f'Resource type {resource_type.name} not supported.') if relation_type == UserResourceRel.follow: resources = self._get_resources_followed_by_user(user_id=user_email, resource_type=resource_type.name) elif relation_type == UserResourceRel.own: resources = self._get_resources_owned_by_user(user_id=user_email, resource_type=resource_type.name) return {resource: resources} def get_dashboard_by_user_relation(self, *, user_email: str, relation_type: UserResourceRel) -> Dict[str, Any]: return self._get_resource_by_user_relation(user_email, relation_type, ResourceType.Dashboard) def get_table_by_user_relation(self, *, user_email: str, relation_type: UserResourceRel) -> Dict[str, Any]: return self._get_resource_by_user_relation(user_email, relation_type, ResourceType.Table) def get_frequently_used_tables(self, *, user_email: str) -> Dict[str, List[PopularTable]]: user = self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.user, uniq_attributes=[ (AtlasCommonParams.qualified_name, user_email)]).entity readers_guids = [] for user_reads in self._filter_active(user[AtlasCommonParams.relationships].get('entityReads')): readers_guids.append(user_reads.get(AtlasCommonParams.guid)) readers = self.client.entity.get_entities_by_guids(guids=list(readers_guids), ignore_relationships=True) _results = {} for reader in readers.entities or list(): entity_uri = reader.attributes.get(AtlasCommonParams.uri) count = reader.attributes.get('count') if count: table_info = AtlasTableKey(entity_uri).get_details() _results[count] = dict(cluster=table_info.get('cluster'), name=table_info.get('table'), schema=table_info.get('schema'), database=table_info.get('database')) sorted_counts = sorted(_results.keys()) results = [] for count in sorted_counts: data: dict = _results.get(count, dict()) table = PopularTable(**data) results.append(table) return {'table': results} def add_resource_relation_by_user(self, *, id: str, user_id: str, relation_type: UserResourceRel, resource_type: ResourceType) -> None: if resource_type not in [ResourceType.Table, ResourceType.Dashboard]: raise NotImplementedError(f'resource type {resource_type} is not supported') entity = self._get_bookmark_entity(entity_uri=id, user_id=user_id, resource_type=resource_type) # type: ignore entity.entity[AtlasCommonParams.attributes][AtlasStatus.ACTIVE.lower()] = True self.client.entity.update_entity(entity) def delete_resource_relation_by_user(self, *, id: str, user_id: str, relation_type: UserResourceRel, resource_type: ResourceType) -> None: if resource_type not in [ResourceType.Table, ResourceType.Dashboard]: raise NotImplementedError(f'resource type {resource_type} is not supported') entity = self._get_bookmark_entity(entity_uri=id, user_id=user_id, resource_type=resource_type) # type: ignore entity.entity[AtlasCommonParams.attributes][AtlasStatus.ACTIVE.lower()] = False self.client.entity.update_entity(entity) def _parse_date(self, date: int) -> Optional[int]: try: date_str = str(date) date_trimmed = date_str[:10] assert len(date_trimmed) == 10 return int(date_trimmed) except Exception: return None def _get_readers(self, entity: AtlasEntityWithExtInfo, model: Any = Reader, top: Optional[int] = 15) \ -> List[Union[Reader, User]]: _readers = entity.get(AtlasCommonParams.relationships, dict()).get('readers', list()) guids = [_reader.get(AtlasCommonParams.guid) for _reader in self._filter_active(_readers)] if not guids: return [] readers = self.client.entity.get_entities_by_guids(guids=list(guids), ignore_relationships=False) _result = [] for _reader in readers.entities or list(): read_count = _reader.attributes['count'] if read_count >= int(app.config['POPULAR_RESOURCES_MINIMUM_READER_COUNT']): reader_qn = _reader.relationshipAttributes['user']['displayText'] reader_details = self._get_user_details(reader_qn) if model == Reader: reader = Reader(user=User(**reader_details), read_count=read_count) elif model == User: reader = User(**reader_details) else: return [] _result.append(reader) if model == Reader: result = sorted(_result, key=attrgetter('read_count'), reverse=True)[:top] else: result = _result result = result[:top] return result def _get_application(self, entity: AtlasEntityWithExtInfo) -> Optional[Application]: _applications = entity.get(AtlasCommonParams.relationships, dict()).get('applications', list()) guids = [a.get(AtlasCommonParams.guid) for a in self._filter_active(_applications)] if not guids: return None applications = self.client.entity.get_entities_by_guids(guids=list(guids), ignore_relationships=False) for _app in applications.entities or list(): url = _app.attributes.get('application_url', '') description = _app.attributes.get('description', '') id = _app.attributes.get('id', '') name = _app.attributes.get('name', '') app = Application(application_url=url, description=description, id=id, name=name) # only single app per table is supported break return app def _get_programmatic_descriptions(self, parameters: dict) -> List[ProgrammaticDescription]: programmatic_descriptions: Dict[str, ProgrammaticDescription] = {} for source, text in parameters.items(): use_parameter = True for regex_filter in app.config['PROGRAMMATIC_DESCRIPTIONS_EXCLUDE_FILTERS']: pattern = re.compile(regex_filter) if pattern.match(source): use_parameter = False break if use_parameter: source = re.sub("([a-z])([A-Z])", "\g<1> \g<2>", source).lower() programmatic_descriptions[source] = ProgrammaticDescription(source=source, text=text) result = dict(sorted(programmatic_descriptions.items())) return list(result.values()) def _serialize_dashboard_queries(self, queries: List[Dict]) -> List[DashboardQuery]: """ Renders DashboardQuery from attributes :param queries: list of dicts with query attributes :returns List of DashboardQuery objects. """ result = [] for query in queries: name = query.get('name', '') query_text = query.get('queryText', '') url = query.get('url', '') dashboard_query = DashboardQuery(name=name, query_text=query_text, url=url) result.append(dashboard_query) return result def _get_dashboard_group(self, group_guid: str) -> AtlasEntityWithExtInfo: """ Return raw DashboardGroup entity. :param group_guid: guid of dashboard group entity. :return : Atlas DashboardGroup entity. """ entity = self.client.entity.get_entities_by_guids(guids=[group_guid]).entities[0] return entity def _get_dashboard_summary(self, entity: AtlasEntityWithExtInfo, executions: List[AtlasEntity]) -> Dict: attributes = entity.entity[AtlasCommonParams.attributes] relationships = entity.entity[AtlasCommonParams.relationships] group = self._get_dashboard_group(relationships.get('group').get(AtlasCommonParams.guid))[ AtlasCommonParams.attributes] successful_executions = [e for e in executions if e.get('state') == 'succeeded'] try: last_successful_execution = successful_executions[0] except IndexError: last_successful_execution = dict(timestamp=0) chart_names = [e[AtlasCommonParams.attributes]['name'] for _, e in entity['referredEntities'].items() if e['typeName'] == AtlasDashboardTypes.chart] result = dict( uri=attributes.get(AtlasCommonParams.qualified_name, ''), cluster=attributes.get('cluster', ''), group_name=relationships.get('group', dict()).get('displayText', ''), group_url=group.get('url', ''), product=attributes.get('product', ''), name=attributes.get('name', ''), url=attributes.get('url', ''), last_successful_run_timestamp=last_successful_execution.get('timestamp', 0), description=attributes.get('description', ''), chart_names=chart_names) return result def _get_dashboard_details(self, entity: AtlasEntityWithExtInfo) -> Dict: try: attributes = entity.entity[AtlasCommonParams.attributes] relationships = entity.entity[AtlasCommonParams.relationships] referred_entities = entity['referredEntities'] badges = self._serialize_badges(entity) tags = self._serialize_tags(entity) _executions = [] _queries = [] for k, v in referred_entities.items(): entity_type = v.get('typeName') _attributes = v[AtlasCommonParams.attributes] if entity_type == AtlasDashboardTypes.execution: _executions.append(_attributes) elif entity_type == AtlasDashboardTypes.query: _queries.append(_attributes) queries = self._serialize_dashboard_queries(_queries) query_names = [q.name for q in queries] table_guids = [t.get(AtlasCommonParams.guid) for t in self._filter_active(relationships.get('tables', []))] if table_guids: _tables = self.client.entity.get_entities_by_guids(guids=table_guids) tables = self._serialize_popular_tables(_tables) else: tables = [] executions_attributes = sorted(_executions, key=lambda x: x.get('timestamp', 0), reverse=True) try: last_execution = executions_attributes[0] except IndexError: last_execution = dict(timestamp=0, state='Unknown') owners = self._get_owners(relationships.get('ownedBy', [])) readers = self._get_readers(entity.entity, User) result = self._get_dashboard_summary(entity, executions_attributes) extra_spec = dict( created_timestamp=attributes.get('createdTimestamp', 0), updated_timestamp=attributes.get('lastModifiedTimestamp', 0), owners=owners, last_run_timestamp=last_execution.get('timestamp', 0), last_run_state=last_execution.get('state', 'Unknown'), query_names=query_names, queries=queries, tables=tables, tags=tags, badges=badges, recent_view_count=attributes.get('popularityScore', 0), frequent_users=readers) result.update(extra_spec) return result except Exception as e: raise e def _get_dashboard(self, qualified_name: str) -> AtlasEntityWithExtInfo: """ Return raw Dasboard entity. :param qualified_name: qualified name of the dashboard :return : Atlas Dashboard entity. """ entity = self.client.entity.get_entity_by_attribute(type_name=AtlasDashboardTypes.metadata, uniq_attributes=[ (AtlasCommonParams.qualified_name, qualified_name)]) return entity def get_dashboard(self, id: str) -> DashboardDetailEntity: entity = self._get_dashboard(id) attributes = self._get_dashboard_details(entity) return DashboardDetailEntity(**attributes) def get_dashboard_description(self, *, id: str) -> Description: """ Return dashboard description. :param id: :return: The description of the dashboard as a string """ entity = self.client.entity.get_entity_by_attribute(type_name=AtlasDashboardTypes.metadata, uniq_attributes=[(AtlasCommonParams.qualified_name, id)]) return entity.entity[AtlasCommonParams.attributes].get('description') def put_dashboard_description(self, *, id: str, description: str) -> None: """ Update the description of the given dashboard. :param id: dashboard id (uri) :param description: Description string :return: None """ entity = self.client.entity.get_entity_by_attribute(type_name=AtlasDashboardTypes.metadata, uniq_attributes=[(AtlasCommonParams.qualified_name, id)]) self.client.entity.partial_update_entity_by_guid( entity_guid=entity.entity.get(AtlasCommonParams.guid), attr_value=description, attr_name='description' ) def _serialize_dashboard_summaries(self, entities: AtlasEntitiesWithExtInfo) -> List[DashboardSummary]: """ Returns dashboards summary for dashboards using specific table. """ result = [] for _dashboard in entities.entities: try: if _dashboard.status == AtlasStatus.ACTIVE: executions = [ entities['referredEntities'].get(e.get(AtlasCommonParams.guid))[AtlasCommonParams.attributes] for e in self._filter_active( _dashboard[AtlasCommonParams.relationships].get('executions', []))] dashboard = AtlasEntityWithExtInfo(attrs=dict(entity=_dashboard, referredEntities={})) summary = DashboardSummary(**self._get_dashboard_summary(dashboard, executions)) result.append(summary) except (KeyError, AttributeError): LOGGER.exception(f'Error while accessing table report: {str(dashboard)}.', exc_info=True) return result def get_resources_using_table(self, *, id: str, resource_type: ResourceType) -> Dict[str, List[DashboardSummary]]: if resource_type == ResourceType.Dashboard: resource = 'dashboards' serialize_function = self._serialize_dashboard_summaries else: raise NotImplementedError(f'{resource_type} is not supported') table = self._get_table_entity(table_uri=id) guids = [d.get(AtlasCommonParams.guid) for d in self._filter_active(table.entity[AtlasCommonParams.relationships].get(resource, []))] if guids: entities = self.client.entity.get_entities_by_guids(guids=guids) result = serialize_function(entities) else: result = [] return {resource: result} @classmethod def _generate_edges(cls, graph: Dict[str, List[str]]) -> List[Tuple[str, str]]: """ Generates list of edge pairs from the graph. :param graph: Graph of nodes :return: List of tuples with graph edges """ edges = [] # for each node in graph for node in graph: # for each neighbour node of a single node for neighbour in graph[node]: # if edge exists then append edges.append((node, neighbour)) return edges @classmethod def _find_shortest_path(cls, graph: Dict[str, List[str]], start: str, end: str, path: List[Any] = []) -> List[str]: """ Find shortest path between graph nodes. Used to calculate 'level' parameter __source__='https://www.python.org/doc/essays/graphs/' __author__='Guido van Rossum' :param graph: Dictionary of str (node key) and List[str] (connected nodes) :param start: Starting node for finding the path :param end: Ending node for finding the path :param path: Accumulator for recursive calls :return: Shortest path between start and end nodes """ path = path + [start] if start == end: return path if not graph.get(start): return [] shortest: List[str] = [] for node in graph[start]: if node not in path: newpath = AtlasProxy._find_shortest_path(graph, node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest @staticmethod def _find_parent_nodes(graph: Dict) -> Dict[str, Set[str]]: """ Rewrite graph dict to the form that makes it possible to easily :param graph: Dictionary of str (node key) and List[str] :return: Dict with keys (node) and values (parents of a node) """ relations: Dict[str, Set[str]] = {} for parent, ancestors in graph.items(): for ancestor in ancestors: if not relations.get(ancestor): relations[ancestor] = set() relations[ancestor].add(parent) return relations def _get_lineage_graph(self, lineage: Dict, entity_type: str, key_class: Any) -> Dict[str, List[str]]: """ Since Atlas bases lineage on additional entity (Process(input=A, output=B)) for capturing lineage we need to create graph that has direct A > B relationships and removes Process entities. :param lineage: Raw linage captured from Atlas :param entity_type: Type of entity for which lineage is captured :param key_class: Helper class used for Amundsen key <> Atlas qualified name serialization/deserialization :return: Graph of nodes with relations. """ processes: Dict[str, Dict[str, Any]] = dict() entity_type = entity_type.lower() entities = lineage.get('guidEntityMap', dict()) relations = lineage.get('relations', []) for relation in relations: input_guid = relation['fromEntityId'] input_type = entities.get(input_guid)['typeName'].lower() output_guid = relation['toEntityId'] output_type = entities.get(output_guid)['typeName'].lower() if input_type.endswith('process') and output_type.endswith(entity_type): output_qn = entities.get(output_guid)[AtlasCommonParams.attributes][AtlasCommonParams.qualified_name] output_key = key_class(output_qn, output_type).amundsen_key # type: ignore if not processes.get(input_guid): processes[input_guid] = dict(inputs=set(), outputs=set()) processes[input_guid]['outputs'].add(output_key) elif output_type.endswith('process') and input_type.endswith(entity_type): input_qn = entities.get(input_guid)[AtlasCommonParams.attributes][AtlasCommonParams.qualified_name] input_key = key_class(input_qn, input_type).amundsen_key # type: ignore if not processes.get(output_guid): processes[output_guid] = dict(inputs=set(), outputs=set()) processes[output_guid]['inputs'].add(input_key) graph: Dict[str, List[str]] = defaultdict(list) for _, spec in processes.items(): for input_key in spec['inputs']: for output_key in spec['outputs']: graph[input_key].append(output_key) return dict(graph) def _serialize_lineage_item(self, edge: Tuple[str, str], direction: str, key_class: Any, graph: Dict, root_node: str, parent_nodes: Dict[str, Set[str]]) -> List[LineageItem]: """ Serializes LineageItem object. :param edge: tuple containing two node keys that are connected with each other. :param direction: Lineage direction upstream/downstream :param key_class: Helper class used for managing Atlas <> Amundsen key formats. :param: graph: Graph from which the edge was derived from. Used to find distance between edge node and entity for which lineage is retrieved. :param parent_nodes: Dict of keys (nodes) with set of keys (parents). :return: Serialized LineageItem list. """ result: List[LineageItem] = [] if direction == 'upstream': key, _ = edge level = len(AtlasProxy._find_shortest_path(graph, key, root_node)) - 1 elif direction == 'downstream': _, key = edge level = len(AtlasProxy._find_shortest_path(graph, root_node, key)) - 1 else: raise ValueError(f'Direction {direction} not supported!') parents = parent_nodes.get(key, ['']) while True: try: parent = parents.pop() except Exception: break badges: List[str] = [] usage = 0 source = key_class(key).get_details()['database'] spec = dict(key=key, parent=parent, source=source, badges=badges, usage=usage, level=level) result.append(LineageItem(**spec)) return result def _serialize_lineage(self, lineage: dict, entity_type: str, root_node: str, direction: str, key_class: Union[Type[AtlasTableKey], Type[AtlasColumnKey]]) -> List[LineageItem]: """ Serializes lineage to Amundsen format based on Atlas lineage output. The assumption for Atlas <> Amundsen lineage is that every Process entity in Atlas lineage contains at least one entity of entity_type both in inputs and outputs. If your lineage is A > B > C where: A - is table B - is file C - is table It won't render A > C table lineage in Amundsen. The implementation follows simplified set of expectations and might be subject of change if such requirement arises. :param lineage: Raw lineage from Atlas :param entity_type: Type of the entity for which lineage is being retrieved :param root_node: key of entity for which lineage will be rendered. Required to calculate 'level' dynamically based on nodes distance. :param direction: upstream/downstream :param key_class: Class for serializing entities keys :return: The Lineage object with upstream & downstream lineage items """ result: List[LineageItem] = [] graph = self._get_lineage_graph(lineage, entity_type, key_class) edges = AtlasProxy._generate_edges(graph) parent_nodes = self._find_parent_nodes(graph) for edge in edges: lineage_items = self._serialize_lineage_item(edge, direction, key_class, graph, root_node, parent_nodes) result += lineage_items return result def get_lineage(self, *, id: str, resource_type: ResourceType, direction: str, depth: int) -> Lineage: """ Retrieves the lineage information for the specified resource type. :param id: Key of entity for which lineage will be collected :param resource_type: Type of the entity for which lineage is being retrieved :param direction: Whether to get the upstream/downstream or both directions :param depth: Depth or level of lineage information. 0=only parent, 1=immediate nodes, 2=... :return: The Lineage object with upstream & downstream lineage items """ lineage_spec: Dict[str, Any] = dict(key=id, direction=direction, depth=depth, upstream_entities=[], downstream_entities=[]) # Atlas returns complete lineage when depth=0. In Amundsen depth=0 means only parent. if depth > 0: key_class: Union[Type[AtlasTableKey], Type[AtlasColumnKey]] if resource_type == ResourceType.Column: key_class = AtlasColumnKey elif resource_type == ResourceType.Table: key_class = AtlasTableKey else: raise NotImplementedError(f'Resource {resource_type.name} not supported!') key = key_class(id) # type: ignore entity = self.client.entity.get_entity_by_attribute(type_name=resource_type.name, uniq_attributes=[(AtlasCommonParams.qualified_name, key.qualified_name)]) entity_guid = entity.entity.guid _upstream: Dict[str, Any] = {} _downstream: Dict[str, Any] = {} if not direction == 'downstream': _upstream = self.client.lineage.get_lineage_info(entity_guid, 'INPUT', depth) if not direction == 'upstream': _downstream = self.client.lineage.get_lineage_info(entity_guid, 'OUTPUT', depth) upstream = self._serialize_lineage(_upstream, resource_type.name, id, 'upstream', key_class) downstream = self._serialize_lineage(_downstream, resource_type.name, id, 'downstream', key_class) lineage_spec['upstream_entities'] = upstream lineage_spec['downstream_entities'] = downstream lineage = Lineage(**lineage_spec) return lineage def get_feature(self, *, feature_uri: str) -> Feature: pass def get_resource_description(self, *, resource_type: ResourceType, uri: str) -> Description: pass def put_resource_description(self, *, resource_type: ResourceType, uri: str, description: str) -> None: pass def add_resource_owner(self, *, uri: str, resource_type: ResourceType, owner: str) -> None: pass def delete_resource_owner(self, *, uri: str, resource_type: ResourceType, owner: str) -> None: pass def get_resource_generation_code(self, *, uri: str, resource_type: ResourceType) -> GenerationCode: pass def get_popular_resources(self, *, num_entries: int, resource_types: List[str], user_id: Optional[str] = None) -> Dict[str, List]: raise NotImplementedError
42.394629
120
0.592382
import datetime import logging import re from collections import defaultdict from operator import attrgetter from random import randint from typing import (Any, Dict, Generator, List, Optional, Set, Tuple, Type, Union) from amundsen_common.entity.resource_type import ResourceType from amundsen_common.models.dashboard import DashboardSummary from amundsen_common.models.feature import Feature from amundsen_common.models.generation_code import GenerationCode from amundsen_common.models.lineage import Lineage, LineageItem from amundsen_common.models.popular_table import PopularTable from amundsen_common.models.table import (Application, Badge, Column, ProgrammaticDescription, Reader, ResourceReport, Stat, Table, Tag, User, Watermark) from amundsen_common.models.user import User as UserEntity from amundsen_common.utils.atlas import (AtlasColumnKey, AtlasCommonParams, AtlasCommonTypes, AtlasDashboardTypes, AtlasStatus, AtlasTableKey, AtlasTableTypes) from apache_atlas.client.base_client import AtlasClient from apache_atlas.model.glossary import (AtlasGlossary, AtlasGlossaryHeader, AtlasGlossaryTerm) from apache_atlas.model.instance import (AtlasEntitiesWithExtInfo, AtlasEntity, AtlasEntityHeader, AtlasEntityWithExtInfo, AtlasRelatedObjectId) from apache_atlas.model.relationship import AtlasRelationship from apache_atlas.utils import type_coerce from beaker.cache import CacheManager from beaker.util import parse_cache_config_options from flask import current_app as app from werkzeug.exceptions import BadRequest from metadata_service.entity.dashboard_detail import \ DashboardDetail as DashboardDetailEntity from metadata_service.entity.dashboard_query import DashboardQuery from metadata_service.entity.description import Description from metadata_service.entity.tag_detail import TagDetail from metadata_service.exception import NotFoundException from metadata_service.proxy import BaseProxy from metadata_service.util import UserResourceRel LOGGER = logging.getLogger(__name__) _ATLAS_PROXY_CACHE_EXPIRY_SEC = 11 * 60 * 60 + randint(0, 3600) class AtlasProxy(BaseProxy): DB_ATTRIBUTE = 'db' STATISTICS_FORMAT_SPEC = app.config['STATISTICS_FORMAT_SPEC'] AMUNDSEN_USER_TAGS = 'amundsen_user_tags' _CACHE = CacheManager(**parse_cache_config_options({'cache.regions': 'atlas_proxy', 'cache.atlas_proxy.type': 'memory', 'cache.atlas_proxy.expire': _ATLAS_PROXY_CACHE_EXPIRY_SEC})) def __init__(self, *, host: str, port: int, user: str = 'admin', password: str = '', encrypted: bool = False, validate_ssl: bool = False, client_kwargs: dict = dict()) -> None: protocol = 'https' if encrypted else 'http' self.client = AtlasClient(f'{protocol}://{host}:{port}', (user, password)) self.client.session.verify = validate_ssl def _parse_dashboard_bookmark_qn(self, bookmark_qn: str) -> Dict: pattern = re.compile(r""" ^(?P<product>[^.]*)_dashboard :// (?P<cluster>[^.]*) \. (?P<dashboard_group>[^.]*) / (?P<dashboard_id>[^.]*) / (?P<type>[^.]*) / bookmark / (?P<user_id>[^.]*) $ """, re.X) result = pattern.match(bookmark_qn) return result.groupdict() if result else dict() def _parse_table_bookmark_qn(self, bookmark_qn: str) -> Dict: pattern = re.compile(r""" ^(?P<db>[^.]*) \. (?P<table>[^.]*) \. (?P<entity_type>[^.]*) \. (?P<user_id>[^.]*)\.bookmark \@ (?P<cluster>.*) $ """, re.X) result = pattern.match(bookmark_qn) return result.groupdict() if result else dict() @classmethod def _filter_active(cls, entities: List[dict]) -> List[dict]: result = [e for e in entities if e.get('relationshipStatus') == AtlasStatus.ACTIVE and e.get('entityStatus') == AtlasStatus.ACTIVE] return result def _get_table_entity(self, *, table_uri: str) -> AtlasEntityWithExtInfo: key = AtlasTableKey(table_uri) try: return self.client.entity.get_entity_by_attribute(type_name=key.entity_type, uniq_attributes=[ (AtlasCommonParams.qualified_name, key.qualified_name)]) except Exception as ex: LOGGER.exception(f'Table not found. {str(ex)}') raise NotFoundException(f'Table URI( {table_uri} ) does not exist') def _get_user_entity(self, user_id: str) -> AtlasEntityWithExtInfo: try: return self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.user, uniq_attributes=[ (AtlasCommonParams.qualified_name, user_id)]) except Exception: raise NotFoundException(f'(User {user_id}) does not exist') def _create_bookmark(self, entity: AtlasEntityWithExtInfo, user_guid: str, bookmark_qn: str, entity_uri: str) -> None: bookmark_entity = { 'entity': { 'typeName': AtlasCommonTypes.bookmark, AtlasCommonParams.attributes: { AtlasCommonParams.qualified_name: bookmark_qn, AtlasStatus.ACTIVE.lower(): True, 'entityUri': entity_uri, 'entityName': entity.entity[AtlasCommonParams.attributes]['name'], 'user': {AtlasCommonParams.guid: user_guid}, 'entity': {AtlasCommonParams.guid: entity.entity[AtlasCommonParams.guid]}} } } bookmark_entity = type_coerce(bookmark_entity, AtlasEntityWithExtInfo) self.client.entity.create_entity(bookmark_entity) def _get_bookmark_entity(self, entity_uri: str, user_id: str, resource_type: ResourceType) -> AtlasEntityWithExtInfo: if resource_type == ResourceType.Table: entity_info = AtlasTableKey(entity_uri).get_details() schema = entity_info.get('schema') table = entity_info.get('table') database = entity_info.get('database', 'hive_table') cluster = entity_info.get('cluster') bookmark_qn = f'{schema}.{table}.{database}.{user_id}.bookmark@{cluster}' else: bookmark_qn = f'{entity_uri}/{resource_type.name.lower()}/bookmark/{user_id}' try: bookmark_entity = self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.bookmark, uniq_attributes=[ (AtlasCommonParams.qualified_name, bookmark_qn)]) except Exception as ex: LOGGER.exception(f'Bookmark not found. {str(ex)}') if resource_type == ResourceType.Table: bookmarked_entity = self._get_table_entity(table_uri=entity_uri) elif resource_type == ResourceType.Dashboard: bookmarked_entity = self._get_dashboard(qualified_name=entity_uri) else: raise NotImplementedError(f'Bookmarks for Resource Type ({resource_type}) are not yet implemented') user_entity = self._get_user_entity(user_id) self._create_bookmark(bookmarked_entity, user_entity.entity[AtlasCommonParams.guid], bookmark_qn, entity_uri) bookmark_entity = self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.bookmark, uniq_attributes=[ (AtlasCommonParams.qualified_name, bookmark_qn)]) return bookmark_entity def _get_column(self, *, table_uri: str, column_name: str) -> Dict: try: table_entity = self._get_table_entity(table_uri=table_uri) columns = table_entity.entity[AtlasCommonParams.relationships].get('columns') for column in columns or list(): col_details = table_entity.referredEntities[column[AtlasCommonParams.guid]] if column_name == col_details[AtlasCommonParams.attributes]['name']: return col_details raise NotFoundException(f'Column not found: {column_name}') except KeyError as ex: LOGGER.exception(f'Column not found: {str(ex)}') raise NotFoundException(f'Column not found: {column_name}') def _serialize_columns(self, *, entity: AtlasEntityWithExtInfo) -> \ Union[List[Column], List]: columns = list() for column in entity.entity[AtlasCommonParams.relationships].get('columns') or list(): column_status = column.get('entityStatus', 'inactive').lower() if column_status != 'active': continue col_entity = entity.referredEntities[column[AtlasCommonParams.guid]] col_attrs = col_entity[AtlasCommonParams.attributes] statistics = list() badges = list() for column_classification in col_entity.get('classifications') or list(): if column_classification.get('entityStatus') == AtlasStatus.ACTIVE: name = column_classification.get('typeName') badges.append(Badge(badge_name=name, category='default')) for stats in col_attrs.get('statistics') or list(): stats_attrs = stats[AtlasCommonParams.attributes] stat_type = stats_attrs.get('stat_name') stat_format = self.STATISTICS_FORMAT_SPEC.get(stat_type, dict()) if not stat_format.get('drop', False): stat_type = stat_format.get('new_name', stat_type) stat_val = stats_attrs.get('stat_val') format_val = stat_format.get('format') if format_val: stat_val = format_val.format(stat_val) else: stat_val = str(stat_val) start_epoch = stats_attrs.get('start_epoch') end_epoch = stats_attrs.get('end_epoch') statistics.append( Stat( stat_type=stat_type, stat_val=stat_val, start_epoch=start_epoch, end_epoch=end_epoch, ) ) columns.append( Column( name=col_attrs.get('name'), description=col_attrs.get('description') or col_attrs.get('comment'), col_type=col_attrs.get('type') or col_attrs.get('dataType') or col_attrs.get('data_type'), sort_order=col_attrs.get('position') or 9999, stats=statistics, badges=badges ) ) return sorted(columns, key=lambda item: item.sort_order) def _get_reports(self, guids: List[str]) -> List[ResourceReport]: reports = [] if guids: report_entities = self.client.entity.get_entities_by_guids(guids=guids) for report_entity in report_entities.entities: try: if report_entity.status == AtlasStatus.ACTIVE: report_attrs = report_entity.attributes reports.append( ResourceReport( name=report_attrs['name'], url=report_attrs['url'] ) ) except (KeyError, AttributeError): LOGGER.exception(f'Error while accessing table report: {str(report_entity)}', exc_info=True) parsed_reports = app.config['RESOURCE_REPORT_CLIENT'](reports) \ if app.config['RESOURCE_REPORT_CLIENT'] else reports return sorted(parsed_reports) def _get_owners(self, data_owners: list, fallback_owner: str = None) -> List[User]: owners_detail = list() active_owners_list = list() for owner in self._filter_active(data_owners): owner_qn = owner['displayText'] owner_data = self._get_user_details(owner_qn) owners_detail.append(User(**owner_data)) active_owners_list.append(owner_qn) if fallback_owner and (fallback_owner not in active_owners_list): owners_detail.append(User(**self._get_user_details(fallback_owner))) return owners_detail def get_user(self, *, id: str) -> Union[UserEntity, None]: pass def create_update_user(self, *, user: User) -> Tuple[User, bool]: pass def get_users(self) -> List[UserEntity]: pass def _serialize_badges(self, entity: AtlasEntityWithExtInfo) -> List[Badge]: result = [] classifications = entity.get('classifications') for classification in classifications or list(): result.append(Badge(badge_name=classification.get('typeName'), category='default')) return result def _serialize_tags(self, entity: AtlasEntityWithExtInfo) -> List[Tag]: result = [] meanings = self._filter_active(entity.get(AtlasCommonParams.relationships, dict()).get('meanings', [])) for term in meanings or list(): result.append(Tag(tag_name=term.get('displayText', ''), tag_type='default')) return result def get_table(self, *, table_uri: str) -> Table: entity = self._get_table_entity(table_uri=table_uri) table_details = entity.entity try: attrs = table_details[AtlasCommonParams.attributes] programmatic_descriptions = self._get_programmatic_descriptions(attrs.get('parameters', dict()) or dict()) table_info = AtlasTableKey(attrs.get(AtlasCommonParams.qualified_name)).get_details() badges = self._serialize_badges(table_details) tags = self._serialize_tags(table_details) columns = self._serialize_columns(entity=entity) reports_guids = [report.get("guid") for report in attrs.get("reports") or list()] table_type = attrs.get('tableType') or 'table' is_view = 'view' in table_type.lower() readers = self._get_readers(table_details, Reader) application = self._get_application(table_details) table = Table( table_writer=application, database=AtlasTableKey(table_uri).get_details()['database'], cluster=table_info.get('cluster', ''), schema=table_info.get('schema', ''), name=attrs.get('name') or table_info.get('table', ''), badges=badges, tags=tags, description=attrs.get('description') or attrs.get('comment'), owners=self._get_owners( table_details[AtlasCommonParams.relationships].get('ownedBy', []), attrs.get('owner')), resource_reports=self._get_reports(guids=reports_guids), columns=columns, is_view=is_view, table_readers=readers, last_updated_timestamp=self._parse_date(table_details.get('updateTime')), programmatic_descriptions=programmatic_descriptions, watermarks=self._get_table_watermarks(table_details)) return table except KeyError: LOGGER.exception('Error while accessing table information. {}', exc_info=True) raise BadRequest(f'Some of the required attributes are missing in: {table_uri}') @staticmethod def _validate_date(text_date: str, date_format: str) -> Tuple[Optional[datetime.datetime], Optional[str]]: try: return datetime.datetime.strptime(text_date, date_format), date_format except (ValueError, TypeError): return None, None @staticmethod def _select_watermark_format(partition_names: Optional[List[Any]]) -> Optional[str]: result = None if partition_names: for partition_name in partition_names: for df in app.config['WATERMARK_DATE_FORMATS']: _, result = AtlasProxy._validate_date(partition_name, df) if result: LOGGER.debug('Established date format', extra=dict(date_format=result)) return result return result @staticmethod def _render_partition_key_name(entity: AtlasEntityWithExtInfo) -> Optional[str]: _partition_keys = [] for partition_key in entity.get(AtlasCommonParams.attributes, dict()).get('partitionKeys', []): partition_key_column_name = partition_key.get('displayName') if partition_key_column_name: _partition_keys.append(partition_key_column_name) partition_key = ' '.join(_partition_keys).strip() return partition_key def _get_table_watermarks(self, entity: AtlasEntityWithExtInfo) -> List[Watermark]: partition_value_format = '%Y-%m-%d %H:%M:%S' _partitions = entity.get(AtlasCommonParams.relationships, dict()).get('partitions', list()) names = [_partition.get('displayText') for _partition in self._filter_active(_partitions)] if not names: return [] partition_key = self._render_partition_key_name(entity) watermark_date_format = self._select_watermark_format(names) partitions = {} for _partition in _partitions: partition_name = _partition.get('displayText') if partition_name and watermark_date_format: partition_date, _ = self._validate_date(partition_name, watermark_date_format) if partition_date: common_values = {'partition_value': datetime.datetime.strftime(partition_date, partition_value_format), 'create_time': 0, 'partition_key': partition_key} partitions[partition_date] = common_values if partitions: low_watermark_date = min(partitions.keys()) high_watermark_date = max(partitions.keys()) low_watermark = Watermark(watermark_type='low_watermark', **partitions.get(low_watermark_date)) high_watermark = Watermark(watermark_type='high_watermark', **partitions.get(high_watermark_date)) return [low_watermark, high_watermark] else: return [] def delete_owner(self, *, table_uri: str, owner: str) -> None: table = self._get_table_entity(table_uri=table_uri) table_entity = table.entity if table_entity[AtlasCommonParams.relationships].get("ownedBy"): try: active_owner = next(filter(lambda item: item['relationshipStatus'] == AtlasStatus.ACTIVE and item['displayText'] == owner, table_entity[AtlasCommonParams.relationships]['ownedBy']), None) if active_owner: self.client.relationship.delete_relationship_by_guid( guid=active_owner.get('relationshipGuid') ) else: raise BadRequest('You can not delete this owner.') except Exception: LOGGER.exception('Error while removing table data owner.', exc_info=True) def add_owner(self, *, table_uri: str, owner: str) -> None: owner_info = self._get_user_details(owner) if not owner_info: raise NotFoundException(f'User "{owner}" does not exist.') user_dict = type_coerce({ "entity": { "typeName": "User", "attributes": {"qualifiedName": owner}, } }, AtlasEntityWithExtInfo) user_entity = self.client.entity.create_entity(user_dict) user_guid = next(iter(user_entity.guidAssignments.values())) table = self._get_table_entity(table_uri=table_uri) entity_def = { "typeName": "DataSet_Users_Owner", "end1": { "guid": table.entity.get("guid"), "typeName": "Table", }, "end2": { "guid": user_guid, "typeName": "User", }, } try: relationship = type_coerce(entity_def, AtlasRelationship) self.client.relationship.create_relationship(relationship=relationship) except Exception: LOGGER.exception('Error while adding the owner information. {}', exc_info=True) raise BadRequest(f'User {owner} is already added as a data owner for table {table_uri}.') def get_table_description(self, *, table_uri: str) -> Union[str, None]: entity = self._get_table_entity(table_uri=table_uri) return entity.entity[AtlasCommonParams.attributes].get('description') def put_table_description(self, *, table_uri: str, description: str) -> None: table = self._get_table_entity(table_uri=table_uri) self.client.entity.partial_update_entity_by_guid( entity_guid=table.entity.get("guid"), attr_value=description, attr_name='description' ) @_CACHE.cache('_get_user_defined_glossary_guid') def _get_user_defined_glossary_guid(self) -> str: glossaries = self.client.glossary.get_all_glossaries() for glossary in glossaries: if glossary.get(AtlasCommonParams.qualified_name) == self.AMUNDSEN_USER_TAGS: return glossary[AtlasCommonParams.guid] glossary_def = AtlasGlossary({"name": self.AMUNDSEN_USER_TAGS, "shortDescription": "Amundsen User Defined Terms"}) glossary = self.client.glossary.create_glossary(glossary_def) return glossary.guid @_CACHE.cache('_get_create_glossary_term') def _get_create_glossary_term(self, term_name: str) -> Union[AtlasGlossaryTerm, AtlasEntityHeader]: params = { 'typeName': "AtlasGlossaryTerm", 'excludeDeletedEntities': True, 'includeSubTypes': True, AtlasCommonParams.attributes: ["assignedEntities", ], 'entityFilters': {'condition': "AND", 'criterion': [{'attributeName': "name", 'operator': "=", 'attributeValue': term_name}] } } result = self.client.discovery.faceted_search(search_parameters=params) if result.approximateCount: term = result.entities[0] else: glossary_guid = self._get_user_defined_glossary_guid() glossary_def = AtlasGlossaryHeader({'glossaryGuid': glossary_guid}) term_def = AtlasGlossaryTerm({'name': term_name, 'anchor': glossary_def}) term = self.client.glossary.create_glossary_term(term_def) return term def add_tag(self, *, id: str, tag: str, tag_type: str = "default", resource_type: ResourceType = ResourceType.Table) -> None: entity = self._get_table_entity(table_uri=id) term = self._get_create_glossary_term(tag) related_entity = AtlasRelatedObjectId({AtlasCommonParams.guid: entity.entity[AtlasCommonParams.guid], "typeName": resource_type.name}) self.client.glossary.assign_term_to_entities(term.guid, [related_entity]) def add_badge(self, *, id: str, badge_name: str, category: str = '', resource_type: ResourceType) -> None: raise NotImplementedError def delete_tag(self, *, id: str, tag: str, tag_type: str, resource_type: ResourceType = ResourceType.Table) -> None: entity = self._get_table_entity(table_uri=id) term = self._get_create_glossary_term(tag) if not term: return assigned_entities = self.client.glossary.get_entities_assigned_with_term(term.guid, "ASC", -1, 0) for item in assigned_entities or list(): if item.get(AtlasCommonParams.guid) == entity.entity[AtlasCommonParams.guid]: related_entity = AtlasRelatedObjectId(item) return self.client.glossary.disassociate_term_from_entities(term.guid, [related_entity]) def delete_badge(self, *, id: str, badge_name: str, category: str, resource_type: ResourceType) -> None: raise NotImplementedError def put_column_description(self, *, table_uri: str, column_name: str, description: str) -> None: column_detail = self._get_column( table_uri=table_uri, column_name=column_name) col_guid = column_detail[AtlasCommonParams.guid] self.client.entity.partial_update_entity_by_guid( entity_guid=col_guid, attr_value=description, attr_name='description' ) def get_column_description(self, *, table_uri: str, column_name: str) -> Union[str, None]: column_detail = self._get_column( table_uri=table_uri, column_name=column_name) return column_detail[AtlasCommonParams.attributes].get('description') def _serialize_popular_tables(self, entities: AtlasEntitiesWithExtInfo) -> List[PopularTable]: popular_tables = list() for table in entities.entities or []: table_attrs = table.attributes table_info = AtlasTableKey(table_attrs.get(AtlasCommonParams.qualified_name)).get_details() table_name = table_info.get('table') or table_attrs.get('name') schema_name = table_info.get('schema', '') db_cluster = table_info.get('cluster', '') popular_table = PopularTable( database=table_info.get('database') or table.typeName, cluster=db_cluster, schema=schema_name, name=table_name, description=table_attrs.get('description') or table_attrs.get('comment')) popular_tables.append(popular_table) return popular_tables def get_popular_tables(self, *, num_entries: int, user_id: Optional[str] = None) -> List[PopularTable]: popular_query_params = {'typeName': AtlasTableTypes.table, 'sortBy': 'popularityScore', 'sortOrder': 'DESCENDING', 'excludeDeletedEntities': True, 'limit': num_entries} search_results = self.client.discovery.faceted_search(search_parameters=popular_query_params) return self._serialize_popular_tables(search_results) def get_latest_updated_ts(self) -> int: date = None metrics = self.client.admin.get_metrics() try: date = self._parse_date(metrics.general.get('stats', {}).get('Notification:lastMessageProcessedTime')) except AttributeError: pass return date or 0 def get_statistics(self) -> Dict[str, Any]: pass @_CACHE.cache('get_tags') def get_tags(self) -> List: tags = [] params = { 'typeName': "AtlasGlossaryTerm", 'limit': 1000, 'offset': 0, 'excludeDeletedEntities': True, 'includeSubTypes': True, AtlasCommonParams.attributes: ["assignedEntities", ] } glossary_terms = self.client.discovery.faceted_search(search_parameters=params) for item in glossary_terms.entities or list(): tags.append( TagDetail( tag_name=item.attributes.get("name"), tag_count=len(item.attributes.get("assignedEntities")) ) ) return tags @_CACHE.cache('get_badges') def get_badges(self) -> List: badges = list() metrics = self.client.admin.get_metrics() try: system_badges = metrics["tag"].get("tagEntities").keys() for item in system_badges: badges.append( Badge(badge_name=item, category="default") ) except AttributeError: LOGGER.info("No badges/classifications available in the system.") return badges def _get_resources_followed_by_user(self, user_id: str, resource_type: str) \ -> List[Union[PopularTable, DashboardSummary]]: if resource_type == ResourceType.Table.name: bookmark_qn_search_pattern = f'_{resource_type.lower()}.{user_id}.bookmark' else: bookmark_qn_search_pattern = f'/{resource_type.lower()}/bookmark/{user_id}' params = { 'typeName': AtlasCommonTypes.bookmark, 'offset': '0', 'limit': '1000', 'excludeDeletedEntities': True, 'entityFilters': { 'condition': 'AND', 'criterion': [ { 'attributeName': AtlasCommonParams.qualified_name, 'operator': 'contains', 'attributeValue': bookmark_qn_search_pattern }, { 'attributeName': AtlasStatus.ACTIVE.lower(), 'operator': 'eq', 'attributeValue': 'true' } ] }, AtlasCommonParams.attributes: ['count', AtlasCommonParams.qualified_name, AtlasCommonParams.uri, 'entityName'] } search_results = self.client.discovery.faceted_search(search_parameters=params) resources: List[Union[PopularTable, DashboardSummary]] = [] for record in search_results.entities or []: if resource_type == ResourceType.Table.name: table_info = AtlasTableKey(record.attributes[AtlasCommonParams.uri]).get_details() res = self._parse_table_bookmark_qn(record.attributes[AtlasCommonParams.qualified_name]) resources.append(PopularTable( database=table_info['database'], cluster=res['cluster'], schema=res['db'], name=res['table'])) elif resource_type == ResourceType.Dashboard.name: dashboard_info = self._parse_dashboard_bookmark_qn(record.attributes[AtlasCommonParams.qualified_name]) resources.append(DashboardSummary( uri=record.attributes[AtlasCommonParams.uri], cluster=dashboard_info['cluster'], name=record.attributes['entityName'], group_name=dashboard_info['dashboard_group'], group_url='', product=dashboard_info['product'], url='' )) else: raise NotImplementedError(f'resource type {resource_type} is not supported') return resources def _get_resources_owned_by_user(self, user_id: str, resource_type: str) \ -> List[Union[PopularTable, DashboardSummary, Any]]: resources: List[Union[PopularTable, DashboardSummary, Any]] = list() if resource_type == ResourceType.Table.name: type_regex = "(.*)_table$" entity_type = AtlasTableTypes.table serialize_function = self._serialize_popular_tables elif resource_type == ResourceType.Dashboard.name: type_regex = 'Dashboard' entity_type = AtlasDashboardTypes.metadata serialize_function = self._serialize_dashboard_summaries else: raise NotImplementedError(f'Resource Type ({resource_type}) is not yet implemented') user_entity = self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.user, uniq_attributes=[ ( AtlasCommonParams.qualified_name, user_id)]).entity if not user_entity: raise NotFoundException(f'User {user_id} not found.') resource_guids = set() for item in self._filter_active(user_entity[AtlasCommonParams.relationships].get('owns')) or list(): if re.compile(type_regex).match(item['typeName']): resource_guids.add(item[AtlasCommonParams.guid]) owned_resources_query = f'{entity_type} where owner like "{user_id.lower()}*" and __state = "ACTIVE"' entities = self.client.discovery.dsl_search(owned_resources_query) for entity in entities.entities or list(): resource_guids.add(entity.guid) if resource_guids: resource_guids_chunks = AtlasProxy.split_list_to_chunks(list(resource_guids), 100) for chunk in resource_guids_chunks: entities = self.client.entity.get_entities_by_guids(guids=list(chunk), ignore_relationships=True) resources += serialize_function(entities) else: LOGGER.info(f'User ({user_id}) does not own any "{resource_type}"') return resources @staticmethod def split_list_to_chunks(input_list: List[Any], n: int) -> Generator: for i in range(0, len(input_list), n): yield input_list[i:i + n] def _get_resource_by_user_relation(self, user_email: str, relation_type: UserResourceRel, resource_type: ResourceType) -> Dict[str, Any]: resources: List[Union[PopularTable, DashboardSummary]] = list() if resource_type.name == ResourceType.Table.name: resource = ResourceType.Table.name.lower() elif resource_type.name == ResourceType.Dashboard.name: resource = ResourceType.Dashboard.name.lower() else: raise NotImplementedError(f'Resource type {resource_type.name} not supported.') if relation_type == UserResourceRel.follow: resources = self._get_resources_followed_by_user(user_id=user_email, resource_type=resource_type.name) elif relation_type == UserResourceRel.own: resources = self._get_resources_owned_by_user(user_id=user_email, resource_type=resource_type.name) return {resource: resources} def get_dashboard_by_user_relation(self, *, user_email: str, relation_type: UserResourceRel) -> Dict[str, Any]: return self._get_resource_by_user_relation(user_email, relation_type, ResourceType.Dashboard) def get_table_by_user_relation(self, *, user_email: str, relation_type: UserResourceRel) -> Dict[str, Any]: return self._get_resource_by_user_relation(user_email, relation_type, ResourceType.Table) def get_frequently_used_tables(self, *, user_email: str) -> Dict[str, List[PopularTable]]: user = self.client.entity.get_entity_by_attribute(type_name=AtlasCommonTypes.user, uniq_attributes=[ (AtlasCommonParams.qualified_name, user_email)]).entity readers_guids = [] for user_reads in self._filter_active(user[AtlasCommonParams.relationships].get('entityReads')): readers_guids.append(user_reads.get(AtlasCommonParams.guid)) readers = self.client.entity.get_entities_by_guids(guids=list(readers_guids), ignore_relationships=True) _results = {} for reader in readers.entities or list(): entity_uri = reader.attributes.get(AtlasCommonParams.uri) count = reader.attributes.get('count') if count: table_info = AtlasTableKey(entity_uri).get_details() _results[count] = dict(cluster=table_info.get('cluster'), name=table_info.get('table'), schema=table_info.get('schema'), database=table_info.get('database')) sorted_counts = sorted(_results.keys()) results = [] for count in sorted_counts: data: dict = _results.get(count, dict()) table = PopularTable(**data) results.append(table) return {'table': results} def add_resource_relation_by_user(self, *, id: str, user_id: str, relation_type: UserResourceRel, resource_type: ResourceType) -> None: if resource_type not in [ResourceType.Table, ResourceType.Dashboard]: raise NotImplementedError(f'resource type {resource_type} is not supported') entity = self._get_bookmark_entity(entity_uri=id, user_id=user_id, resource_type=resource_type) entity.entity[AtlasCommonParams.attributes][AtlasStatus.ACTIVE.lower()] = True self.client.entity.update_entity(entity) def delete_resource_relation_by_user(self, *, id: str, user_id: str, relation_type: UserResourceRel, resource_type: ResourceType) -> None: if resource_type not in [ResourceType.Table, ResourceType.Dashboard]: raise NotImplementedError(f'resource type {resource_type} is not supported') entity = self._get_bookmark_entity(entity_uri=id, user_id=user_id, resource_type=resource_type) entity.entity[AtlasCommonParams.attributes][AtlasStatus.ACTIVE.lower()] = False self.client.entity.update_entity(entity) def _parse_date(self, date: int) -> Optional[int]: try: date_str = str(date) date_trimmed = date_str[:10] assert len(date_trimmed) == 10 return int(date_trimmed) except Exception: return None def _get_readers(self, entity: AtlasEntityWithExtInfo, model: Any = Reader, top: Optional[int] = 15) \ -> List[Union[Reader, User]]: _readers = entity.get(AtlasCommonParams.relationships, dict()).get('readers', list()) guids = [_reader.get(AtlasCommonParams.guid) for _reader in self._filter_active(_readers)] if not guids: return [] readers = self.client.entity.get_entities_by_guids(guids=list(guids), ignore_relationships=False) _result = [] for _reader in readers.entities or list(): read_count = _reader.attributes['count'] if read_count >= int(app.config['POPULAR_RESOURCES_MINIMUM_READER_COUNT']): reader_qn = _reader.relationshipAttributes['user']['displayText'] reader_details = self._get_user_details(reader_qn) if model == Reader: reader = Reader(user=User(**reader_details), read_count=read_count) elif model == User: reader = User(**reader_details) else: return [] _result.append(reader) if model == Reader: result = sorted(_result, key=attrgetter('read_count'), reverse=True)[:top] else: result = _result result = result[:top] return result def _get_application(self, entity: AtlasEntityWithExtInfo) -> Optional[Application]: _applications = entity.get(AtlasCommonParams.relationships, dict()).get('applications', list()) guids = [a.get(AtlasCommonParams.guid) for a in self._filter_active(_applications)] if not guids: return None applications = self.client.entity.get_entities_by_guids(guids=list(guids), ignore_relationships=False) for _app in applications.entities or list(): url = _app.attributes.get('application_url', '') description = _app.attributes.get('description', '') id = _app.attributes.get('id', '') name = _app.attributes.get('name', '') app = Application(application_url=url, description=description, id=id, name=name) break return app def _get_programmatic_descriptions(self, parameters: dict) -> List[ProgrammaticDescription]: programmatic_descriptions: Dict[str, ProgrammaticDescription] = {} for source, text in parameters.items(): use_parameter = True for regex_filter in app.config['PROGRAMMATIC_DESCRIPTIONS_EXCLUDE_FILTERS']: pattern = re.compile(regex_filter) if pattern.match(source): use_parameter = False break if use_parameter: source = re.sub("([a-z])([A-Z])", "\g<1> \g<2>", source).lower() programmatic_descriptions[source] = ProgrammaticDescription(source=source, text=text) result = dict(sorted(programmatic_descriptions.items())) return list(result.values()) def _serialize_dashboard_queries(self, queries: List[Dict]) -> List[DashboardQuery]: result = [] for query in queries: name = query.get('name', '') query_text = query.get('queryText', '') url = query.get('url', '') dashboard_query = DashboardQuery(name=name, query_text=query_text, url=url) result.append(dashboard_query) return result def _get_dashboard_group(self, group_guid: str) -> AtlasEntityWithExtInfo: entity = self.client.entity.get_entities_by_guids(guids=[group_guid]).entities[0] return entity def _get_dashboard_summary(self, entity: AtlasEntityWithExtInfo, executions: List[AtlasEntity]) -> Dict: attributes = entity.entity[AtlasCommonParams.attributes] relationships = entity.entity[AtlasCommonParams.relationships] group = self._get_dashboard_group(relationships.get('group').get(AtlasCommonParams.guid))[ AtlasCommonParams.attributes] successful_executions = [e for e in executions if e.get('state') == 'succeeded'] try: last_successful_execution = successful_executions[0] except IndexError: last_successful_execution = dict(timestamp=0) chart_names = [e[AtlasCommonParams.attributes]['name'] for _, e in entity['referredEntities'].items() if e['typeName'] == AtlasDashboardTypes.chart] result = dict( uri=attributes.get(AtlasCommonParams.qualified_name, ''), cluster=attributes.get('cluster', ''), group_name=relationships.get('group', dict()).get('displayText', ''), group_url=group.get('url', ''), product=attributes.get('product', ''), name=attributes.get('name', ''), url=attributes.get('url', ''), last_successful_run_timestamp=last_successful_execution.get('timestamp', 0), description=attributes.get('description', ''), chart_names=chart_names) return result def _get_dashboard_details(self, entity: AtlasEntityWithExtInfo) -> Dict: try: attributes = entity.entity[AtlasCommonParams.attributes] relationships = entity.entity[AtlasCommonParams.relationships] referred_entities = entity['referredEntities'] badges = self._serialize_badges(entity) tags = self._serialize_tags(entity) _executions = [] _queries = [] for k, v in referred_entities.items(): entity_type = v.get('typeName') _attributes = v[AtlasCommonParams.attributes] if entity_type == AtlasDashboardTypes.execution: _executions.append(_attributes) elif entity_type == AtlasDashboardTypes.query: _queries.append(_attributes) queries = self._serialize_dashboard_queries(_queries) query_names = [q.name for q in queries] table_guids = [t.get(AtlasCommonParams.guid) for t in self._filter_active(relationships.get('tables', []))] if table_guids: _tables = self.client.entity.get_entities_by_guids(guids=table_guids) tables = self._serialize_popular_tables(_tables) else: tables = [] executions_attributes = sorted(_executions, key=lambda x: x.get('timestamp', 0), reverse=True) try: last_execution = executions_attributes[0] except IndexError: last_execution = dict(timestamp=0, state='Unknown') owners = self._get_owners(relationships.get('ownedBy', [])) readers = self._get_readers(entity.entity, User) result = self._get_dashboard_summary(entity, executions_attributes) extra_spec = dict( created_timestamp=attributes.get('createdTimestamp', 0), updated_timestamp=attributes.get('lastModifiedTimestamp', 0), owners=owners, last_run_timestamp=last_execution.get('timestamp', 0), last_run_state=last_execution.get('state', 'Unknown'), query_names=query_names, queries=queries, tables=tables, tags=tags, badges=badges, recent_view_count=attributes.get('popularityScore', 0), frequent_users=readers) result.update(extra_spec) return result except Exception as e: raise e def _get_dashboard(self, qualified_name: str) -> AtlasEntityWithExtInfo: entity = self.client.entity.get_entity_by_attribute(type_name=AtlasDashboardTypes.metadata, uniq_attributes=[ (AtlasCommonParams.qualified_name, qualified_name)]) return entity def get_dashboard(self, id: str) -> DashboardDetailEntity: entity = self._get_dashboard(id) attributes = self._get_dashboard_details(entity) return DashboardDetailEntity(**attributes) def get_dashboard_description(self, *, id: str) -> Description: entity = self.client.entity.get_entity_by_attribute(type_name=AtlasDashboardTypes.metadata, uniq_attributes=[(AtlasCommonParams.qualified_name, id)]) return entity.entity[AtlasCommonParams.attributes].get('description') def put_dashboard_description(self, *, id: str, description: str) -> None: entity = self.client.entity.get_entity_by_attribute(type_name=AtlasDashboardTypes.metadata, uniq_attributes=[(AtlasCommonParams.qualified_name, id)]) self.client.entity.partial_update_entity_by_guid( entity_guid=entity.entity.get(AtlasCommonParams.guid), attr_value=description, attr_name='description' ) def _serialize_dashboard_summaries(self, entities: AtlasEntitiesWithExtInfo) -> List[DashboardSummary]: result = [] for _dashboard in entities.entities: try: if _dashboard.status == AtlasStatus.ACTIVE: executions = [ entities['referredEntities'].get(e.get(AtlasCommonParams.guid))[AtlasCommonParams.attributes] for e in self._filter_active( _dashboard[AtlasCommonParams.relationships].get('executions', []))] dashboard = AtlasEntityWithExtInfo(attrs=dict(entity=_dashboard, referredEntities={})) summary = DashboardSummary(**self._get_dashboard_summary(dashboard, executions)) result.append(summary) except (KeyError, AttributeError): LOGGER.exception(f'Error while accessing table report: {str(dashboard)}.', exc_info=True) return result def get_resources_using_table(self, *, id: str, resource_type: ResourceType) -> Dict[str, List[DashboardSummary]]: if resource_type == ResourceType.Dashboard: resource = 'dashboards' serialize_function = self._serialize_dashboard_summaries else: raise NotImplementedError(f'{resource_type} is not supported') table = self._get_table_entity(table_uri=id) guids = [d.get(AtlasCommonParams.guid) for d in self._filter_active(table.entity[AtlasCommonParams.relationships].get(resource, []))] if guids: entities = self.client.entity.get_entities_by_guids(guids=guids) result = serialize_function(entities) else: result = [] return {resource: result} @classmethod def _generate_edges(cls, graph: Dict[str, List[str]]) -> List[Tuple[str, str]]: edges = [] for node in graph: for neighbour in graph[node]: edges.append((node, neighbour)) return edges @classmethod def _find_shortest_path(cls, graph: Dict[str, List[str]], start: str, end: str, path: List[Any] = []) -> List[str]: path = path + [start] if start == end: return path if not graph.get(start): return [] shortest: List[str] = [] for node in graph[start]: if node not in path: newpath = AtlasProxy._find_shortest_path(graph, node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest @staticmethod def _find_parent_nodes(graph: Dict) -> Dict[str, Set[str]]: relations: Dict[str, Set[str]] = {} for parent, ancestors in graph.items(): for ancestor in ancestors: if not relations.get(ancestor): relations[ancestor] = set() relations[ancestor].add(parent) return relations def _get_lineage_graph(self, lineage: Dict, entity_type: str, key_class: Any) -> Dict[str, List[str]]: processes: Dict[str, Dict[str, Any]] = dict() entity_type = entity_type.lower() entities = lineage.get('guidEntityMap', dict()) relations = lineage.get('relations', []) for relation in relations: input_guid = relation['fromEntityId'] input_type = entities.get(input_guid)['typeName'].lower() output_guid = relation['toEntityId'] output_type = entities.get(output_guid)['typeName'].lower() if input_type.endswith('process') and output_type.endswith(entity_type): output_qn = entities.get(output_guid)[AtlasCommonParams.attributes][AtlasCommonParams.qualified_name] output_key = key_class(output_qn, output_type).amundsen_key if not processes.get(input_guid): processes[input_guid] = dict(inputs=set(), outputs=set()) processes[input_guid]['outputs'].add(output_key) elif output_type.endswith('process') and input_type.endswith(entity_type): input_qn = entities.get(input_guid)[AtlasCommonParams.attributes][AtlasCommonParams.qualified_name] input_key = key_class(input_qn, input_type).amundsen_key if not processes.get(output_guid): processes[output_guid] = dict(inputs=set(), outputs=set()) processes[output_guid]['inputs'].add(input_key) graph: Dict[str, List[str]] = defaultdict(list) for _, spec in processes.items(): for input_key in spec['inputs']: for output_key in spec['outputs']: graph[input_key].append(output_key) return dict(graph) def _serialize_lineage_item(self, edge: Tuple[str, str], direction: str, key_class: Any, graph: Dict, root_node: str, parent_nodes: Dict[str, Set[str]]) -> List[LineageItem]: result: List[LineageItem] = [] if direction == 'upstream': key, _ = edge level = len(AtlasProxy._find_shortest_path(graph, key, root_node)) - 1 elif direction == 'downstream': _, key = edge level = len(AtlasProxy._find_shortest_path(graph, root_node, key)) - 1 else: raise ValueError(f'Direction {direction} not supported!') parents = parent_nodes.get(key, ['']) while True: try: parent = parents.pop() except Exception: break badges: List[str] = [] usage = 0 source = key_class(key).get_details()['database'] spec = dict(key=key, parent=parent, source=source, badges=badges, usage=usage, level=level) result.append(LineageItem(**spec)) return result def _serialize_lineage(self, lineage: dict, entity_type: str, root_node: str, direction: str, key_class: Union[Type[AtlasTableKey], Type[AtlasColumnKey]]) -> List[LineageItem]: result: List[LineageItem] = [] graph = self._get_lineage_graph(lineage, entity_type, key_class) edges = AtlasProxy._generate_edges(graph) parent_nodes = self._find_parent_nodes(graph) for edge in edges: lineage_items = self._serialize_lineage_item(edge, direction, key_class, graph, root_node, parent_nodes) result += lineage_items return result def get_lineage(self, *, id: str, resource_type: ResourceType, direction: str, depth: int) -> Lineage: lineage_spec: Dict[str, Any] = dict(key=id, direction=direction, depth=depth, upstream_entities=[], downstream_entities=[]) if depth > 0: key_class: Union[Type[AtlasTableKey], Type[AtlasColumnKey]] if resource_type == ResourceType.Column: key_class = AtlasColumnKey elif resource_type == ResourceType.Table: key_class = AtlasTableKey else: raise NotImplementedError(f'Resource {resource_type.name} not supported!') key = key_class(id) entity = self.client.entity.get_entity_by_attribute(type_name=resource_type.name, uniq_attributes=[(AtlasCommonParams.qualified_name, key.qualified_name)]) entity_guid = entity.entity.guid _upstream: Dict[str, Any] = {} _downstream: Dict[str, Any] = {} if not direction == 'downstream': _upstream = self.client.lineage.get_lineage_info(entity_guid, 'INPUT', depth) if not direction == 'upstream': _downstream = self.client.lineage.get_lineage_info(entity_guid, 'OUTPUT', depth) upstream = self._serialize_lineage(_upstream, resource_type.name, id, 'upstream', key_class) downstream = self._serialize_lineage(_downstream, resource_type.name, id, 'downstream', key_class) lineage_spec['upstream_entities'] = upstream lineage_spec['downstream_entities'] = downstream lineage = Lineage(**lineage_spec) return lineage def get_feature(self, *, feature_uri: str) -> Feature: pass def get_resource_description(self, *, resource_type: ResourceType, uri: str) -> Description: pass def put_resource_description(self, *, resource_type: ResourceType, uri: str, description: str) -> None: pass def add_resource_owner(self, *, uri: str, resource_type: ResourceType, owner: str) -> None: pass def delete_resource_owner(self, *, uri: str, resource_type: ResourceType, owner: str) -> None: pass def get_resource_generation_code(self, *, uri: str, resource_type: ResourceType) -> GenerationCode: pass def get_popular_resources(self, *, num_entries: int, resource_types: List[str], user_id: Optional[str] = None) -> Dict[str, List]: raise NotImplementedError
true
true
f71109e10fcd45e0190f2d7900c8aab146d9538e
1,281
py
Python
run.py
DataScience-MD/ABM
291911e005df8db8b764cd3f9b16b38b735207eb
[ "MIT" ]
null
null
null
run.py
DataScience-MD/ABM
291911e005df8db8b764cd3f9b16b38b735207eb
[ "MIT" ]
null
null
null
run.py
DataScience-MD/ABM
291911e005df8db8b764cd3f9b16b38b735207eb
[ "MIT" ]
6
2020-06-18T21:47:20.000Z
2021-05-05T21:25:34.000Z
# -*- coding: utf-8 -*- """ Created on Wed Mar 25 12:13:19 2020 @author: metalcorebear """ from model import propagation_model import model_params import argparse import os import pandas as pd # Specify arguments def get_path(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--output', help='Enter the output path.', required=True) args = vars(parser.parse_args()) output_path = str(args['output']) return output_path # Generate output file name parameters output_path = get_path() density = model_params.parameters['density'] nodes = model_params.parameters['network_size'] neg_bias = model_params.parameters['neg_bias'] filename = 'ABM_' + str(density) + '_' + str(nodes) + '_' + str(neg_bias) + '.csv' output_file = os.path.join(output_path, filename) # Instantiate model meme_model = propagation_model() # Number of steps to run model. steps = model_params.parameters['steps'] for i in range(steps): print("Step: " + str(i)) meme_model.step() # Generate output output_data = meme_model.datacollector.get_model_vars_dataframe() output_data.to_csv(output_file, encoding='UTF8') print (output_data) print('Filename:') print(filename) print('You are a great American!!')
25.117647
88
0.697112
from model import propagation_model import model_params import argparse import os import pandas as pd def get_path(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--output', help='Enter the output path.', required=True) args = vars(parser.parse_args()) output_path = str(args['output']) return output_path output_path = get_path() density = model_params.parameters['density'] nodes = model_params.parameters['network_size'] neg_bias = model_params.parameters['neg_bias'] filename = 'ABM_' + str(density) + '_' + str(nodes) + '_' + str(neg_bias) + '.csv' output_file = os.path.join(output_path, filename) meme_model = propagation_model() steps = model_params.parameters['steps'] for i in range(steps): print("Step: " + str(i)) meme_model.step() output_data = meme_model.datacollector.get_model_vars_dataframe() output_data.to_csv(output_file, encoding='UTF8') print (output_data) print('Filename:') print(filename) print('You are a great American!!')
true
true
f7110a3a9b918590809e75600d33ed9e69f464fc
2,103
py
Python
vision/google/cloud/vision_v1p2beta1/types.py
deryrahman/google-cloud-python
b55058c4b2328fde32f29bfd8ea04708fcc578e0
[ "Apache-2.0" ]
1
2020-10-25T04:39:41.000Z
2020-10-25T04:39:41.000Z
vision/google/cloud/vision_v1p2beta1/types.py
deryrahman/google-cloud-python
b55058c4b2328fde32f29bfd8ea04708fcc578e0
[ "Apache-2.0" ]
4
2018-11-13T22:15:36.000Z
2018-12-07T18:31:38.000Z
vision/google/cloud/vision_v1p2beta1/types.py
deryrahman/google-cloud-python
b55058c4b2328fde32f29bfd8ea04708fcc578e0
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import sys from google.api_core.protobuf_helpers import get_messages from google.api import http_pb2 from google.cloud.vision_v1p2beta1.proto import geometry_pb2 from google.cloud.vision_v1p2beta1.proto import image_annotator_pb2 from google.cloud.vision_v1p2beta1.proto import text_annotation_pb2 from google.cloud.vision_v1p2beta1.proto import web_detection_pb2 from google.longrunning import operations_pb2 from google.protobuf import any_pb2 from google.protobuf import descriptor_pb2 from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 from google.protobuf import wrappers_pb2 from google.rpc import status_pb2 from google.type import color_pb2 from google.type import latlng_pb2 _shared_modules = [ http_pb2, operations_pb2, any_pb2, descriptor_pb2, empty_pb2, timestamp_pb2, wrappers_pb2, status_pb2, color_pb2, latlng_pb2, ] _local_modules = [ geometry_pb2, image_annotator_pb2, text_annotation_pb2, web_detection_pb2, ] names = [] for module in _shared_modules: for name, message in get_messages(module).items(): setattr(sys.modules[__name__], name, message) names.append(name) for module in _local_modules: for name, message in get_messages(module).items(): message.__module__ = 'google.cloud.vision_v1p2beta1.types' setattr(sys.modules[__name__], name, message) names.append(name) __all__ = tuple(sorted(names))
30.042857
74
0.770804
from __future__ import absolute_import import sys from google.api_core.protobuf_helpers import get_messages from google.api import http_pb2 from google.cloud.vision_v1p2beta1.proto import geometry_pb2 from google.cloud.vision_v1p2beta1.proto import image_annotator_pb2 from google.cloud.vision_v1p2beta1.proto import text_annotation_pb2 from google.cloud.vision_v1p2beta1.proto import web_detection_pb2 from google.longrunning import operations_pb2 from google.protobuf import any_pb2 from google.protobuf import descriptor_pb2 from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 from google.protobuf import wrappers_pb2 from google.rpc import status_pb2 from google.type import color_pb2 from google.type import latlng_pb2 _shared_modules = [ http_pb2, operations_pb2, any_pb2, descriptor_pb2, empty_pb2, timestamp_pb2, wrappers_pb2, status_pb2, color_pb2, latlng_pb2, ] _local_modules = [ geometry_pb2, image_annotator_pb2, text_annotation_pb2, web_detection_pb2, ] names = [] for module in _shared_modules: for name, message in get_messages(module).items(): setattr(sys.modules[__name__], name, message) names.append(name) for module in _local_modules: for name, message in get_messages(module).items(): message.__module__ = 'google.cloud.vision_v1p2beta1.types' setattr(sys.modules[__name__], name, message) names.append(name) __all__ = tuple(sorted(names))
true
true
f7110a923f1dfdc24b38657b7ed503e0e741a094
351
py
Python
cms_bs3_theme/context_processors.py
Nekmo/djangocms-bs3-theme
1155588414164d6e5d027131e9181856f8a80d5d
[ "MIT" ]
null
null
null
cms_bs3_theme/context_processors.py
Nekmo/djangocms-bs3-theme
1155588414164d6e5d027131e9181856f8a80d5d
[ "MIT" ]
10
2018-07-30T15:09:57.000Z
2022-03-29T21:54:12.000Z
cms_bs3_theme/context_processors.py
Nekmo/djangocms-bs3-theme
1155588414164d6e5d027131e9181856f8a80d5d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # from cms_bs3_theme.models import ThemeSite def settings(request): """ """ from . import conf conf = dict(vars(conf)) # conf.update(ThemeSite.objects.get_theme_conf(request=request, fail=False)) data = request.session.get('cms_bs3_theme_conf', {}) conf.update(data) return {'bs3_conf': conf}
25.071429
80
0.655271
def settings(request): from . import conf conf = dict(vars(conf)) data = request.session.get('cms_bs3_theme_conf', {}) conf.update(data) return {'bs3_conf': conf}
true
true
f7110d49a2e7fea67a97fd1616c5378611856817
836
py
Python
bin/tellopro.py
hgu-sit22005/telloproject-21800130
9f9e27c64d702982795311fcabfba6a2b6d5d1f2
[ "MIT" ]
null
null
null
bin/tellopro.py
hgu-sit22005/telloproject-21800130
9f9e27c64d702982795311fcabfba6a2b6d5d1f2
[ "MIT" ]
null
null
null
bin/tellopro.py
hgu-sit22005/telloproject-21800130
9f9e27c64d702982795311fcabfba6a2b6d5d1f2
[ "MIT" ]
null
null
null
from tello import Tello import sys from datetime import datetime import time import TelloPro tello = Tello() command_lst = [] command_lst.append(TelloPro.get_instance('takeoff', -1, "")) command_lst.append(TelloPro.get_instance('up', 30, "")) command_lst.append(TelloPro.get_instance('down', 30, "")) command_lst.append(TelloPro.get_instance('left', 30, "")) command_lst.append(TelloPro.get_instance('right', 30, "")) command_lst.append(TelloPro.get_instance('forward', 30, "")) command_lst.append(TelloPro.get_instance('back', 30, "")) command_lst.append(TelloPro.get_instance('cw', 60, "")) command_lst.append(TelloPro.get_instance('ccw', 60, "")) command_lst.append(TelloPro.get_instance('flip', -1, "l")) command_lst.append(TelloPro.get_instance('land', -1, "")) for command in command_lst: tello.send_command_instance(command)
34.833333
60
0.752392
from tello import Tello import sys from datetime import datetime import time import TelloPro tello = Tello() command_lst = [] command_lst.append(TelloPro.get_instance('takeoff', -1, "")) command_lst.append(TelloPro.get_instance('up', 30, "")) command_lst.append(TelloPro.get_instance('down', 30, "")) command_lst.append(TelloPro.get_instance('left', 30, "")) command_lst.append(TelloPro.get_instance('right', 30, "")) command_lst.append(TelloPro.get_instance('forward', 30, "")) command_lst.append(TelloPro.get_instance('back', 30, "")) command_lst.append(TelloPro.get_instance('cw', 60, "")) command_lst.append(TelloPro.get_instance('ccw', 60, "")) command_lst.append(TelloPro.get_instance('flip', -1, "l")) command_lst.append(TelloPro.get_instance('land', -1, "")) for command in command_lst: tello.send_command_instance(command)
true
true
f7110ed7a1c5c6ec8eedf0cbbdad38d01af37edd
5,451
py
Python
yt/frontends/_skeleton/data_structures.py
danielgrassinger/yt_new_frontend
5f91d2fb8721c4c5da0af543a6256ed979cd9fc9
[ "BSD-3-Clause-Clear" ]
null
null
null
yt/frontends/_skeleton/data_structures.py
danielgrassinger/yt_new_frontend
5f91d2fb8721c4c5da0af543a6256ed979cd9fc9
[ "BSD-3-Clause-Clear" ]
1
2016-04-05T22:30:14.000Z
2016-04-05T22:30:14.000Z
yt/frontends/_skeleton/data_structures.py
danielgrassinger/yt_new_frontend
5f91d2fb8721c4c5da0af543a6256ed979cd9fc9
[ "BSD-3-Clause-Clear" ]
1
2020-12-05T05:51:09.000Z
2020-12-05T05:51:09.000Z
""" Skeleton data structures """ #----------------------------------------------------------------------------- # Copyright (c) 2013, yt Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- from yt.data_objects.grid_patch import \ AMRGridPatch from yt.geometry.grid_geometry_handler import \ GridIndex from yt.data_objects.static_output import \ Dataset from .fields import SkeletonFieldInfo class SkeletonGrid(AMRGridPatch): _id_offset = 0 def __init__(self, id, index, level, start, dimensions): AMRGridPatch.__init__(self, id, filename=index.index_filename, index=index) self.Parent = [] self.Children = [] self.Level = level self.start_index = start.copy() self.stop_index = self.start_index + dimensions self.ActiveDimensions = dimensions.copy() def __repr__(self): return "SkeletonGrid_%04i (%s)" % (self.id, self.ActiveDimensions) class SkeletonHierarchy(GridIndex): grid = SkeletonGrid def __init__(self, ds, dataset_type='skeleton'): self.dataset_type = dataset_type # for now, the index file is the dataset! self.index_filename = self.dataset.parameter_filename self.directory = os.path.dirname(self.index_filename) GridIndex.__init__(self, ds, dataset_type) def _detect_output_fields(self): # This needs to set a self.field_list that contains all the available, # on-disk fields. # NOTE: Each should be a tuple, where the first element is the on-disk # fluid type or particle type. Convention suggests that the on-disk # fluid type is usually the dataset_type and the on-disk particle type # (for a single population of particles) is "io". pass def _count_grids(self): # This needs to set self.num_grids pass def _parse_index(self): # This needs to fill the following arrays, where N is self.num_grids: # self.grid_left_edge (N, 3) <= float64 # self.grid_right_edge (N, 3) <= float64 # self.grid_dimensions (N, 3) <= int # self.grid_particle_count (N, 1) <= int # self.grid_levels (N, 1) <= int # self.grids (N, 1) <= grid objects # pass def _populate_grid_objects(self): # For each grid, this must call: # grid._prepare_grid() # grid._setup_dx() # This must also set: # grid.Children <= list of child grids # grid.Parent <= parent grid # This is handled by the frontend because often the children must be # identified. pass class SkeletonDataset(Dataset): _index_class = SkeletonHierarchy _field_info_class = SkeletonFieldInfo def __init__(self, filename, dataset_type='skeleton', storage_filename=None, units_override=None): self.fluid_types += ('skeleton',) Dataset.__init__(self, filename, dataset_type, units_override=units_override) self.storage_filename = storage_filename def _set_code_unit_attributes(self): # This is where quantities are created that represent the various # on-disk units. These are the currently available quantities which # should be set, along with examples of how to set them to standard # values. # # self.length_unit = self.quan(1.0, "cm") # self.mass_unit = self.quan(1.0, "g") # self.time_unit = self.quan(1.0, "s") # self.time_unit = self.quan(1.0, "s") # # These can also be set: # self.velocity_unit = self.quan(1.0, "cm/s") # self.magnetic_unit = self.quan(1.0, "gauss") pass def _parse_parameter_file(self): # This needs to set up the following items. Note that these are all # assumed to be in code units; domain_left_edge and domain_right_edge # will be updated to be in code units at a later time. This includes # the cosmological parameters. # # self.unique_identifier # self.parameters <= full of code-specific items of use # self.domain_left_edge <= array of float64 # self.domain_right_edge <= array of float64 # self.dimensionality <= int # self.domain_dimensions <= array of int64 # self.periodicity <= three-element tuple of booleans # self.current_time <= simulation time in code units # # We also set up cosmological information. Set these to zero if # non-cosmological. # # self.cosmological_simulation <= int, 0 or 1 # self.current_redshift <= float # self.omega_lambda <= float # self.omega_matter <= float # self.hubble_constant <= float pass @classmethod def _is_valid(self, *args, **kwargs): # This accepts a filename or a set of arguments and returns True or # False depending on if the file is of the type requested. return False
37.854167
78
0.593653
from yt.data_objects.grid_patch import \ AMRGridPatch from yt.geometry.grid_geometry_handler import \ GridIndex from yt.data_objects.static_output import \ Dataset from .fields import SkeletonFieldInfo class SkeletonGrid(AMRGridPatch): _id_offset = 0 def __init__(self, id, index, level, start, dimensions): AMRGridPatch.__init__(self, id, filename=index.index_filename, index=index) self.Parent = [] self.Children = [] self.Level = level self.start_index = start.copy() self.stop_index = self.start_index + dimensions self.ActiveDimensions = dimensions.copy() def __repr__(self): return "SkeletonGrid_%04i (%s)" % (self.id, self.ActiveDimensions) class SkeletonHierarchy(GridIndex): grid = SkeletonGrid def __init__(self, ds, dataset_type='skeleton'): self.dataset_type = dataset_type self.index_filename = self.dataset.parameter_filename self.directory = os.path.dirname(self.index_filename) GridIndex.__init__(self, ds, dataset_type) def _detect_output_fields(self): pass def _count_grids(self): pass def _parse_index(self): pass def _populate_grid_objects(self): pass class SkeletonDataset(Dataset): _index_class = SkeletonHierarchy _field_info_class = SkeletonFieldInfo def __init__(self, filename, dataset_type='skeleton', storage_filename=None, units_override=None): self.fluid_types += ('skeleton',) Dataset.__init__(self, filename, dataset_type, units_override=units_override) self.storage_filename = storage_filename def _set_code_unit_attributes(self): pass def _parse_parameter_file(self): pass @classmethod def _is_valid(self, *args, **kwargs): return False
true
true
f7110fbcf2ee39a52a9cf4baf18e8773ac09b93d
766
py
Python
blog/admin.py
hdzAlexander/MyDjangoBlog
4c8b0a654d8086e4c3b1bc4b8533479f79d7b834
[ "MIT" ]
null
null
null
blog/admin.py
hdzAlexander/MyDjangoBlog
4c8b0a654d8086e4c3b1bc4b8533479f79d7b834
[ "MIT" ]
null
null
null
blog/admin.py
hdzAlexander/MyDjangoBlog
4c8b0a654d8086e4c3b1bc4b8533479f79d7b834
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import Article, Category, User from django import forms from pagedown.widgets import AdminPagedownWidget class ArticleForm(forms.ModelForm): text = forms.CharField(widget=AdminPagedownWidget()) class Meta: model = Article fields = '__all__' class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'publish_time', 'last_modify_time', 'id') class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'created_time', 'last_modify_time', 'id') class UserAdmin(admin.ModelAdmin): list_display = ('username', 'nickname', 'created_time', 'id') admin.site.register(Article, ArticleAdmin) admin.site.register(Category, CategoryAdmin) admin.site.register(User, UserAdmin)
25.533333
70
0.741514
from django.contrib import admin from .models import Article, Category, User from django import forms from pagedown.widgets import AdminPagedownWidget class ArticleForm(forms.ModelForm): text = forms.CharField(widget=AdminPagedownWidget()) class Meta: model = Article fields = '__all__' class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'publish_time', 'last_modify_time', 'id') class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'created_time', 'last_modify_time', 'id') class UserAdmin(admin.ModelAdmin): list_display = ('username', 'nickname', 'created_time', 'id') admin.site.register(Article, ArticleAdmin) admin.site.register(Category, CategoryAdmin) admin.site.register(User, UserAdmin)
true
true
f711129c9db6df7c63a7497c63fdb1ce99c0681f
463
bzl
Python
third_party/snappy/workspace.bzl
jeongukjae/nori-clone
e0f8afb842499be4d55f1fc47292fbecdbca2a86
[ "Apache-2.0" ]
38
2022-01-07T05:19:28.000Z
2022-03-27T13:44:53.000Z
third_party/snappy/workspace.bzl
jeongukjae/nori-clone
e0f8afb842499be4d55f1fc47292fbecdbca2a86
[ "Apache-2.0" ]
19
2022-01-11T14:25:03.000Z
2022-02-18T14:24:19.000Z
third_party/snappy/workspace.bzl
jeongukjae/nori-clone
e0f8afb842499be4d55f1fc47292fbecdbca2a86
[ "Apache-2.0" ]
3
2022-02-14T13:51:20.000Z
2022-03-28T06:55:38.000Z
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("//third_party:repo.bzl", "clean_dep") def configure_snappy(): http_archive( name = "com_github_google_snappy", build_file = clean_dep("//third_party/snappy:BUILD.bzl"), sha256 = "e170ce0def2c71d0403f5cda61d6e2743373f9480124bcfcd0fa9b3299d428d9", strip_prefix = "snappy-1.1.9", url = "https://github.com/google/snappy/archive/1.1.9.zip", )
38.583333
84
0.691145
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("//third_party:repo.bzl", "clean_dep") def configure_snappy(): http_archive( name = "com_github_google_snappy", build_file = clean_dep("//third_party/snappy:BUILD.bzl"), sha256 = "e170ce0def2c71d0403f5cda61d6e2743373f9480124bcfcd0fa9b3299d428d9", strip_prefix = "snappy-1.1.9", url = "https://github.com/google/snappy/archive/1.1.9.zip", )
true
true
f71113c1dbcd319ed876635e4cd8becd72b4fcca
748
py
Python
allennlp/__main__.py
12seetharaman/allennlp
212035f23c4642b3f3bc850316fe0119f2053ab1
[ "Apache-2.0" ]
1
2021-06-12T22:01:10.000Z
2021-06-12T22:01:10.000Z
allennlp/__main__.py
12seetharaman/allennlp
212035f23c4642b3f3bc850316fe0119f2053ab1
[ "Apache-2.0" ]
null
null
null
allennlp/__main__.py
12seetharaman/allennlp
212035f23c4642b3f3bc850316fe0119f2053ab1
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import logging import os import sys if os.environ.get("ALLENNLP_DEBUG"): LEVEL = logging.DEBUG else: level_name = os.environ.get("ALLENNLP_LOG_LEVEL") LEVEL = logging._nameToLevel.get(level_name, logging.INFO) sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) logging.basicConfig(format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", level=LEVEL) # filelock emits too many messages, so tell it to be quiet unless it has something # important to say. _filelock_logger = logging.getLogger("filelock") _filelock_logger.setLevel(logging.WARNING) from allennlp.commands import main # noqa def run(): main(prog="allennlp") if __name__ == "__main__": run()
25.793103
95
0.731283
import logging import os import sys if os.environ.get("ALLENNLP_DEBUG"): LEVEL = logging.DEBUG else: level_name = os.environ.get("ALLENNLP_LOG_LEVEL") LEVEL = logging._nameToLevel.get(level_name, logging.INFO) sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) logging.basicConfig(format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", level=LEVEL) _filelock_logger = logging.getLogger("filelock") _filelock_logger.setLevel(logging.WARNING) from allennlp.commands import main def run(): main(prog="allennlp") if __name__ == "__main__": run()
true
true
f71114482557985f31dbb204aaef377b0d7b4168
3,125
py
Python
vds_vault_oauth/utilities/Token.py
veeva/vds-vault-oauth-tool
91e424a673e99261d538b27a938f7f56ac154475
[ "Apache-2.0" ]
2
2019-12-19T02:10:39.000Z
2020-06-03T15:28:54.000Z
vds_vault_oauth/utilities/Token.py
veeva/vds-vault-oauth-tool
91e424a673e99261d538b27a938f7f56ac154475
[ "Apache-2.0" ]
null
null
null
vds_vault_oauth/utilities/Token.py
veeva/vds-vault-oauth-tool
91e424a673e99261d538b27a938f7f56ac154475
[ "Apache-2.0" ]
1
2022-02-17T08:09:27.000Z
2022-02-17T08:09:27.000Z
from datetime import datetime from jose import jwt from jose.utils import base64url_decode from jose.exceptions import JWTError from vds_vault_oauth.utilities import OAuthContainer # Token that stores the necessary tokens and provides the ability to decode & log them. class Token(): def __init__(self, token_value, token_type, logger): self.token_value = token_value self.token_type = token_type self.token_claims = dict() self.logger = logger def decodeTokens(self): if (self.token_value != None and self.token_type != "refresh_token"): try: claims = jwt.get_unverified_claims(self.token_value) headers = jwt.get_unverified_headers(self.token_value) self.token_claims.update(headers) self.token_claims.update(claims) except JWTError as e: import sys self.logger.log(("\t%s: %s\n" % (str(sys.exc_info()[0]), str(e)))) self.logger.log(("\t%s: %s\n\n" % ("Error", "Non-JWT token detected. Verifying against introspection endpoint."))) return False return True def verifyTokenClaims(self): self.logger.log(("\n\t" + '{s:{c}^{n}}'.format(s=" Verifying '" + self.token_type + "' Claims ",n=65,c='-') + "\n\n")) if ('sub' in self.token_claims): self.logger.log(("\t%s: %s\n" % ("The 'sub' claim exists", self.token_claims['sub']))) else: self.logger.log(("\n\tINVALID: The 'sub' claim does not exist. This is required.\n"), "ERROR") if ('aud' in self.token_claims): self.logger.log(("\t%s: %s\n" % ("The 'aud' claim exists", self.token_claims['aud']))) else: self.logger.log(("\n\tINVALID: The 'aud' claim does not exist. This is optionally required.\n"), "ERROR") if ('exp' in self.token_claims): expiry = datetime.utcfromtimestamp(int(self.token_claims['exp'])).strftime('%Y-%m-%d %H:%M:%S') self.logger.log(("\t%s: %s\n" % ("The 'exp' claim exists", str(self.token_claims['exp']) + " (" + str(expiry) + " UTC)"))) else: self.logger.log(("\n\tINVALID: The 'exp' claim does not exist.\n"), "ERROR") if self.token_type == "access_token": if ('cid' in self.token_claims): self.logger.log(("\t%s: %s\n" % ("The 'cid' claim exists", self.token_claims['cid']))) elif ('appid' in self.token_claims): self.logger.log(("\t%s: %s\n" % ("The 'appid' claim exists", self.token_claims['appid']))) else: self.logger.log(("\n\tINVALID: The 'cid' or 'appid' claim does not exist.\n"), "ERROR") self.logger.log(("\n\n")) def logTokenClaims(self): for key, value in self.token_claims.items(): self.logger.log(("\t%s: %s\n" % (key, value))) self.logger.log(("\n\t" + '{s:{c}^{n}}'.format(s='',n=65,c='-') + "\n\n")) self.logger.log(("\n"))
49.603175
135
0.5552
from datetime import datetime from jose import jwt from jose.utils import base64url_decode from jose.exceptions import JWTError from vds_vault_oauth.utilities import OAuthContainer class Token(): def __init__(self, token_value, token_type, logger): self.token_value = token_value self.token_type = token_type self.token_claims = dict() self.logger = logger def decodeTokens(self): if (self.token_value != None and self.token_type != "refresh_token"): try: claims = jwt.get_unverified_claims(self.token_value) headers = jwt.get_unverified_headers(self.token_value) self.token_claims.update(headers) self.token_claims.update(claims) except JWTError as e: import sys self.logger.log(("\t%s: %s\n" % (str(sys.exc_info()[0]), str(e)))) self.logger.log(("\t%s: %s\n\n" % ("Error", "Non-JWT token detected. Verifying against introspection endpoint."))) return False return True def verifyTokenClaims(self): self.logger.log(("\n\t" + '{s:{c}^{n}}'.format(s=" Verifying '" + self.token_type + "' Claims ",n=65,c='-') + "\n\n")) if ('sub' in self.token_claims): self.logger.log(("\t%s: %s\n" % ("The 'sub' claim exists", self.token_claims['sub']))) else: self.logger.log(("\n\tINVALID: The 'sub' claim does not exist. This is required.\n"), "ERROR") if ('aud' in self.token_claims): self.logger.log(("\t%s: %s\n" % ("The 'aud' claim exists", self.token_claims['aud']))) else: self.logger.log(("\n\tINVALID: The 'aud' claim does not exist. This is optionally required.\n"), "ERROR") if ('exp' in self.token_claims): expiry = datetime.utcfromtimestamp(int(self.token_claims['exp'])).strftime('%Y-%m-%d %H:%M:%S') self.logger.log(("\t%s: %s\n" % ("The 'exp' claim exists", str(self.token_claims['exp']) + " (" + str(expiry) + " UTC)"))) else: self.logger.log(("\n\tINVALID: The 'exp' claim does not exist.\n"), "ERROR") if self.token_type == "access_token": if ('cid' in self.token_claims): self.logger.log(("\t%s: %s\n" % ("The 'cid' claim exists", self.token_claims['cid']))) elif ('appid' in self.token_claims): self.logger.log(("\t%s: %s\n" % ("The 'appid' claim exists", self.token_claims['appid']))) else: self.logger.log(("\n\tINVALID: The 'cid' or 'appid' claim does not exist.\n"), "ERROR") self.logger.log(("\n\n")) def logTokenClaims(self): for key, value in self.token_claims.items(): self.logger.log(("\t%s: %s\n" % (key, value))) self.logger.log(("\n\t" + '{s:{c}^{n}}'.format(s='',n=65,c='-') + "\n\n")) self.logger.log(("\n"))
true
true
f7111500e4a819c6afa8f433794c1e6549e9bd38
6,317
py
Python
lwb_heartbeat/child/views.py
jayadams011/lwb_heartbeat
6d9b594f317107cd26932485dd8d063e226970fa
[ "MIT" ]
1
2021-03-18T20:55:04.000Z
2021-03-18T20:55:04.000Z
lwb_heartbeat/child/views.py
jayadams011/lwb_heartbeat
6d9b594f317107cd26932485dd8d063e226970fa
[ "MIT" ]
17
2018-05-23T15:14:17.000Z
2018-05-25T23:39:38.000Z
lwb_heartbeat/child/views.py
jayadams011/lwb_heartbeat
6d9b594f317107cd26932485dd8d063e226970fa
[ "MIT" ]
2
2018-06-12T20:50:38.000Z
2021-03-18T20:55:21.000Z
from django.views.generic import (TemplateView, ListView, DetailView, CreateView, UpdateView) from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.conf import settings from .forms import ChildEditForm, ChildAddForm from .models import Child, MedicalUpdate from images.models import Photo from django.contrib.auth.models import User from django.shortcuts import render, get_object_or_404, redirect class ChildListView(LoginRequiredMixin, ListView): """View to see a list of all children.""" template_name = "child_list.html" login_url = reverse_lazy('auth_login') context_object_name = 'children' model = Child def get(self, *args, **kwargs): """get args and kwargs""" return super().get(*args, **kwargs) def get_context_data(self, **kwargs): """return context data""" context = super().get_context_data(**kwargs) return context class ChildMedicalUpdateView(LoginRequiredMixin, DetailView): template_name = 'child_medical_veiw.html' model = MedicalUpdate login_url = reverse_lazy('auth_url') context_object_name = 'medicalupdate' def get_queryset(self): return MedicalUpdate.objects.filter(child__id=self.kwargs['pk']) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['child'] = Child.objects.filter(id=self.kwargs['pk']).first() context['medicalupdate'] = self.get_queryset() return context # # OLD VERSION:------------------------------------------------------ # don't delete until presentation # class ChildEditView(LoginRequiredMixin, UpdateView): # """Lets admin or super edit a child profile.""" # template_name = 'child_edit.html' # model = Child # form_class = ChildEditForm # login_url = reverse_lazy('auth_login') # success_url = reverse_lazy('children') # # DO # # change to use pk # slug_url_kwarg = 'username' # slug_field = 'user__username' # def get(self, *args, **kwargs): # """Get.""" # self.kwargs['username'] = self.request.user.get_username() # return super().get(*args, **kwargs) # def post(self, *args, **kwargs): # """Post.""" # self.kwargs['username'] = self.request.user.get_username() # return super().post(*args, **kwargs) # def get_form_kwargs(self): # """Get kwargs.""" # kwargs = super().get_form_kwargs() # kwargs.update({'username': self.request.user.get_username()}) # return kwargs # def form_valid(self, form): # """Validate form.""" # # form.instance.user.email = form.data['email'] # form.instance.user.first_name = form.data['first_name'] # form.instance.user.last_name = form.data['last_name'] # form.instance.user.save() # return super().form_valid(form) class ChildEditView(LoginRequiredMixin, UpdateView): """Lets admin or super edit a child profile.""" template_name = 'child_edit.html' model = Child form_class = ChildEditForm login_url = reverse_lazy('auth_login') success_url = reverse_lazy('childlist') def get(self, *args, **kwargs): """Get info""" # DO # maybe only need return super self.kwargs['username'] = self.request.user.get_username() return super().post(*args, **kwargs) def post(self, *args, **kwargs): """Post for child edit form.""" # Do # same as the get comment self.kwargs['username'] = self.request.user.get_username() return super().post(*args, **kwargs) def get_form_kwargs(self): """Get kwargs from edit form.""" kwargs = super().get_form_kwargs() kwargs.update({'username': self.request.user.get_username()}) return kwargs def form_valid(self, form): """Validate form data.""" # form.instance.user = self.request.user # form.instance.save() # import pdb; pdb.set_trace() photo = form.instance.photos.first() if photo and 'image' not in form.files: photo.delete() elif photo: photo.image = form.files['image'] photo.description = form.data['description'] photo.save() elif 'image' in form.files: # create new photo instance photo = Photo( child=form.instance, image=form.files['image'], description=form.data['description'] ) photo.save() return super().form_valid(form) class ChildDetailView(LoginRequiredMixin, DetailView): template_name = 'child_profile.html' model = Child login_url = reverse_lazy('auth_url') pk_url_kwarg = 'pk' # DON'T DELETE # NEED FOR REFERENCE ---------------------------------------- # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) # # photos = Photo.objects.filter(user__username=self.request.user.username) # # import pdb; pdb.set_trace() # # context['child_photos'] = photos # return context # def get_queryset(self): # return Child.objects.filter(published='PUBLIC') # ------------------------------------------------------------- class ChildCreateView(LoginRequiredMixin, CreateView): """Lets a staff with appropriate permissions add a child to the system.""" pass template_name = 'child_create.html' model = Child form_class = ChildAddForm success_url = reverse_lazy('childlist') login_url = reverse_lazy('auth_login') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({'username': self.request.user.username}) return kwargs def form_valid(self, form): form.instance.user = self.request.user form.instance.save() if 'image' in form.files: # create new photo instance photo = Photo( child=form.instance, image=form.files['image'], description=form.data['description'] ) photo.save() return super().form_valid(form)
32.901042
84
0.609467
from django.views.generic import (TemplateView, ListView, DetailView, CreateView, UpdateView) from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.conf import settings from .forms import ChildEditForm, ChildAddForm from .models import Child, MedicalUpdate from images.models import Photo from django.contrib.auth.models import User from django.shortcuts import render, get_object_or_404, redirect class ChildListView(LoginRequiredMixin, ListView): template_name = "child_list.html" login_url = reverse_lazy('auth_login') context_object_name = 'children' model = Child def get(self, *args, **kwargs): return super().get(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class ChildMedicalUpdateView(LoginRequiredMixin, DetailView): template_name = 'child_medical_veiw.html' model = MedicalUpdate login_url = reverse_lazy('auth_url') context_object_name = 'medicalupdate' def get_queryset(self): return MedicalUpdate.objects.filter(child__id=self.kwargs['pk']) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['child'] = Child.objects.filter(id=self.kwargs['pk']).first() context['medicalupdate'] = self.get_queryset() return context # class ChildEditView(LoginRequiredMixin, UpdateView): # """Lets admin or super edit a child profile.""" # template_name = 'child_edit.html' # model = Child # form_class = ChildEditForm # login_url = reverse_lazy('auth_login') # success_url = reverse_lazy('children') # # DO # # change to use pk # slug_url_kwarg = 'username' # slug_field = 'user__username' # def get(self, *args, **kwargs): # """Get.""" # self.kwargs['username'] = self.request.user.get_username() # return super().get(*args, **kwargs) # def post(self, *args, **kwargs): # """Post.""" # self.kwargs['username'] = self.request.user.get_username() # return super().post(*args, **kwargs) # def get_form_kwargs(self): # """Get kwargs.""" # kwargs = super().get_form_kwargs() # kwargs.update({'username': self.request.user.get_username()}) # return kwargs # def form_valid(self, form): # """Validate form.""" # # form.instance.user.email = form.data['email'] # form.instance.user.first_name = form.data['first_name'] # form.instance.user.last_name = form.data['last_name'] # form.instance.user.save() # return super().form_valid(form) class ChildEditView(LoginRequiredMixin, UpdateView): template_name = 'child_edit.html' model = Child form_class = ChildEditForm login_url = reverse_lazy('auth_login') success_url = reverse_lazy('childlist') def get(self, *args, **kwargs): # DO # maybe only need return super self.kwargs['username'] = self.request.user.get_username() return super().post(*args, **kwargs) def post(self, *args, **kwargs): # Do # same as the get comment self.kwargs['username'] = self.request.user.get_username() return super().post(*args, **kwargs) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({'username': self.request.user.get_username()}) return kwargs def form_valid(self, form): # form.instance.user = self.request.user # form.instance.save() # import pdb; pdb.set_trace() photo = form.instance.photos.first() if photo and 'image' not in form.files: photo.delete() elif photo: photo.image = form.files['image'] photo.description = form.data['description'] photo.save() elif 'image' in form.files: # create new photo instance photo = Photo( child=form.instance, image=form.files['image'], description=form.data['description'] ) photo.save() return super().form_valid(form) class ChildDetailView(LoginRequiredMixin, DetailView): template_name = 'child_profile.html' model = Child login_url = reverse_lazy('auth_url') pk_url_kwarg = 'pk' # DON'T DELETE model = Child form_class = ChildAddForm success_url = reverse_lazy('childlist') login_url = reverse_lazy('auth_login') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({'username': self.request.user.username}) return kwargs def form_valid(self, form): form.instance.user = self.request.user form.instance.save() if 'image' in form.files: photo = Photo( child=form.instance, image=form.files['image'], description=form.data['description'] ) photo.save() return super().form_valid(form)
true
true
f71115104cdacec380fdd3d6df84abcdf9c0321a
552
py
Python
MatchApp/migrations/0062_auto_20210511_2322.py
elizza19/django_local_library
f2dc053e44684b7a966d8bc0ff364f5251449f5b
[ "Apache-2.0" ]
null
null
null
MatchApp/migrations/0062_auto_20210511_2322.py
elizza19/django_local_library
f2dc053e44684b7a966d8bc0ff364f5251449f5b
[ "Apache-2.0" ]
null
null
null
MatchApp/migrations/0062_auto_20210511_2322.py
elizza19/django_local_library
f2dc053e44684b7a966d8bc0ff364f5251449f5b
[ "Apache-2.0" ]
null
null
null
# Generated by Django 3.1.7 on 2021-05-11 21:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('MatchApp', '0061_apadrinamiento'), ] operations = [ migrations.AlterField( model_name='apadrinamiento', name='tipo_ingreso', field=models.CharField(blank=True, choices=[('Combinado', 'Combinado'), ('Unico', 'Unico'), ('Directo Albergue', 'Directo Albergue')], max_length=20, null=True, verbose_name='Tipo de Ingreso'), ), ]
29.052632
205
0.632246
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('MatchApp', '0061_apadrinamiento'), ] operations = [ migrations.AlterField( model_name='apadrinamiento', name='tipo_ingreso', field=models.CharField(blank=True, choices=[('Combinado', 'Combinado'), ('Unico', 'Unico'), ('Directo Albergue', 'Directo Albergue')], max_length=20, null=True, verbose_name='Tipo de Ingreso'), ), ]
true
true
f71115497ba704cbabc6220d07f71e798fe5819d
589
py
Python
src/models/conv_block.py
plutasnyy/mgr
4ca5686ba7d62d0e2b8c172f17eb90bd822fdc21
[ "MIT" ]
3
2021-10-04T17:13:14.000Z
2021-10-17T21:08:26.000Z
src/models/conv_block.py
plutasnyy/mgr
4ca5686ba7d62d0e2b8c172f17eb90bd822fdc21
[ "MIT" ]
null
null
null
src/models/conv_block.py
plutasnyy/mgr
4ca5686ba7d62d0e2b8c172f17eb90bd822fdc21
[ "MIT" ]
null
null
null
from torch import nn class ConvolutionalBlock(nn.Module): def __init__(self, in_channels=128, out_channels=256, kernel_size=3, padding=1, stride=1, padding_mode='zeros'): super().__init__() self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride, padding_mode=padding_mode) self.bn1 = nn.BatchNorm1d(out_channels) self.relu1 = nn.ReLU() def forward(self, x): out = self.conv1(x) out = self.bn1(out) out = self.relu1(out) return out
32.722222
116
0.633277
from torch import nn class ConvolutionalBlock(nn.Module): def __init__(self, in_channels=128, out_channels=256, kernel_size=3, padding=1, stride=1, padding_mode='zeros'): super().__init__() self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride, padding_mode=padding_mode) self.bn1 = nn.BatchNorm1d(out_channels) self.relu1 = nn.ReLU() def forward(self, x): out = self.conv1(x) out = self.bn1(out) out = self.relu1(out) return out
true
true
f71115f7872ed81af5335fcea362c1a33abafa50
4,675
py
Python
LinReg/utilsLinReg.py
peterchanw/utils
26133c52ba5b0407d38371100b7b56fe2cf68149
[ "MIT" ]
null
null
null
LinReg/utilsLinReg.py
peterchanw/utils
26133c52ba5b0407d38371100b7b56fe2cf68149
[ "MIT" ]
null
null
null
LinReg/utilsLinReg.py
peterchanw/utils
26133c52ba5b0407d38371100b7b56fe2cf68149
[ "MIT" ]
null
null
null
import sklearn.metrics as metrics import pandas as pd import numpy as np def repair_chrdata(df, tCol): ### Parameters: # df: input dataframe # tCol: targeted column label with NaN ### Output # df: repaired dataframe # word: string of related dataframe column with some records have NaN in targeted column # count: number of records fixed in the targeted column with NaN # work out number of NaN records need to fix dFrm = df[df[tCol].isnull()] count = len(dFrm) # work out the fill up string (most appearance) at targeted column for NULL tword = df[tCol].unique().tolist() # print(tword) wordLT = df[tCol].value_counts(dropna=False) word = '' wordCnt = 0 for index, value in wordLT.items(): print(f'[COUNT] Index: {index}, Value: {value}') if wordCnt < value: word = index wordCnt = value # print(word) # print(wordLT) # update the targeted NaN with the most frequent string mask = df[tCol].isnull() df.loc[mask, tCol] = word print(f'[REPAIR] "{tCol}" with string: {word}, Count: {count}') return df, word, count # Repair a single number data column contained NaN with median value def repair_numdata(df, tCol): ### Parameters: # df: input dataframe # tCol: targeted column label with NaN ### Output # df: repaired dataframe # medianVal: median value of related dataframe column with some records have NaN in targeted column # count: number of records fixed in the targeted column with NaN # work out number of NaN records need to fix dFrm = df[df[tCol].isnull()] count = len(dFrm) # work out the median value of the records from targeted column medianVal = df[tCol].median() # update the targeted NaN with the median value mask = df[tCol].isnull() df.loc[mask, tCol] = medianVal print(f'[REPAIR] "{tCol}" Median: {medianVal}, Count: {count}') return df, medianVal, count ### Work out the educated guess targets to repair dataframe with NaN in 'repair_rdata' function def repair_target(df, tCol, rCol): ### Parameters: # df: input dataframe # tCol: targeted column label with NaN # rCol: related column label without NaN for educated guess ### Output # target: column value of related column that have NaN in targeted column repair = df[df[tCol].isnull()] # print(repair[[rCol, tCol]]) target = sorted(repair[rCol].unique().tolist()) print(f'[TARGET] {tCol} NaN target: {target}') return target ### Educated guess to repair dataframe column contained NaN with mean value of related ### dataframe column def repair_rcdata(df, tCol, rCol, target): ### Parameters: # df: input dataframe # tCol: targeted column label with NaN # rCol: related column label without NaN for educated guess # target: column value of related column that have NaN in targeted column ### Output # df: repaired dataframe # meanVal: mean value of related dataframe column with some records have NaN in targeted column # count: number of records fixed in the targeted column with NaN ### Main coding # work out number of NaN records need to fix dFrm = df[df[tCol].isnull()] dFrm = dFrm[dFrm[rCol] == target] count = len(dFrm) # work out the mean value of the records from related column repair = df.loc[df[rCol] == target] meanVal = round(repair[tCol].mean(), 3) if np.isnan(meanVal): meanVal = np.float64(0) # update the targeted NaN with the calculated mean value of related records df[tCol] = df.apply( lambda row: meanVal if np.isnan(row[tCol]) & (row[rCol] == target) else row[tCol], axis=1 ) print(f'[REPAIR] {tCol}({target}) Mean: {meanVal}, Count: {count}') return df, meanVal, count def regression_results(y_true, y_pred): # Regression metrics explained_variance=metrics.explained_variance_score(y_true, y_pred) mean_absolute_error=metrics.mean_absolute_error(y_true, y_pred) mse=metrics.mean_squared_error(y_true, y_pred) # mean_squared_log_error=metrics.mean_squared_log_error(y_true, y_pred) # median_absolute_error=metrics.median_absolute_error(y_true, y_pred) r2=metrics.r2_score(y_true, y_pred) print('explained_variance: ', round(explained_variance,4)) # print('mean_squared_log_error: ', round(mean_squared_log_error,4)) print('r-squared (r2): ', round(r2,4)) print('mean_absolute_error (MAE): ', round(mean_absolute_error,4)) print('mean_squared_error (MSE): ', round(mse,4)) print('root_mean_squared_error (RMSE): ', round(np.sqrt(mse),4))
39.618644
103
0.678503
import sklearn.metrics as metrics import pandas as pd import numpy as np def repair_chrdata(df, tCol): m = df[df[tCol].isnull()] count = len(dFrm) tword = df[tCol].unique().tolist() wordLT = df[tCol].value_counts(dropna=False) word = '' wordCnt = 0 for index, value in wordLT.items(): print(f'[COUNT] Index: {index}, Value: {value}') if wordCnt < value: word = index wordCnt = value mask = df[tCol].isnull() df.loc[mask, tCol] = word print(f'[REPAIR] "{tCol}" with string: {word}, Count: {count}') return df, word, count def repair_numdata(df, tCol): m = df[df[tCol].isnull()] count = len(dFrm) medianVal = df[tCol].median() mask = df[tCol].isnull() df.loc[mask, tCol] = medianVal print(f'[REPAIR] "{tCol}" Median: {medianVal}, Count: {count}') return df, medianVal, count 3) if np.isnan(meanVal): meanVal = np.float64(0) df[tCol] = df.apply( lambda row: meanVal if np.isnan(row[tCol]) & (row[rCol] == target) else row[tCol], axis=1 ) print(f'[REPAIR] {tCol}({target}) Mean: {meanVal}, Count: {count}') return df, meanVal, count def regression_results(y_true, y_pred): explained_variance=metrics.explained_variance_score(y_true, y_pred) mean_absolute_error=metrics.mean_absolute_error(y_true, y_pred) mse=metrics.mean_squared_error(y_true, y_pred) r2=metrics.r2_score(y_true, y_pred) print('explained_variance: ', round(explained_variance,4)) print('r-squared (r2): ', round(r2,4)) print('mean_absolute_error (MAE): ', round(mean_absolute_error,4)) print('mean_squared_error (MSE): ', round(mse,4)) print('root_mean_squared_error (RMSE): ', round(np.sqrt(mse),4))
true
true
f7111649d25110179d27bb7eae88a96fbb847598
6,173
py
Python
autotest/t024_test.py
hansonmcoombs/flopy
49398983c36d381992621d5bf698ea7f78fc0014
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
autotest/t024_test.py
hansonmcoombs/flopy
49398983c36d381992621d5bf698ea7f78fc0014
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
autotest/t024_test.py
hansonmcoombs/flopy
49398983c36d381992621d5bf698ea7f78fc0014
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
import os import numpy as np import pytest from ci_framework import FlopyTestSetup, base_test_dir import flopy base_dir = base_test_dir(__file__, rel_path="temp", verbose=True) ex_pth = os.path.join("..", "examples", "data", "mf2005_test") testmodels = [ os.path.join(ex_pth, f) for f in os.listdir(ex_pth) if f.endswith(".nam") ] @pytest.mark.parametrize( "namfile", testmodels, ) def test_checker_on_load(namfile): # load all of the models in the mf2005_test folder # model level checks are performed by default on load() checker_on_load(namfile) def checker_on_load(mfnam): f = os.path.basename(mfnam) d = os.path.dirname(mfnam) m = flopy.modflow.Modflow.load(f, model_ws=d) assert isinstance( m, flopy.modflow.Modflow ), "Not a flopy.modflow.Modflow instance" def test_bcs_check(): model_ws = f"{base_dir}_test_bcs_check" test_setup = FlopyTestSetup(verbose=True, test_dirs=model_ws) mf = flopy.modflow.Modflow(version="mf2005", model_ws=model_ws) # test check for isolated cells dis = flopy.modflow.ModflowDis( mf, nlay=2, nrow=3, ncol=3, top=100, botm=95 ) bas = flopy.modflow.ModflowBas(mf, ibound=np.ones((2, 3, 3), dtype=int)) chk = bas.check() dis = flopy.modflow.ModflowDis( mf, nlay=3, nrow=5, ncol=5, top=100, botm=95 ) ibound = np.zeros((3, 5, 5), dtype=int) ibound[1, 1, 1] = 1 # fully isolated cell ibound[0:2, 4, 4] = 1 # cell connected vertically to one other cell bas = flopy.modflow.ModflowBas(mf, ibound=ibound) mf._mg_resync = True chk = bas.check() assert chk.summary_array["desc"][0] == "isolated cells in ibound array" assert ( chk.summary_array.i[0] == 1 and chk.summary_array.i[0] == 1 and chk.summary_array.j[0] == 1 ) assert len(chk.summary_array) == 1 ghb = flopy.modflow.ModflowGhb( mf, stress_period_data={0: [0, 0, 0, 100, 1]} ) riv = flopy.modflow.ModflowRiv( mf, stress_period_data={ 0: [[0, 0, 0, 101, 10, 100], [0, 0, 1, 80, 10, 90]] }, ) chk = ghb.check() assert chk.summary_array["desc"][0] == "BC in inactive cell" chk = riv.check() assert chk.summary_array["desc"][4] == "RIV stage below rbots" assert np.array_equal(chk.summary_array["j"], np.array([0, 1, 1, 1, 1])) def test_properties_check(): # test that storage values ignored for steady state model_ws = f"{base_dir}_test_properties_check" test_setup = FlopyTestSetup(verbose=True, test_dirs=model_ws) mf = flopy.modflow.Modflow( version="mf2005", model_ws=model_ws, ) dis = flopy.modflow.ModflowDis( mf, nrow=2, ncol=2, top=np.array([[100, np.nan], [100, 100]]), nper=3, steady=True, ) chk = dis.check() assert len(chk.summary_array) == 1 kij = ( chk.summary_array["k"][0], chk.summary_array["i"][0], chk.summary_array["j"][0], ) assert kij == (0, 0, 1) lpf = flopy.modflow.ModflowLpf(mf, sy=np.ones((2, 2)), ss=np.ones((2, 2))) chk = lpf.check() assert len(chk.summary_array) == 0 # test k values check lpf = flopy.modflow.ModflowLpf( mf, hk=np.array([[1, 1e10], [1, -1]]), hani=np.array([[1, 1], [1, -1]]), vka=np.array([[1e10, 0], [1, 1e-20]]), ) chk = lpf.check() ind1 = np.array( [ True if list(inds) == [0, 1, 1] else False for inds in chk.view_summary_array_fields(["k", "i", "j"]) ] ) ind1_errors = chk.summary_array[ind1]["desc"] ind2 = np.array( [ True if list(inds) == [0, 0, 1] else False for inds in chk.view_summary_array_fields(["k", "i", "j"]) ] ) ind2_errors = chk.summary_array[ind2]["desc"] ind3 = np.array( [ True if list(inds) == [0, 0, 0] else False for inds in chk.view_summary_array_fields(["k", "i", "j"]) ] ) ind3_errors = chk.summary_array[ind3]["desc"] assert ( "zero or negative horizontal hydraulic conductivity values" in ind1_errors ) assert ( "horizontal hydraulic conductivity values below checker threshold of 1e-11" in ind1_errors ) assert "negative horizontal anisotropy values" in ind1_errors assert ( "vertical hydraulic conductivity values below checker threshold of 1e-11" in ind1_errors ) assert ( "horizontal hydraulic conductivity values above checker threshold of 100000.0" in ind2_errors ) assert ( "zero or negative vertical hydraulic conductivity values" in ind2_errors ) assert ( "vertical hydraulic conductivity values above checker threshold of 100000.0" in ind3_errors ) def test_oc_check(): m = flopy.modflow.Modflow() oc = flopy.modflow.mfoc.ModflowOc(m) chk = oc.check() assert len(chk.summary_array) == 1, len(chk.summary_array) assert "DIS package not available" in chk.summary_array[0]["desc"] flopy.modflow.ModflowDis(m) oc.stress_period_data = {(0, 0): ["save head", "save budget"]} chk = oc.check() # check passsed assert len(chk.summary_array) == 0, len(chk.summary_array) oc.stress_period_data = {(0, 0): ["save"]} chk = oc.check() assert len(chk.summary_array) == 1, len(chk.summary_array) assert "too few words" in chk.summary_array[0]["desc"] oc.stress_period_data = {(0, 0): ["save it"]} chk = oc.check() assert len(chk.summary_array) == 1, len(chk.summary_array) assert "action 'save it' ignored" in chk.summary_array[0]["desc"] oc.stress_period_data = {(1, 1): ["save head", "save budget"]} chk = oc.check() assert len(chk.summary_array) == 1, len(chk.summary_array) assert "OC stress_period_data ignored" in chk.summary_array[0]["desc"] if __name__ == "__main__": print(f"numpy version: {np.__version__}") for mfnam in testmodels: checker_on_load(mfnam) test_bcs_check() test_properties_check() test_oc_check()
30.408867
86
0.61526
import os import numpy as np import pytest from ci_framework import FlopyTestSetup, base_test_dir import flopy base_dir = base_test_dir(__file__, rel_path="temp", verbose=True) ex_pth = os.path.join("..", "examples", "data", "mf2005_test") testmodels = [ os.path.join(ex_pth, f) for f in os.listdir(ex_pth) if f.endswith(".nam") ] @pytest.mark.parametrize( "namfile", testmodels, ) def test_checker_on_load(namfile): checker_on_load(namfile) def checker_on_load(mfnam): f = os.path.basename(mfnam) d = os.path.dirname(mfnam) m = flopy.modflow.Modflow.load(f, model_ws=d) assert isinstance( m, flopy.modflow.Modflow ), "Not a flopy.modflow.Modflow instance" def test_bcs_check(): model_ws = f"{base_dir}_test_bcs_check" test_setup = FlopyTestSetup(verbose=True, test_dirs=model_ws) mf = flopy.modflow.Modflow(version="mf2005", model_ws=model_ws) dis = flopy.modflow.ModflowDis( mf, nlay=2, nrow=3, ncol=3, top=100, botm=95 ) bas = flopy.modflow.ModflowBas(mf, ibound=np.ones((2, 3, 3), dtype=int)) chk = bas.check() dis = flopy.modflow.ModflowDis( mf, nlay=3, nrow=5, ncol=5, top=100, botm=95 ) ibound = np.zeros((3, 5, 5), dtype=int) ibound[1, 1, 1] = 1 ibound[0:2, 4, 4] = 1 bas = flopy.modflow.ModflowBas(mf, ibound=ibound) mf._mg_resync = True chk = bas.check() assert chk.summary_array["desc"][0] == "isolated cells in ibound array" assert ( chk.summary_array.i[0] == 1 and chk.summary_array.i[0] == 1 and chk.summary_array.j[0] == 1 ) assert len(chk.summary_array) == 1 ghb = flopy.modflow.ModflowGhb( mf, stress_period_data={0: [0, 0, 0, 100, 1]} ) riv = flopy.modflow.ModflowRiv( mf, stress_period_data={ 0: [[0, 0, 0, 101, 10, 100], [0, 0, 1, 80, 10, 90]] }, ) chk = ghb.check() assert chk.summary_array["desc"][0] == "BC in inactive cell" chk = riv.check() assert chk.summary_array["desc"][4] == "RIV stage below rbots" assert np.array_equal(chk.summary_array["j"], np.array([0, 1, 1, 1, 1])) def test_properties_check(): model_ws = f"{base_dir}_test_properties_check" test_setup = FlopyTestSetup(verbose=True, test_dirs=model_ws) mf = flopy.modflow.Modflow( version="mf2005", model_ws=model_ws, ) dis = flopy.modflow.ModflowDis( mf, nrow=2, ncol=2, top=np.array([[100, np.nan], [100, 100]]), nper=3, steady=True, ) chk = dis.check() assert len(chk.summary_array) == 1 kij = ( chk.summary_array["k"][0], chk.summary_array["i"][0], chk.summary_array["j"][0], ) assert kij == (0, 0, 1) lpf = flopy.modflow.ModflowLpf(mf, sy=np.ones((2, 2)), ss=np.ones((2, 2))) chk = lpf.check() assert len(chk.summary_array) == 0 lpf = flopy.modflow.ModflowLpf( mf, hk=np.array([[1, 1e10], [1, -1]]), hani=np.array([[1, 1], [1, -1]]), vka=np.array([[1e10, 0], [1, 1e-20]]), ) chk = lpf.check() ind1 = np.array( [ True if list(inds) == [0, 1, 1] else False for inds in chk.view_summary_array_fields(["k", "i", "j"]) ] ) ind1_errors = chk.summary_array[ind1]["desc"] ind2 = np.array( [ True if list(inds) == [0, 0, 1] else False for inds in chk.view_summary_array_fields(["k", "i", "j"]) ] ) ind2_errors = chk.summary_array[ind2]["desc"] ind3 = np.array( [ True if list(inds) == [0, 0, 0] else False for inds in chk.view_summary_array_fields(["k", "i", "j"]) ] ) ind3_errors = chk.summary_array[ind3]["desc"] assert ( "zero or negative horizontal hydraulic conductivity values" in ind1_errors ) assert ( "horizontal hydraulic conductivity values below checker threshold of 1e-11" in ind1_errors ) assert "negative horizontal anisotropy values" in ind1_errors assert ( "vertical hydraulic conductivity values below checker threshold of 1e-11" in ind1_errors ) assert ( "horizontal hydraulic conductivity values above checker threshold of 100000.0" in ind2_errors ) assert ( "zero or negative vertical hydraulic conductivity values" in ind2_errors ) assert ( "vertical hydraulic conductivity values above checker threshold of 100000.0" in ind3_errors ) def test_oc_check(): m = flopy.modflow.Modflow() oc = flopy.modflow.mfoc.ModflowOc(m) chk = oc.check() assert len(chk.summary_array) == 1, len(chk.summary_array) assert "DIS package not available" in chk.summary_array[0]["desc"] flopy.modflow.ModflowDis(m) oc.stress_period_data = {(0, 0): ["save head", "save budget"]} chk = oc.check() assert len(chk.summary_array) == 0, len(chk.summary_array) oc.stress_period_data = {(0, 0): ["save"]} chk = oc.check() assert len(chk.summary_array) == 1, len(chk.summary_array) assert "too few words" in chk.summary_array[0]["desc"] oc.stress_period_data = {(0, 0): ["save it"]} chk = oc.check() assert len(chk.summary_array) == 1, len(chk.summary_array) assert "action 'save it' ignored" in chk.summary_array[0]["desc"] oc.stress_period_data = {(1, 1): ["save head", "save budget"]} chk = oc.check() assert len(chk.summary_array) == 1, len(chk.summary_array) assert "OC stress_period_data ignored" in chk.summary_array[0]["desc"] if __name__ == "__main__": print(f"numpy version: {np.__version__}") for mfnam in testmodels: checker_on_load(mfnam) test_bcs_check() test_properties_check() test_oc_check()
true
true
f71116abd987c23bd57eb804a843ee09589e01bb
1,039
py
Python
mkt/receipts/forms.py
muffinresearch/zamboni
045a6f07c775b99672af6d9857d295ed02fe5dd9
[ "BSD-3-Clause" ]
null
null
null
mkt/receipts/forms.py
muffinresearch/zamboni
045a6f07c775b99672af6d9857d295ed02fe5dd9
[ "BSD-3-Clause" ]
null
null
null
mkt/receipts/forms.py
muffinresearch/zamboni
045a6f07c775b99672af6d9857d295ed02fe5dd9
[ "BSD-3-Clause" ]
null
null
null
from urlparse import urlparse from django import forms from tower import ugettext_lazy as _lazy import amo from mkt.api.forms import SluggableModelChoiceField from mkt.webapps.models import Addon class ReceiptForm(forms.Form): app = SluggableModelChoiceField( queryset=Addon.objects.filter(type=amo.ADDON_WEBAPP), sluggable_to_field_name='app_slug') class TestInstall(forms.Form): TYPE_CHOICES = (('none', _lazy('No receipt')), ('ok', _lazy(u'Test receipt')), ('expired', _lazy(u'Expired test receipt')), ('invalid', _lazy(u'Invalid test receipt')), ('refunded', _lazy(u'Refunded test receipt'))) receipt_type = forms.ChoiceField(choices=TYPE_CHOICES) manifest_url = forms.URLField() def clean(self): data = self.cleaned_data url = data.get('manifest_url') if url: parsed = urlparse(url) data['root'] = '%s://%s' % (parsed.scheme, parsed.netloc) return data
29.685714
69
0.633301
from urlparse import urlparse from django import forms from tower import ugettext_lazy as _lazy import amo from mkt.api.forms import SluggableModelChoiceField from mkt.webapps.models import Addon class ReceiptForm(forms.Form): app = SluggableModelChoiceField( queryset=Addon.objects.filter(type=amo.ADDON_WEBAPP), sluggable_to_field_name='app_slug') class TestInstall(forms.Form): TYPE_CHOICES = (('none', _lazy('No receipt')), ('ok', _lazy(u'Test receipt')), ('expired', _lazy(u'Expired test receipt')), ('invalid', _lazy(u'Invalid test receipt')), ('refunded', _lazy(u'Refunded test receipt'))) receipt_type = forms.ChoiceField(choices=TYPE_CHOICES) manifest_url = forms.URLField() def clean(self): data = self.cleaned_data url = data.get('manifest_url') if url: parsed = urlparse(url) data['root'] = '%s://%s' % (parsed.scheme, parsed.netloc) return data
true
true
f71116b2ae769985945c817a41063eed0536271e
104
py
Python
workflow/__init__.py
upsila/Upflow
ab6238d48911685da06ff91bce9041e37fb18b3f
[ "MIT" ]
null
null
null
workflow/__init__.py
upsila/Upflow
ab6238d48911685da06ff91bce9041e37fb18b3f
[ "MIT" ]
null
null
null
workflow/__init__.py
upsila/Upflow
ab6238d48911685da06ff91bce9041e37fb18b3f
[ "MIT" ]
null
null
null
from entities.workflow import Workflow class Main(Workflow): def _run(self, job): return {}
20.8
38
0.682692
from entities.workflow import Workflow class Main(Workflow): def _run(self, job): return {}
true
true
f7111a0e4b0ff2edf2962809ef97e273e18bb374
625
py
Python
test/example_using_relations.py
renzon/ndb_relations
90ac165aeb2a01ec89e59c1db6da9d934ca4d6ee
[ "MIT" ]
4
2016-05-27T20:01:36.000Z
2016-07-03T01:39:17.000Z
test/example_using_relations.py
renzon/ndb_relations
90ac165aeb2a01ec89e59c1db6da9d934ca4d6ee
[ "MIT" ]
7
2016-05-11T01:47:29.000Z
2016-06-11T03:32:25.000Z
test/example_using_relations.py
renzon/ndb_relations
90ac165aeb2a01ec89e59c1db6da9d934ca4d6ee
[ "MIT" ]
1
2016-09-08T19:48:06.000Z
2016-09-08T19:48:06.000Z
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from google.appengine.ext import ndb from ndb_relations.relations import OneToMany class User2(ndb.Model): name = ndb.StringProperty() class Order2(ndb.Model): pass class OrderItem2(ndb.Model): name = ndb.StringProperty() price = ndb.FloatProperty() class OrderOwner(OneToMany): origin = ndb.KeyProperty(User2) destin = ndb.KeyProperty(Order2) class Item(ndb.Model): name = ndb.StringProperty() class OrderItemRelation(OneToMany): origin = ndb.KeyProperty(Order2) destin = ndb.KeyProperty(Item)
18.939394
56
0.7264
from __future__ import absolute_import, unicode_literals from google.appengine.ext import ndb from ndb_relations.relations import OneToMany class User2(ndb.Model): name = ndb.StringProperty() class Order2(ndb.Model): pass class OrderItem2(ndb.Model): name = ndb.StringProperty() price = ndb.FloatProperty() class OrderOwner(OneToMany): origin = ndb.KeyProperty(User2) destin = ndb.KeyProperty(Order2) class Item(ndb.Model): name = ndb.StringProperty() class OrderItemRelation(OneToMany): origin = ndb.KeyProperty(Order2) destin = ndb.KeyProperty(Item)
true
true
f7111b18c712225e31d8dae10ffb3f63df40655a
3,524
py
Python
deepvariant/python/variant_calling_wrap_test.py
tedyun/deepvariant
aba55537eec832e6cea678349422124ef50680f4
[ "BSD-3-Clause" ]
1
2018-12-07T19:48:57.000Z
2018-12-07T19:48:57.000Z
deepvariant/python/variant_calling_wrap_test.py
hcxiong/deepvariant
aba55537eec832e6cea678349422124ef50680f4
[ "BSD-3-Clause" ]
null
null
null
deepvariant/python/variant_calling_wrap_test.py
hcxiong/deepvariant
aba55537eec832e6cea678349422124ef50680f4
[ "BSD-3-Clause" ]
null
null
null
# Copyright 2017 Google Inc. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Tests for VariantCalling CLIF python wrappers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest from third_party.nucleus.io import fasta from third_party.nucleus.io import sam from third_party.nucleus.util import ranges from deepvariant import testdata from deepvariant.protos import deepvariant_pb2 from deepvariant.python import allelecounter as _allelecounter from deepvariant.python import variant_calling def setUpModule(): testdata.init() class WrapVariantCallingTest(absltest.TestCase): def test_call_from_allele_counter(self): ref = fasta.IndexedFastaReader(testdata.CHR20_FASTA) sam_reader = sam.SamReader(testdata.CHR20_BAM) size = 1000 region = ranges.make_range('chr20', 10000000, 10000000 + size) allele_counter = _allelecounter.AlleleCounter( ref.c_reader, region, deepvariant_pb2.AlleleCounterOptions(partition_size=size)) caller = variant_calling.VariantCaller( deepvariant_pb2.VariantCallerOptions( min_count_snps=2, min_count_indels=2, min_fraction_snps=0.12, min_fraction_indels=0.12, sample_name='sample_name', p_error=0.001, max_gq=50, gq_resolution=1, ploidy=2)) # Grab all of the reads in our region and add them to the allele_counter. reads = list(sam_reader.query(region)) self.assertNotEmpty(reads) for read in reads: allele_counter.add(read) # Get the candidates records for this whole region. candidates = caller.calls_from_allele_counter(allele_counter) # We should have at least some candidates and some gvcf records. self.assertNotEmpty(candidates) # Each candidate should be a DeepVariantCall. for candidate in candidates: self.assertIsInstance(candidate, deepvariant_pb2.DeepVariantCall) if __name__ == '__main__': absltest.main()
37.489362
78
0.755675
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest from third_party.nucleus.io import fasta from third_party.nucleus.io import sam from third_party.nucleus.util import ranges from deepvariant import testdata from deepvariant.protos import deepvariant_pb2 from deepvariant.python import allelecounter as _allelecounter from deepvariant.python import variant_calling def setUpModule(): testdata.init() class WrapVariantCallingTest(absltest.TestCase): def test_call_from_allele_counter(self): ref = fasta.IndexedFastaReader(testdata.CHR20_FASTA) sam_reader = sam.SamReader(testdata.CHR20_BAM) size = 1000 region = ranges.make_range('chr20', 10000000, 10000000 + size) allele_counter = _allelecounter.AlleleCounter( ref.c_reader, region, deepvariant_pb2.AlleleCounterOptions(partition_size=size)) caller = variant_calling.VariantCaller( deepvariant_pb2.VariantCallerOptions( min_count_snps=2, min_count_indels=2, min_fraction_snps=0.12, min_fraction_indels=0.12, sample_name='sample_name', p_error=0.001, max_gq=50, gq_resolution=1, ploidy=2)) reads = list(sam_reader.query(region)) self.assertNotEmpty(reads) for read in reads: allele_counter.add(read) candidates = caller.calls_from_allele_counter(allele_counter) self.assertNotEmpty(candidates) for candidate in candidates: self.assertIsInstance(candidate, deepvariant_pb2.DeepVariantCall) if __name__ == '__main__': absltest.main()
true
true
f7111b40a996bfc4e37a080db8cb29fe6e7081e2
4,902
py
Python
bot.py
Pdiskbot/doodurl
31cf2bef4d6e5093254e374b16029976a6c4d1ff
[ "MIT" ]
null
null
null
bot.py
Pdiskbot/doodurl
31cf2bef4d6e5093254e374b16029976a6c4d1ff
[ "MIT" ]
null
null
null
bot.py
Pdiskbot/doodurl
31cf2bef4d6e5093254e374b16029976a6c4d1ff
[ "MIT" ]
null
null
null
from os import environ import os import time from urllib.parse import urlparse import aiohttp from pyshorteners import Shortener from bs4 import BeautifulSoup import requests import re from pyrogram import Client, filters API_ID = environ.get('API_ID') API_HASH = environ.get('API_HASH') BOT_TOKEN = environ.get('BOT_TOKEN') API_KEY = environ.get('API_KEY') CHANNEL = environ.get('CHANNEL') HOWTO = environ.get('HOWTO') bot = Client('Droplink bot', api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) @bot.on_message(filters.command('start') & filters.private) async def start(bot, message): await message.reply( f"**Hi {message.chat.first_name}!**\n\n" "I'm doodurl bot. Just send me link and get short link") @bot.on_message(filters.command('help') & filters.private) async def start(bot, message): await message.reply( f"**Hello, {message.chat.first_name}!**\n\n" "**If you send post which had doodstream Links, texts & images... Than I'll convert & replace all pdisk links with your doodurk links \nMessage me @mrpunisher52 For more help-**") @bot.on_message(filters.command('support') & filters.private) async def start(bot, message): await message.reply( f"**Hey, {message.chat.first_name}!**\n\n" "**please contact me on @mrpunisher52 or for more join @hornyworld22**") @bot.on_message(filters.text & filters.private) async def pdisk_uploader(bot, message): new_string = str(message.text) conv = await message.reply("Converting...") dele = conv["message_id"] try: pdisk_link = await multi_pdisk_up(new_string) await bot.delete_messages(chat_id=message.chat.id, message_ids=dele) await message.reply(f'{pdisk_link}' , quote=True) except Exception as e: await message.reply(f'Error: {e}', quote=True) @bot.on_message(filters.photo & filters.private) async def pdisk_uploader(bot, message): new_string = str(message.caption) conv = await message.reply("Converting...") dele = conv["message_id"] try: pdisk_link = await multi_pdisk_up(new_string) if(len(pdisk_link) > 1020): await bot.delete_messages(chat_id=message.chat.id, message_ids=dele) await message.reply(f'{pdisk_link}' , quote=True) else: await bot.delete_messages(chat_id=message.chat.id, message_ids=dele) await bot.send_photo(message.chat.id, message.photo.file_id, caption=f'{pdisk_link}') except Exception as e: await message.reply(f'Error: {e}', quote=True) async def pdisk_up(link): if ('pdisk' in link or 'kuklink' in link or 'kofilink' in link or 'cofilink' in link or 'bit' in link or 'vdshort' in link or 'vidrivers' in link or 'dplinks' in link or 'wslinker' in link or 'mdisk' in link or 'dood' in link): url = 'https://doodurl.in/api' params = {'api': API_KEY, 'url': link} async with aiohttp.ClientSession() as session: async with session.get(url, params=params, raise_for_status=True) as response: data = await response.json() v_url = data["shortenedUrl"] else: v_url = link return (v_url) async def multi_pdisk_up(ml_string): list_string = ml_string.splitlines() ml_string = ' \n'.join(list_string) new_ml_string = list(map(str, ml_string.split(" "))) new_ml_string = [sub.replace('https://t.me/Desi_Bhabhi_Aunty_hot_Video/41', 'https://t.me/Desi_Bhabhi_Aunty_hot_Video/61') for sub in new_ml_string] #new_ml_string = await remove_footer(new_ml_string) new_join_str = "".join(new_ml_string) urls = re.findall(r'(https?://[^\s]+)', new_join_str) nml_len = len(new_ml_string) u_len = len(urls) url_index = [] count = 0 for i in range(nml_len): for j in range(u_len): if (urls[j] in new_ml_string[i]): url_index.append(count) count += 1 new_urls = await new_pdisk_url(urls) url_index = list(dict.fromkeys(url_index)) i = 0 for j in url_index: new_ml_string[j] = new_ml_string[j].replace(urls[i], new_urls[i]) i += 1 new_string = " ".join(new_ml_string) #return await addFooter(new_string) return (new_string) async def new_pdisk_url(urls): new_urls = [] for i in urls: time.sleep(0.2) new_urls.append(await pdisk_up(i)) return new_urls '''async def remove_footer(new_List): for i in new_List: if('https://t.me/Desi_Bhabhi_Aunty_hot_Video/41' in i): i = i.replace("41","61") #new_List.remove(i) return new_List''' '''async def addFooter(str): footer = """ ━━━━━━━━━━━━━━━ ⚙️ How to Download / Watch Online :""" + HOWTO + """ ━━━━━━━━━━━━━━━ ⭐️JOIN CHANNEL ➡️ t.me/""" + CHANNEL return str + footer''' bot.run()
35.014286
231
0.648307
from os import environ import os import time from urllib.parse import urlparse import aiohttp from pyshorteners import Shortener from bs4 import BeautifulSoup import requests import re from pyrogram import Client, filters API_ID = environ.get('API_ID') API_HASH = environ.get('API_HASH') BOT_TOKEN = environ.get('BOT_TOKEN') API_KEY = environ.get('API_KEY') CHANNEL = environ.get('CHANNEL') HOWTO = environ.get('HOWTO') bot = Client('Droplink bot', api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) @bot.on_message(filters.command('start') & filters.private) async def start(bot, message): await message.reply( f"**Hi {message.chat.first_name}!**\n\n" "I'm doodurl bot. Just send me link and get short link") @bot.on_message(filters.command('help') & filters.private) async def start(bot, message): await message.reply( f"**Hello, {message.chat.first_name}!**\n\n" "**If you send post which had doodstream Links, texts & images... Than I'll convert & replace all pdisk links with your doodurk links \nMessage me @mrpunisher52 For more help-**") @bot.on_message(filters.command('support') & filters.private) async def start(bot, message): await message.reply( f"**Hey, {message.chat.first_name}!**\n\n" "**please contact me on @mrpunisher52 or for more join @hornyworld22**") @bot.on_message(filters.text & filters.private) async def pdisk_uploader(bot, message): new_string = str(message.text) conv = await message.reply("Converting...") dele = conv["message_id"] try: pdisk_link = await multi_pdisk_up(new_string) await bot.delete_messages(chat_id=message.chat.id, message_ids=dele) await message.reply(f'{pdisk_link}' , quote=True) except Exception as e: await message.reply(f'Error: {e}', quote=True) @bot.on_message(filters.photo & filters.private) async def pdisk_uploader(bot, message): new_string = str(message.caption) conv = await message.reply("Converting...") dele = conv["message_id"] try: pdisk_link = await multi_pdisk_up(new_string) if(len(pdisk_link) > 1020): await bot.delete_messages(chat_id=message.chat.id, message_ids=dele) await message.reply(f'{pdisk_link}' , quote=True) else: await bot.delete_messages(chat_id=message.chat.id, message_ids=dele) await bot.send_photo(message.chat.id, message.photo.file_id, caption=f'{pdisk_link}') except Exception as e: await message.reply(f'Error: {e}', quote=True) async def pdisk_up(link): if ('pdisk' in link or 'kuklink' in link or 'kofilink' in link or 'cofilink' in link or 'bit' in link or 'vdshort' in link or 'vidrivers' in link or 'dplinks' in link or 'wslinker' in link or 'mdisk' in link or 'dood' in link): url = 'https://doodurl.in/api' params = {'api': API_KEY, 'url': link} async with aiohttp.ClientSession() as session: async with session.get(url, params=params, raise_for_status=True) as response: data = await response.json() v_url = data["shortenedUrl"] else: v_url = link return (v_url) async def multi_pdisk_up(ml_string): list_string = ml_string.splitlines() ml_string = ' \n'.join(list_string) new_ml_string = list(map(str, ml_string.split(" "))) new_ml_string = [sub.replace('https://t.me/Desi_Bhabhi_Aunty_hot_Video/41', 'https://t.me/Desi_Bhabhi_Aunty_hot_Video/61') for sub in new_ml_string] new_join_str = "".join(new_ml_string) urls = re.findall(r'(https?://[^\s]+)', new_join_str) nml_len = len(new_ml_string) u_len = len(urls) url_index = [] count = 0 for i in range(nml_len): for j in range(u_len): if (urls[j] in new_ml_string[i]): url_index.append(count) count += 1 new_urls = await new_pdisk_url(urls) url_index = list(dict.fromkeys(url_index)) i = 0 for j in url_index: new_ml_string[j] = new_ml_string[j].replace(urls[i], new_urls[i]) i += 1 new_string = " ".join(new_ml_string) return (new_string) async def new_pdisk_url(urls): new_urls = [] for i in urls: time.sleep(0.2) new_urls.append(await pdisk_up(i)) return new_urls bot.run()
true
true
f7111b54edc96721170c65660842877a6eab505a
3,373
py
Python
discovery-provider/src/models/__init__.py
lucylow/audius-protocol
5ef93462f9dc7df01a15877c02ca79b9a7d99236
[ "Apache-2.0" ]
1
2022-03-27T21:40:36.000Z
2022-03-27T21:40:36.000Z
discovery-provider/src/models/__init__.py
abelxmendoza/audius-protocol
33757e1b722a4be97960086b98b26ae3a75ee56b
[ "Apache-2.0" ]
null
null
null
discovery-provider/src/models/__init__.py
abelxmendoza/audius-protocol
33757e1b722a4be97960086b98b26ae3a75ee56b
[ "Apache-2.0" ]
null
null
null
from .aggregate_interval_play import AggregateIntervalPlay from .milestone import Milestone from .models import ( AggregateDailyAppNameMetrics, AggregateDailyTotalUsersMetrics, AggregateDailyUniqueUsersMetrics, AggregateMonthlyAppNameMetrics, AggregateMonthlyPlays, AggregateMonthlyTotalUsersMetrics, AggregateMonthlyUniqueUsersMetrics, AggregatePlaylist, AggregatePlays, AggregateTrack, AggregateUser, AppMetricsAllTime, AppMetricsTrailingMonth, AppMetricsTrailingWeek, AppNameMetrics, AssociatedWallet, Base, BlacklistedIPLD, Block, BlockMixin, Challenge, ChallengeDisbursement, ChallengeType, Follow, HourlyPlayCounts, IndexingCheckpoints, IPLDBlacklistBlock, ListenStreakChallenge, Play, Playlist, PlaysArchive, ProfileCompletionChallenge, Remix, Repost, RepostType, RouteMetrics, RouteMetricsAllTime, RouteMetricsDayMatview, RouteMetricsMonthMatview, RouteMetricsTrailingMonth, RouteMetricsTrailingWeek, Save, SaveType, SkippedTransaction, SkippedTransactionLevel, Stem, TagTrackUserMatview, Track, URSMContentNode, User, UserBalance, UserBalanceChange, UserChallenge, UserListeningHistory, WalletChain, ) from .related_artist import RelatedArtist from .reward_manager import RewardManagerTransaction from .spl_token_transaction import SPLTokenTransaction from .track_route import TrackRoute from .track_trending_score import TrackTrendingScore from .trending_param import TrendingParam from .trending_result import TrendingResult from .user_bank import UserBankAccount, UserBankTransaction from .user_events import UserEvents __all__ = [ "AggregateDailyAppNameMetrics", "AggregateDailyTotalUsersMetrics", "AggregateDailyUniqueUsersMetrics", "AggregateMonthlyAppNameMetrics", "AggregateMonthlyTotalUsersMetrics", "AggregateMonthlyUniqueUsersMetrics", "AggregatePlaylist", "AggregatePlays", "AggregateMonthlyPlays", "AggregateTrack", "AggregateUser", "AggregateIntervalPlay", "AppMetricsAllTime", "AppMetricsTrailingMonth", "AppMetricsTrailingWeek", "AppNameMetrics", "AssociatedWallet", "Base", "BlacklistedIPLD", "Block", "BlockMixin", "Challenge", "ChallengeDisbursement", "ChallengeType", "Follow", "HourlyPlayCounts", "IPLDBlacklistBlock", "IndexingCheckpoints", "ListenStreakChallenge", "Milestone", "Play", "PlaysArchive", "Playlist", "ProfileCompletionChallenge", "RelatedArtist", "Remix", "Repost", "RepostType", "RewardManagerTransaction", "RouteMetrics", "RouteMetricsAllTime", "RouteMetricsDayMatview", "RouteMetricsMonthMatview", "RouteMetricsTrailingMonth", "RouteMetricsTrailingWeek", "Save", "SaveType", "SkippedTransaction", "SkippedTransactionLevel", "SPLTokenTransaction", "Stem", "TagTrackUserMatview", "Track", "TrackRoute", "TrackTrendingScore", "TrendingParam", "TrendingResult", "URSMContentNode", "User", "UserBalance", "UserBalanceChange", "UserChallenge", "UserBankTransaction", "UserBankAccount", "UserEvents", "UserListeningHistory", "WalletChain", ]
24.266187
59
0.721613
from .aggregate_interval_play import AggregateIntervalPlay from .milestone import Milestone from .models import ( AggregateDailyAppNameMetrics, AggregateDailyTotalUsersMetrics, AggregateDailyUniqueUsersMetrics, AggregateMonthlyAppNameMetrics, AggregateMonthlyPlays, AggregateMonthlyTotalUsersMetrics, AggregateMonthlyUniqueUsersMetrics, AggregatePlaylist, AggregatePlays, AggregateTrack, AggregateUser, AppMetricsAllTime, AppMetricsTrailingMonth, AppMetricsTrailingWeek, AppNameMetrics, AssociatedWallet, Base, BlacklistedIPLD, Block, BlockMixin, Challenge, ChallengeDisbursement, ChallengeType, Follow, HourlyPlayCounts, IndexingCheckpoints, IPLDBlacklistBlock, ListenStreakChallenge, Play, Playlist, PlaysArchive, ProfileCompletionChallenge, Remix, Repost, RepostType, RouteMetrics, RouteMetricsAllTime, RouteMetricsDayMatview, RouteMetricsMonthMatview, RouteMetricsTrailingMonth, RouteMetricsTrailingWeek, Save, SaveType, SkippedTransaction, SkippedTransactionLevel, Stem, TagTrackUserMatview, Track, URSMContentNode, User, UserBalance, UserBalanceChange, UserChallenge, UserListeningHistory, WalletChain, ) from .related_artist import RelatedArtist from .reward_manager import RewardManagerTransaction from .spl_token_transaction import SPLTokenTransaction from .track_route import TrackRoute from .track_trending_score import TrackTrendingScore from .trending_param import TrendingParam from .trending_result import TrendingResult from .user_bank import UserBankAccount, UserBankTransaction from .user_events import UserEvents __all__ = [ "AggregateDailyAppNameMetrics", "AggregateDailyTotalUsersMetrics", "AggregateDailyUniqueUsersMetrics", "AggregateMonthlyAppNameMetrics", "AggregateMonthlyTotalUsersMetrics", "AggregateMonthlyUniqueUsersMetrics", "AggregatePlaylist", "AggregatePlays", "AggregateMonthlyPlays", "AggregateTrack", "AggregateUser", "AggregateIntervalPlay", "AppMetricsAllTime", "AppMetricsTrailingMonth", "AppMetricsTrailingWeek", "AppNameMetrics", "AssociatedWallet", "Base", "BlacklistedIPLD", "Block", "BlockMixin", "Challenge", "ChallengeDisbursement", "ChallengeType", "Follow", "HourlyPlayCounts", "IPLDBlacklistBlock", "IndexingCheckpoints", "ListenStreakChallenge", "Milestone", "Play", "PlaysArchive", "Playlist", "ProfileCompletionChallenge", "RelatedArtist", "Remix", "Repost", "RepostType", "RewardManagerTransaction", "RouteMetrics", "RouteMetricsAllTime", "RouteMetricsDayMatview", "RouteMetricsMonthMatview", "RouteMetricsTrailingMonth", "RouteMetricsTrailingWeek", "Save", "SaveType", "SkippedTransaction", "SkippedTransactionLevel", "SPLTokenTransaction", "Stem", "TagTrackUserMatview", "Track", "TrackRoute", "TrackTrendingScore", "TrendingParam", "TrendingResult", "URSMContentNode", "User", "UserBalance", "UserBalanceChange", "UserChallenge", "UserBankTransaction", "UserBankAccount", "UserEvents", "UserListeningHistory", "WalletChain", ]
true
true
f7111b7a88487687de3ed2da70a17151db0b1ae9
824
py
Python
setup.py
patilsangram/filesystem
e5e5dc6be07ea656649f11484b072c43e3249163
[ "MIT" ]
null
null
null
setup.py
patilsangram/filesystem
e5e5dc6be07ea656649f11484b072c43e3249163
[ "MIT" ]
null
null
null
setup.py
patilsangram/filesystem
e5e5dc6be07ea656649f11484b072c43e3249163
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from pip.req import parse_requirements import re, ast # get version from __version__ variable in file_management/__init__.py _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('file_management/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) requirements = parse_requirements("requirements.txt", session="") setup( name='file_management', version=version, description='App for managing File', author='Indictrans', author_email='sangram.p@indictranstech.com', packages=find_packages(), zip_safe=False, include_package_data=True, install_requires=[str(ir.req) for ir in requirements], dependency_links=[str(ir._link) for ir in requirements if ir._link] )
30.518519
70
0.746359
from setuptools import setup, find_packages from pip.req import parse_requirements import re, ast _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('file_management/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) requirements = parse_requirements("requirements.txt", session="") setup( name='file_management', version=version, description='App for managing File', author='Indictrans', author_email='sangram.p@indictranstech.com', packages=find_packages(), zip_safe=False, include_package_data=True, install_requires=[str(ir.req) for ir in requirements], dependency_links=[str(ir._link) for ir in requirements if ir._link] )
true
true
f7111bc8bd0bd3222f4299cc296a1b52711c7e58
632
py
Python
feder/letters/migrations/0010_auto_20180112_1721.py
dzemeuksis/feder
32ef7793af6256d4ecada61505c7baf334b34419
[ "MIT" ]
16
2015-08-11T17:20:26.000Z
2022-02-11T20:15:41.000Z
feder/letters/migrations/0010_auto_20180112_1721.py
dzemeuksis/feder
32ef7793af6256d4ecada61505c7baf334b34419
[ "MIT" ]
534
2015-08-04T00:10:54.000Z
2022-03-17T10:44:47.000Z
feder/letters/migrations/0010_auto_20180112_1721.py
dzemeuksis/feder
32ef7793af6256d4ecada61505c7baf334b34419
[ "MIT" ]
10
2017-08-30T13:34:32.000Z
2022-02-18T13:00:35.000Z
# Generated by Django 1.11.7 on 2018-01-12 17:21 from django.db import migrations class Migration(migrations.Migration): dependencies = [("letters", "0009_auto_20170826_0742")] operations = [ migrations.AlterModelOptions( name="letter", options={ "ordering": ["created"], "permissions": ( ("can_filter_eml", "Can filter eml"), ("recognize_letter", "Can recognize letter"), ), "verbose_name": "Letter", "verbose_name_plural": "Letters", }, ) ]
26.333333
65
0.509494
from django.db import migrations class Migration(migrations.Migration): dependencies = [("letters", "0009_auto_20170826_0742")] operations = [ migrations.AlterModelOptions( name="letter", options={ "ordering": ["created"], "permissions": ( ("can_filter_eml", "Can filter eml"), ("recognize_letter", "Can recognize letter"), ), "verbose_name": "Letter", "verbose_name_plural": "Letters", }, ) ]
true
true
f7111c244cf17ed30e14fe5cad1f582a6877bbef
3,512
py
Python
ranger/commands.py
mariofrescas/configfiles
694623d9590ecc939a6ebeed8dd7806ed0dc248e
[ "MIT" ]
null
null
null
ranger/commands.py
mariofrescas/configfiles
694623d9590ecc939a6ebeed8dd7806ed0dc248e
[ "MIT" ]
null
null
null
ranger/commands.py
mariofrescas/configfiles
694623d9590ecc939a6ebeed8dd7806ed0dc248e
[ "MIT" ]
null
null
null
from ranger.api.commands import Command class paste_as_root(Command): def execute(self): if self.fm.do_cut: self.fm.execute_console('shell sudo mv %c .') else: self.fm.execute_console('shell sudo cp -r %c .') class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifier: # match only directories command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m --reverse --header='Jump to file'" else: # match files and directories command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m --reverse --header='Jump to filemap <C-f> fzf_select'" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file) import os from ranger.core.loader import CommandLoader class extract_here(Command): def execute(self): """ extract selected files to current directory.""" cwd = self.fm.thisdir marked_files = tuple(cwd.get_selection()) def refresh(_): cwd = self.fm.get_directory(original_path) cwd.load_content() one_file = marked_files[0] cwd = self.fm.thisdir original_path = cwd.path au_flags = ['-x', cwd.path] au_flags += self.line.split()[1:] au_flags += ['-e'] self.fm.copy_buffer.clear() self.fm.cut_buffer = False if len(marked_files) == 1: descr = "extracting: " + os.path.basename(one_file.path) else: descr = "extracting files from: " + os.path.basename( one_file.dirname) obj = CommandLoader(args=['aunpack'] + au_flags + [f.path for f in marked_files], descr=descr, read=True) obj.signal_bind('after', refresh) self.fm.loader.add(obj) import os from ranger.core.loader import CommandLoader class compress(Command): def execute(self): """ Compress marked files to current directory """ cwd = self.fm.thisdir marked_files = cwd.get_selection() if not marked_files: return def refresh(_): cwd = self.fm.get_directory(original_path) cwd.load_content() original_path = cwd.path parts = self.line.split() au_flags = parts[1:] descr = "compressing files in: " + os.path.basename(parts[1]) obj = CommandLoader(args=['apack'] + au_flags + \ [os.path.relpath(f.path, cwd.path) for f in marked_files], descr=descr, read=True) obj.signal_bind('after', refresh) self.fm.loader.add(obj) def tab(self, tabnum): """ Complete with current folder name """ extension = ['.zip', '.tar.gz', '.rar', '.7z'] return ['compress ' + os.path.basename(self.fm.thisdir.path) + ext for ext in extension]
33.132075
118
0.577733
from ranger.api.commands import Command class paste_as_root(Command): def execute(self): if self.fm.do_cut: self.fm.execute_console('shell sudo mv %c .') else: self.fm.execute_console('shell sudo cp -r %c .') class fzf_select(Command): def execute(self): import subprocess import os.path if self.quantifier: command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m --reverse --header='Jump to file'" else: command="find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \ -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m --reverse --header='Jump to filemap <C-f> fzf_select'" fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE) stdout, stderr = fzf.communicate() if fzf.returncode == 0: fzf_file = os.path.abspath(stdout.rstrip('\n')) if os.path.isdir(fzf_file): self.fm.cd(fzf_file) else: self.fm.select_file(fzf_file) import os from ranger.core.loader import CommandLoader class extract_here(Command): def execute(self): cwd = self.fm.thisdir marked_files = tuple(cwd.get_selection()) def refresh(_): cwd = self.fm.get_directory(original_path) cwd.load_content() one_file = marked_files[0] cwd = self.fm.thisdir original_path = cwd.path au_flags = ['-x', cwd.path] au_flags += self.line.split()[1:] au_flags += ['-e'] self.fm.copy_buffer.clear() self.fm.cut_buffer = False if len(marked_files) == 1: descr = "extracting: " + os.path.basename(one_file.path) else: descr = "extracting files from: " + os.path.basename( one_file.dirname) obj = CommandLoader(args=['aunpack'] + au_flags + [f.path for f in marked_files], descr=descr, read=True) obj.signal_bind('after', refresh) self.fm.loader.add(obj) import os from ranger.core.loader import CommandLoader class compress(Command): def execute(self): cwd = self.fm.thisdir marked_files = cwd.get_selection() if not marked_files: return def refresh(_): cwd = self.fm.get_directory(original_path) cwd.load_content() original_path = cwd.path parts = self.line.split() au_flags = parts[1:] descr = "compressing files in: " + os.path.basename(parts[1]) obj = CommandLoader(args=['apack'] + au_flags + \ [os.path.relpath(f.path, cwd.path) for f in marked_files], descr=descr, read=True) obj.signal_bind('after', refresh) self.fm.loader.add(obj) def tab(self, tabnum): extension = ['.zip', '.tar.gz', '.rar', '.7z'] return ['compress ' + os.path.basename(self.fm.thisdir.path) + ext for ext in extension]
true
true
f7111c4b339a8c9a31964af5560fd7bc01cde698
18,586
py
Python
CallHome/_version.py
yinruiqing/pyannote-db-callhome
81db9c8cc611322d10e9bddb3af0d72707124ec8
[ "MIT" ]
3
2019-04-15T12:27:57.000Z
2021-06-08T20:30:55.000Z
CallHome/_version.py
yinruiqing/pyannote-db-callhome
81db9c8cc611322d10e9bddb3af0d72707124ec8
[ "MIT" ]
null
null
null
CallHome/_version.py
yinruiqing/pyannote-db-callhome
81db9c8cc611322d10e9bddb3af0d72707124ec8
[ "MIT" ]
1
2019-11-26T01:24:10.000Z
2019-11-26T01:24:10.000Z
# 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" cfg.tag_prefix = "" # replace mydatabase the same way you did in "setup.py" cfg.parentdir_prefix = "pyannote-db-callhome-" # replace MyDatabase the same way you did in "setup.py" cfg.versionfile_source = "CallHome/_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.537285
79
0.585494
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" cfg.tag_prefix = "" cfg.parentdir_prefix = "pyannote-db-callhome-" cfg.versionfile_source = "CallHome/_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
f7111d7380c0da12701099921e08841c81cb9296
1,795
py
Python
test/functional/feature_filelock.py
caffeine239/bitcoin
94e5f13e62041bc299514b38a04ba1686002143e
[ "MIT" ]
null
null
null
test/functional/feature_filelock.py
caffeine239/bitcoin
94e5f13e62041bc299514b38a04ba1686002143e
[ "MIT" ]
null
null
null
test/functional/feature_filelock.py
caffeine239/bitcoin
94e5f13e62041bc299514b38a04ba1686002143e
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Check that it's not possible to start a second muskcoind instance using the same datadir or wallet.""" import os from test_framework.test_framework import BitcoinTestFramework from test_framework.test_node import ErrorMatch class FilelockTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 def setup_network(self): self.add_nodes(self.num_nodes, extra_args=None) self.nodes[0].start([]) self.nodes[0].wait_for_rpc_connection() def run_test(self): datadir = os.path.join(self.nodes[0].datadir, 'regtest') self.log.info("Using datadir {}".format(datadir)) self.log.info("Check that we can't start a second muskcoind instance using the same datadir") expected_msg = "Error: Cannot obtain a lock on data directory {}. Muskcoin Core is probably already running.".format(datadir) self.nodes[1].assert_start_raises_init_error(extra_args=['-datadir={}'.format(self.nodes[0].datadir), '-noserver'], expected_msg=expected_msg) if self.is_wallet_compiled(): wallet_dir = os.path.join(datadir, 'wallets') self.log.info("Check that we can't start a second muskcoind instance using the same wallet") expected_msg = "Error: Error initializing wallet database environment" self.nodes[1].assert_start_raises_init_error(extra_args=['-walletdir={}'.format(wallet_dir), '-noserver'], expected_msg=expected_msg, match=ErrorMatch.PARTIAL_REGEX) if __name__ == '__main__': FilelockTest().main()
48.513514
177
0.720891
import os from test_framework.test_framework import BitcoinTestFramework from test_framework.test_node import ErrorMatch class FilelockTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 def setup_network(self): self.add_nodes(self.num_nodes, extra_args=None) self.nodes[0].start([]) self.nodes[0].wait_for_rpc_connection() def run_test(self): datadir = os.path.join(self.nodes[0].datadir, 'regtest') self.log.info("Using datadir {}".format(datadir)) self.log.info("Check that we can't start a second muskcoind instance using the same datadir") expected_msg = "Error: Cannot obtain a lock on data directory {}. Muskcoin Core is probably already running.".format(datadir) self.nodes[1].assert_start_raises_init_error(extra_args=['-datadir={}'.format(self.nodes[0].datadir), '-noserver'], expected_msg=expected_msg) if self.is_wallet_compiled(): wallet_dir = os.path.join(datadir, 'wallets') self.log.info("Check that we can't start a second muskcoind instance using the same wallet") expected_msg = "Error: Error initializing wallet database environment" self.nodes[1].assert_start_raises_init_error(extra_args=['-walletdir={}'.format(wallet_dir), '-noserver'], expected_msg=expected_msg, match=ErrorMatch.PARTIAL_REGEX) if __name__ == '__main__': FilelockTest().main()
true
true
f7111f05c84ed4cfc811daaea97b7ff27f4879ce
6,649
py
Python
infra/config.py
szyszy/dist_test
a992ed1c007e9ec4850643e707bc803fbf5a084b
[ "Apache-2.0" ]
28
2016-05-03T21:16:48.000Z
2021-06-11T17:09:58.000Z
infra/config.py
szyszy/dist_test
a992ed1c007e9ec4850643e707bc803fbf5a084b
[ "Apache-2.0" ]
45
2016-05-03T22:16:09.000Z
2019-04-23T20:53:07.000Z
infra/config.py
szyszy/dist_test
a992ed1c007e9ec4850643e707bc803fbf5a084b
[ "Apache-2.0" ]
25
2016-04-20T00:02:08.000Z
2020-11-24T18:05:45.000Z
from ConfigParser import SafeConfigParser import errno import logging import os import urllib2 class Config(object): # S3 settings AWS_ACCESS_KEY_CONFIG = ('aws', 'access_key', 'AWS_ACCESS_KEY') AWS_SECRET_KEY_CONFIG = ('aws', 'secret_key', 'AWS_SECRET_KEY') AWS_TEST_RESULT_BUCKET_CONFIG = ('aws', 'test_result_bucket', 'TEST_RESULT_BUCKET') # MySQL settings MYSQL_HOST_CONFIG = ('mysql', 'host', 'MYSQL_HOST') MYSQL_PORT_CONFIG = ('mysql', 'port', 'MYSQL_PORT') MYSQL_USER_CONFIG = ('mysql', 'user', 'MYSQL_USER') MYSQL_PWD_CONFIG = ('mysql', 'password', 'MYSQL_PWD') MYSQL_DB_CONFIG = ('mysql', 'database', 'MYSQL_DB') # Isolate settings ISOLATE_HOME_CONFIG = ('isolate', 'home', "ISOLATE_HOME") ISOLATE_SERVER_CONFIG = ('isolate', 'server', "ISOLATE_SERVER") ISOLATE_CACHE_DIR_CONFIG = ('isolate', 'cache_dir', "ISOLATE_CACHE_DIR") # Beanstalk settings BEANSTALK_HOST_CONFIG = ('beanstalk', 'host', 'BEANSTALK_HOST') # Dist test settings DIST_TEST_MASTER_CONFIG = ('dist_test', 'master', "DIST_TEST_MASTER") DIST_TEST_JOB_PATH_CONFIG = ('dist_test', 'job_path', 'DIST_TEST_JOB_PATH') DIST_TEST_USER_CONFIG = ('dist_test', 'user', 'DIST_TEST_USER') DIST_TEST_PASSWORD_CONFIG = ('dist_test', 'password', 'DIST_TEST_PASSWORD') DIST_TEST_URL_TIMEOUT_CONFIG = ('dist_test', 'url_timeout', 'DIST_TEST_URL_TIMEOUT') def __init__(self, path=None): if path is None: path = os.getenv("DIST_TEST_CNF") if path is None: path = os.path.join(os.getenv("HOME"), ".dist_test.cnf") logging.info("Reading configuration from %s", path) # Populate parser with default values defaults = { "log_dir" : os.path.join(os.path.dirname(os.path.realpath(__file__)), "logs"), "submit_gce_metrics" : "True", "allowed_ip_ranges": "0.0.0.0/0", "accounts": "{}", } self.config = SafeConfigParser(defaults) self.config.read(path) # Isolate settings self.ISOLATE_HOME = self._get_with_env_override(*self.ISOLATE_HOME_CONFIG) self.ISOLATE_SERVER = self._get_with_env_override(*self.ISOLATE_SERVER_CONFIG) self.ISOLATE_CACHE_DIR = self._get_with_env_override(*self.ISOLATE_CACHE_DIR_CONFIG) # S3 settings self.AWS_ACCESS_KEY = self._get_with_env_override(*self.AWS_ACCESS_KEY_CONFIG) self.AWS_SECRET_KEY = self._get_with_env_override(*self.AWS_SECRET_KEY_CONFIG) self.AWS_TEST_RESULT_BUCKET = self._get_with_env_override(*self.AWS_TEST_RESULT_BUCKET_CONFIG) # MySQL settings self.MYSQL_HOST = self._get_with_env_override(*self.MYSQL_HOST_CONFIG) try: self.MYSQL_PORT = int(self._get_with_env_override(*self.MYSQL_PORT_CONFIG)) except: self.MYSQL_PORT = 3306 self.MYSQL_USER = self._get_with_env_override(*self.MYSQL_USER_CONFIG) self.MYSQL_PWD = self._get_with_env_override(*self.MYSQL_PWD_CONFIG) self.MYSQL_DB = self._get_with_env_override(*self.MYSQL_DB_CONFIG) # Beanstalk settings self.BEANSTALK_HOST = self._get_with_env_override(*self.BEANSTALK_HOST_CONFIG) # dist_test settings if not self.config.has_section('dist_test'): self.config.add_section('dist_test') self.DIST_TEST_MASTER = self._get_with_env_override(*self.DIST_TEST_MASTER_CONFIG) self.DIST_TEST_JOB_PATH = self._get_with_env_override(*self.DIST_TEST_JOB_PATH_CONFIG) if self.DIST_TEST_JOB_PATH is None: self.DIST_TEST_JOB_PATH = os.path.expanduser("~/.dist-test-last-job") self.DIST_TEST_USER = self._get_with_env_override(*self.DIST_TEST_USER_CONFIG) self.DIST_TEST_PASSWORD = self._get_with_env_override(*self.DIST_TEST_PASSWORD_CONFIG) self.DIST_TEST_URL_TIMEOUT = self._get_with_env_override(*self.DIST_TEST_URL_TIMEOUT_CONFIG) if self.DIST_TEST_URL_TIMEOUT is not None: self.DIST_TEST_URL_TIMEOUT = float(self.DIST_TEST_URL_TIMEOUT) # dist_test master configs (in the 'dist_test' section) self.DIST_TEST_ALLOWED_IP_RANGES = self.config.get('dist_test', 'allowed_ip_ranges') self.ACCOUNTS = self.config.get('dist_test', 'accounts') self.log_dir = self.config.get('dist_test', 'log_dir') # Make the log directory if it doesn't exist Config.mkdir_p(self.log_dir) self.SERVER_ACCESS_LOG = os.path.join(self.log_dir, "server-access.log") self.SERVER_ERROR_LOG = os.path.join(self.log_dir, "server-error.log") self.SERVER_LOG = os.path.join(self.log_dir, "server.log") self.SLAVE_LOG = os.path.join(self.log_dir, "slave.log") @staticmethod def mkdir_p(path): """Similar to mkdir -p, make a directory ignoring EEXIST""" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def _get_with_env_override(self, section, option, env_key): env_value = os.environ.get(env_key) if env_value is not None: return env_value file_value = None if self.config.has_option(section, option): file_value = self.config.get(section, option) return file_value def ensure_aws_configured(self): self._ensure_configs([self.AWS_ACCESS_KEY_CONFIG, self.AWS_SECRET_KEY_CONFIG, self.AWS_TEST_RESULT_BUCKET_CONFIG]) def ensure_isolate_configured(self): self._ensure_configs([self.ISOLATE_HOME_CONFIG, self.ISOLATE_SERVER_CONFIG, self.ISOLATE_CACHE_DIR_CONFIG]) def ensure_mysql_configured(self): self._ensure_configs([self.MYSQL_HOST_CONFIG, self.MYSQL_USER_CONFIG, self.MYSQL_PWD_CONFIG, self.MYSQL_DB_CONFIG]) def ensure_beanstalk_configured(self): self._ensure_configs([self.BEANSTALK_HOST_CONFIG]) def ensure_dist_test_configured(self): self._ensure_configs([self.DIST_TEST_MASTER_CONFIG]) def _ensure_configs(self, configs): for config in configs: if self._get_with_env_override(*config) is None: raise Exception(("Missing configuration %s.%s. Please set in the config file or " + "set the environment variable %s.") % config) def configure_auth(self): """ Configure urllib2 to pass authentication information if provided in the configuration. """ if not self.DIST_TEST_USER: return password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, self.DIST_TEST_MASTER, self.DIST_TEST_USER, self.DIST_TEST_PASSWORD) handler = urllib2.HTTPDigestAuthHandler(password_mgr) opener = urllib2.build_opener(handler) urllib2.install_opener(opener)
41.298137
98
0.719958
from ConfigParser import SafeConfigParser import errno import logging import os import urllib2 class Config(object): AWS_ACCESS_KEY_CONFIG = ('aws', 'access_key', 'AWS_ACCESS_KEY') AWS_SECRET_KEY_CONFIG = ('aws', 'secret_key', 'AWS_SECRET_KEY') AWS_TEST_RESULT_BUCKET_CONFIG = ('aws', 'test_result_bucket', 'TEST_RESULT_BUCKET') MYSQL_HOST_CONFIG = ('mysql', 'host', 'MYSQL_HOST') MYSQL_PORT_CONFIG = ('mysql', 'port', 'MYSQL_PORT') MYSQL_USER_CONFIG = ('mysql', 'user', 'MYSQL_USER') MYSQL_PWD_CONFIG = ('mysql', 'password', 'MYSQL_PWD') MYSQL_DB_CONFIG = ('mysql', 'database', 'MYSQL_DB') ISOLATE_HOME_CONFIG = ('isolate', 'home', "ISOLATE_HOME") ISOLATE_SERVER_CONFIG = ('isolate', 'server', "ISOLATE_SERVER") ISOLATE_CACHE_DIR_CONFIG = ('isolate', 'cache_dir', "ISOLATE_CACHE_DIR") BEANSTALK_HOST_CONFIG = ('beanstalk', 'host', 'BEANSTALK_HOST') DIST_TEST_MASTER_CONFIG = ('dist_test', 'master', "DIST_TEST_MASTER") DIST_TEST_JOB_PATH_CONFIG = ('dist_test', 'job_path', 'DIST_TEST_JOB_PATH') DIST_TEST_USER_CONFIG = ('dist_test', 'user', 'DIST_TEST_USER') DIST_TEST_PASSWORD_CONFIG = ('dist_test', 'password', 'DIST_TEST_PASSWORD') DIST_TEST_URL_TIMEOUT_CONFIG = ('dist_test', 'url_timeout', 'DIST_TEST_URL_TIMEOUT') def __init__(self, path=None): if path is None: path = os.getenv("DIST_TEST_CNF") if path is None: path = os.path.join(os.getenv("HOME"), ".dist_test.cnf") logging.info("Reading configuration from %s", path) defaults = { "log_dir" : os.path.join(os.path.dirname(os.path.realpath(__file__)), "logs"), "submit_gce_metrics" : "True", "allowed_ip_ranges": "0.0.0.0/0", "accounts": "{}", } self.config = SafeConfigParser(defaults) self.config.read(path) self.ISOLATE_HOME = self._get_with_env_override(*self.ISOLATE_HOME_CONFIG) self.ISOLATE_SERVER = self._get_with_env_override(*self.ISOLATE_SERVER_CONFIG) self.ISOLATE_CACHE_DIR = self._get_with_env_override(*self.ISOLATE_CACHE_DIR_CONFIG) self.AWS_ACCESS_KEY = self._get_with_env_override(*self.AWS_ACCESS_KEY_CONFIG) self.AWS_SECRET_KEY = self._get_with_env_override(*self.AWS_SECRET_KEY_CONFIG) self.AWS_TEST_RESULT_BUCKET = self._get_with_env_override(*self.AWS_TEST_RESULT_BUCKET_CONFIG) self.MYSQL_HOST = self._get_with_env_override(*self.MYSQL_HOST_CONFIG) try: self.MYSQL_PORT = int(self._get_with_env_override(*self.MYSQL_PORT_CONFIG)) except: self.MYSQL_PORT = 3306 self.MYSQL_USER = self._get_with_env_override(*self.MYSQL_USER_CONFIG) self.MYSQL_PWD = self._get_with_env_override(*self.MYSQL_PWD_CONFIG) self.MYSQL_DB = self._get_with_env_override(*self.MYSQL_DB_CONFIG) self.BEANSTALK_HOST = self._get_with_env_override(*self.BEANSTALK_HOST_CONFIG) if not self.config.has_section('dist_test'): self.config.add_section('dist_test') self.DIST_TEST_MASTER = self._get_with_env_override(*self.DIST_TEST_MASTER_CONFIG) self.DIST_TEST_JOB_PATH = self._get_with_env_override(*self.DIST_TEST_JOB_PATH_CONFIG) if self.DIST_TEST_JOB_PATH is None: self.DIST_TEST_JOB_PATH = os.path.expanduser("~/.dist-test-last-job") self.DIST_TEST_USER = self._get_with_env_override(*self.DIST_TEST_USER_CONFIG) self.DIST_TEST_PASSWORD = self._get_with_env_override(*self.DIST_TEST_PASSWORD_CONFIG) self.DIST_TEST_URL_TIMEOUT = self._get_with_env_override(*self.DIST_TEST_URL_TIMEOUT_CONFIG) if self.DIST_TEST_URL_TIMEOUT is not None: self.DIST_TEST_URL_TIMEOUT = float(self.DIST_TEST_URL_TIMEOUT) self.DIST_TEST_ALLOWED_IP_RANGES = self.config.get('dist_test', 'allowed_ip_ranges') self.ACCOUNTS = self.config.get('dist_test', 'accounts') self.log_dir = self.config.get('dist_test', 'log_dir') Config.mkdir_p(self.log_dir) self.SERVER_ACCESS_LOG = os.path.join(self.log_dir, "server-access.log") self.SERVER_ERROR_LOG = os.path.join(self.log_dir, "server-error.log") self.SERVER_LOG = os.path.join(self.log_dir, "server.log") self.SLAVE_LOG = os.path.join(self.log_dir, "slave.log") @staticmethod def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def _get_with_env_override(self, section, option, env_key): env_value = os.environ.get(env_key) if env_value is not None: return env_value file_value = None if self.config.has_option(section, option): file_value = self.config.get(section, option) return file_value def ensure_aws_configured(self): self._ensure_configs([self.AWS_ACCESS_KEY_CONFIG, self.AWS_SECRET_KEY_CONFIG, self.AWS_TEST_RESULT_BUCKET_CONFIG]) def ensure_isolate_configured(self): self._ensure_configs([self.ISOLATE_HOME_CONFIG, self.ISOLATE_SERVER_CONFIG, self.ISOLATE_CACHE_DIR_CONFIG]) def ensure_mysql_configured(self): self._ensure_configs([self.MYSQL_HOST_CONFIG, self.MYSQL_USER_CONFIG, self.MYSQL_PWD_CONFIG, self.MYSQL_DB_CONFIG]) def ensure_beanstalk_configured(self): self._ensure_configs([self.BEANSTALK_HOST_CONFIG]) def ensure_dist_test_configured(self): self._ensure_configs([self.DIST_TEST_MASTER_CONFIG]) def _ensure_configs(self, configs): for config in configs: if self._get_with_env_override(*config) is None: raise Exception(("Missing configuration %s.%s. Please set in the config file or " + "set the environment variable %s.") % config) def configure_auth(self): if not self.DIST_TEST_USER: return password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, self.DIST_TEST_MASTER, self.DIST_TEST_USER, self.DIST_TEST_PASSWORD) handler = urllib2.HTTPDigestAuthHandler(password_mgr) opener = urllib2.build_opener(handler) urllib2.install_opener(opener)
true
true
f7111ff9d442298eb7e9b8dc90218d35c91d6141
2,107
py
Python
jodconverter-web/src/main/office/program/python-core-2.7.6/lib/ctypes/macholib/dylib.py
Congliang0229/kkFileView
1b5793c10aaa047f78c6be4abc41d807e71f71ab
[ "Apache-2.0" ]
112
2015-01-15T21:36:02.000Z
2021-12-28T19:19:01.000Z
jodconverter-web/src/main/office/program/python-core-2.7.6/lib/ctypes/macholib/dylib.py
Congliang0229/kkFileView
1b5793c10aaa047f78c6be4abc41d807e71f71ab
[ "Apache-2.0" ]
6
2017-03-14T00:42:42.000Z
2022-01-06T23:09:18.000Z
jodconverter-web/src/main/office/program/python-core-2.7.6/lib/ctypes/macholib/dylib.py
Congliang0229/kkFileView
1b5793c10aaa047f78c6be4abc41d807e71f71ab
[ "Apache-2.0" ]
41
2017-03-18T14:11:58.000Z
2021-04-14T05:06:09.000Z
###################################################################### # This file should be kept compatible with Python 2.3, see PEP 291. # ###################################################################### """ Generic dylib path manipulation """ import re __all__ = ['dylib_info'] DYLIB_RE = re.compile(r"""(?x) (?P<location>^.*)(?:^|/) (?P<name> (?P<shortname>\w+?) (?:\.(?P<version>[^._]+))? (?:_(?P<suffix>[^._]+))? \.dylib$ ) """) def dylib_info(filename): """ A dylib name can take one of the following four forms: Location/Name.SomeVersion_Suffix.dylib Location/Name.SomeVersion.dylib Location/Name_Suffix.dylib Location/Name.dylib returns None if not found or a mapping equivalent to: dict( location='Location', name='Name.SomeVersion_Suffix.dylib', shortname='Name', version='SomeVersion', suffix='Suffix', ) Note that SomeVersion and Suffix are optional and may be None if not present. """ is_dylib = DYLIB_RE.match(filename) if not is_dylib: return None return is_dylib.groupdict() def test_dylib_info(): def d(location=None, name=None, shortname=None, version=None, suffix=None): return dict( location=location, name=name, shortname=shortname, version=version, suffix=suffix ) assert dylib_info('completely/invalid') is None assert dylib_info('completely/invalide_debug') is None assert dylib_info('P/Foo.dylib') == d('P', 'Foo.dylib', 'Foo') assert dylib_info('P/Foo_debug.dylib') == d('P', 'Foo_debug.dylib', 'Foo', suffix='debug') assert dylib_info('P/Foo.A.dylib') == d('P', 'Foo.A.dylib', 'Foo', 'A') assert dylib_info('P/Foo_debug.A.dylib') == d('P', 'Foo_debug.A.dylib', 'Foo_debug', 'A') assert dylib_info('P/Foo.A_debug.dylib') == d('P', 'Foo.A_debug.dylib', 'Foo', 'A', 'debug') if __name__ == '__main__': test_dylib_info()
31.447761
97
0.542477
true
true
f711200559a829dfeddb00585fc885fd87a0e944
31,403
py
Python
nni/retiarii/nn/pytorch/api.py
ggzhang0071/nni
f4145e62d89c3ca383cf00f2de5dfd2d1025ad92
[ "MIT" ]
1
2022-03-06T12:57:08.000Z
2022-03-06T12:57:08.000Z
nni/retiarii/nn/pytorch/api.py
ggzhang0071/nni
f4145e62d89c3ca383cf00f2de5dfd2d1025ad92
[ "MIT" ]
null
null
null
nni/retiarii/nn/pytorch/api.py
ggzhang0071/nni
f4145e62d89c3ca383cf00f2de5dfd2d1025ad92
[ "MIT" ]
null
null
null
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import math import operator import warnings from typing import Any, List, Union, Dict, Optional, Callable, Iterable, NoReturn, TypeVar import torch import torch.nn as nn from nni.common.serializer import Translatable from nni.retiarii.serializer import basic_unit from nni.retiarii.utils import STATE_DICT_PY_MAPPING_PARTIAL from .utils import Mutable, generate_new_label, get_fixed_value __all__ = ['LayerChoice', 'InputChoice', 'ValueChoice', 'Placeholder', 'ChosenInputs'] class LayerChoice(Mutable): """ Layer choice selects one of the ``candidates``, then apply it on inputs and return results. Layer choice does not allow itself to be nested. Parameters ---------- candidates : list of nn.Module or OrderedDict A module list to be selected from. prior : list of float Prior distribution used in random sampling. label : str Identifier of the layer choice. Attributes ---------- length : int Deprecated. Number of ops to choose from. ``len(layer_choice)`` is recommended. names : list of str Names of candidates. choices : list of Module Deprecated. A list of all candidate modules in the layer choice module. ``list(layer_choice)`` is recommended, which will serve the same purpose. Notes ----- ``candidates`` can be a list of modules or a ordered dict of named modules, for example, .. code-block:: python self.op_choice = LayerChoice(OrderedDict([ ("conv3x3", nn.Conv2d(3, 16, 128)), ("conv5x5", nn.Conv2d(5, 16, 128)), ("conv7x7", nn.Conv2d(7, 16, 128)) ])) Elements in layer choice can be modified or deleted. Use ``del self.op_choice["conv5x5"]`` or ``self.op_choice[1] = nn.Conv3d(...)``. Adding more choices is not supported yet. """ # FIXME: prior is designed but not supported yet @classmethod def create_fixed_module(cls, candidates: Union[Dict[str, nn.Module], List[nn.Module]], *, label: Optional[str] = None, **kwargs): chosen = get_fixed_value(label) if isinstance(candidates, list): result = candidates[int(chosen)] else: result = candidates[chosen] # map the named hierarchies to support weight inheritance for python engine if hasattr(result, STATE_DICT_PY_MAPPING_PARTIAL): # handle cases where layer choices are nested # already has a mapping, will merge with it prev_mapping = getattr(result, STATE_DICT_PY_MAPPING_PARTIAL) setattr(result, STATE_DICT_PY_MAPPING_PARTIAL, {k: f'{chosen}.{v}' for k, v in prev_mapping.items()}) else: # "result" needs to know where to map itself. # Ideally, we should put a _mapping_ in the module where "result" is located, # but it's impossible to put mapping into parent module here. setattr(result, STATE_DICT_PY_MAPPING_PARTIAL, {'__self__': str(chosen)}) return result def __init__(self, candidates: Union[Dict[str, nn.Module], List[nn.Module]], *, prior: Optional[List[float]] = None, label: Optional[str] = None, **kwargs): super(LayerChoice, self).__init__() if 'key' in kwargs: warnings.warn(f'"key" is deprecated. Assuming label.') label = kwargs['key'] if 'return_mask' in kwargs: warnings.warn(f'"return_mask" is deprecated. Ignoring...') if 'reduction' in kwargs: warnings.warn(f'"reduction" is deprecated. Ignoring...') self.candidates = candidates self.prior = prior or [1 / len(candidates) for _ in range(len(candidates))] assert abs(sum(self.prior) - 1) < 1e-5, 'Sum of prior distribution is not 1.' self._label = generate_new_label(label) self.names = [] if isinstance(candidates, dict): for name, module in candidates.items(): assert name not in ["length", "reduction", "return_mask", "_key", "key", "names"], \ "Please don't use a reserved name '{}' for your module.".format(name) self.add_module(name, module) self.names.append(name) elif isinstance(candidates, list): for i, module in enumerate(candidates): self.add_module(str(i), module) self.names.append(str(i)) else: raise TypeError("Unsupported candidates type: {}".format(type(candidates))) self._first_module = self._modules[self.names[0]] # to make the dummy forward meaningful @property def key(self): return self._key() @torch.jit.ignore def _key(self): warnings.warn('Using key to access the identifier of LayerChoice is deprecated. Please use label instead.', category=DeprecationWarning) return self._label @property def label(self): return self._label def __getitem__(self, idx): if isinstance(idx, str): return self._modules[idx] return list(self)[idx] def __setitem__(self, idx, module): key = idx if isinstance(idx, str) else self.names[idx] return setattr(self, key, module) def __delitem__(self, idx): if isinstance(idx, slice): for key in self.names[idx]: delattr(self, key) else: if isinstance(idx, str): key, idx = idx, self.names.index(idx) else: key = self.names[idx] delattr(self, key) del self.names[idx] def __len__(self): return len(self.names) def __iter__(self): return map(lambda name: self._modules[name], self.names) @property def choices(self): return self._choices() @torch.jit.ignore def _choices(self): warnings.warn("layer_choice.choices is deprecated. Use `list(layer_choice)` instead.", category=DeprecationWarning) return list(self) def forward(self, x): warnings.warn('You should not run forward of this module directly.') return self._first_module(x) def __repr__(self): return f'LayerChoice({self.candidates}, label={repr(self.label)})' try: from typing import Literal except ImportError: from typing_extensions import Literal ReductionType = Literal['mean', 'concat', 'sum', 'none'] class InputChoice(Mutable): """ Input choice selects ``n_chosen`` inputs from ``choose_from`` (contains ``n_candidates`` keys). Use ``reduction`` to specify how chosen inputs are reduced into one output. A few options are: * ``none``: do nothing and return the list directly. * ``sum``: summing all the chosen inputs. * ``mean``: taking the average of all chosen inputs. * ``concat``: concatenate all chosen inputs at dimension 1. We don't support customizing reduction yet. Parameters ---------- n_candidates : int Number of inputs to choose from. It is required. n_chosen : int Recommended inputs to choose. If None, mutator is instructed to select any. reduction : str ``mean``, ``concat``, ``sum`` or ``none``. prior : list of float Prior distribution used in random sampling. label : str Identifier of the input choice. """ @classmethod def create_fixed_module(cls, n_candidates: int, n_chosen: Optional[int] = 1, reduction: ReductionType = 'sum', *, prior: Optional[List[float]] = None, label: Optional[str] = None, **kwargs): return ChosenInputs(get_fixed_value(label), reduction=reduction) def __init__(self, n_candidates: int, n_chosen: Optional[int] = 1, reduction: str = 'sum', *, prior: Optional[List[float]] = None, label: Optional[str] = None, **kwargs): super(InputChoice, self).__init__() if 'key' in kwargs: warnings.warn(f'"key" is deprecated. Assuming label.') label = kwargs['key'] if 'return_mask' in kwargs: warnings.warn(f'"return_mask" is deprecated. Ignoring...') if 'choose_from' in kwargs: warnings.warn(f'"reduction" is deprecated. Ignoring...') self.n_candidates = n_candidates self.n_chosen = n_chosen self.reduction = reduction self.prior = prior or [1 / n_candidates for _ in range(n_candidates)] assert self.reduction in ['mean', 'concat', 'sum', 'none'] self._label = generate_new_label(label) @property def key(self): return self._key() @torch.jit.ignore def _key(self): warnings.warn('Using key to access the identifier of InputChoice is deprecated. Please use label instead.', category=DeprecationWarning) return self._label @property def label(self): return self._label def forward(self, candidate_inputs: List[torch.Tensor]) -> torch.Tensor: warnings.warn('You should not run forward of this module directly.') return candidate_inputs[0] def __repr__(self): return f'InputChoice(n_candidates={self.n_candidates}, n_chosen={self.n_chosen}, ' \ f'reduction={repr(self.reduction)}, label={repr(self.label)})' class ChosenInputs(nn.Module): """ A module that chooses from a tensor list and outputs a reduced tensor. The already-chosen version of InputChoice. When forward, ``chosen`` will be used to select inputs from ``candidate_inputs``, and ``reduction`` will be used to choose from those inputs to form a tensor. Attributes ---------- chosen : list of int Indices of chosen inputs. reduction : ``mean`` | ``concat`` | ``sum`` | ``none`` How to reduce the inputs when multiple are selected. """ def __init__(self, chosen: Union[List[int], int], reduction: ReductionType): super().__init__() self.chosen = chosen if isinstance(chosen, list) else [chosen] self.reduction = reduction def forward(self, candidate_inputs): return self._tensor_reduction(self.reduction, [candidate_inputs[i] for i in self.chosen]) def _tensor_reduction(self, reduction_type, tensor_list): if reduction_type == 'none': return tensor_list if not tensor_list: return None # empty. return None for now if len(tensor_list) == 1: return tensor_list[0] if reduction_type == 'sum': return sum(tensor_list) if reduction_type == 'mean': return sum(tensor_list) / len(tensor_list) if reduction_type == 'concat': return torch.cat(tensor_list, dim=1) raise ValueError(f'Unrecognized reduction policy: "{reduction_type}"') # the code in ValueChoice can be generated with this codegen # this is not done online because I want to have type-hint supports # $ python -c "from nni.retiarii.nn.pytorch.api import _valuechoice_codegen; _valuechoice_codegen(_internal=True)" def _valuechoice_codegen(*, _internal: bool = False): if not _internal: raise RuntimeError("This method is set to be internal. Please don't use it directly.") MAPPING = { # unary 'neg': '-', 'pos': '+', 'invert': '~', # binary 'add': '+', 'sub': '-', 'mul': '*', 'matmul': '@', 'truediv': '//', 'floordiv': '/', 'mod': '%', 'lshift': '<<', 'rshift': '>>', 'and': '&', 'xor': '^', 'or': '|', # no reflection 'lt': '<', 'le': '<=', 'eq': '==', 'ne': '!=', 'ge': '>=', 'gt': '>', # NOTE # Currently we don't support operators like __contains__ (b in a), # Might support them in future when we actually need them. } binary_template = """ def __{op}__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.{opt}, '{{}} {sym} {{}}', [self, other])""" binary_r_template = """ def __r{op}__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.{opt}, '{{}} {sym} {{}}', [other, self])""" unary_template = """ def __{op}__(self) -> 'ValueChoiceX': return ValueChoiceX(operator.{op}, '{sym}{{}}', [self])""" for op, sym in MAPPING.items(): if op in ['neg', 'pos', 'invert']: print(unary_template.format(op=op, sym=sym) + '\n') else: opt = op + '_' if op in ['and', 'or'] else op print(binary_template.format(op=op, opt=opt, sym=sym) + '\n') if op not in ['lt', 'le', 'eq', 'ne', 'ge', 'gt']: print(binary_r_template.format(op=op, opt=opt, sym=sym) + '\n') def _valuechoice_staticmethod_helper(orig_func): orig_func.__doc__ += """ Notes ----- This function performs lazy evaluation. Only the expression will be recorded when the function is called. The real evaluation happens when the inner value choice has determined its final decision. If no value choice is contained in the parameter list, the evaluation will be intermediate.""" return orig_func class ValueChoiceX(Translatable): """Internal API. Implementation note: The transformed (X) version of value choice. It can be the result of composition (transformation) of one or several value choices. For example, .. code-block:: python nn.ValueChoice([1, 2]) + nn.ValueChoice([3, 4]) + 5 The instance of base class cannot be created directly. Instead, they should be only the result of transformation of value choice. Therefore, there is no need to implement ``create_fixed_module`` in this class, because, 1. For python-engine, value choice itself has create fixed module. Consequently, the transformation is born to be fixed. 2. For graph-engine, it uses evaluate to calculate the result. Potentially, we have to implement the evaluation logic in oneshot algorithms. I believe we can postpone the discussion till then. """ def __init__(self, function: Callable[..., Any], repr_template: str, arguments: List[Any], dry_run: bool = True): super().__init__() if function is None: # this case is a hack for ValueChoice subclass # it will reach here only because ``__init__`` in ``nn.Module`` is useful. return self.function = function self.repr_template = repr_template self.arguments = arguments assert any(isinstance(arg, ValueChoiceX) for arg in self.arguments) if dry_run: # for sanity check self.dry_run() def inner_choices(self) -> Iterable['ValueChoice']: """ Return an iterable of all leaf value choices. Useful for composition of value choices. No deduplication on labels. Mutators should take care. """ for arg in self.arguments: if isinstance(arg, ValueChoiceX): yield from arg.inner_choices() def dry_run(self) -> Any: """ Dry run the value choice to get one of its possible evaluation results. """ # values are not used return self._evaluate(iter([]), True) def evaluate(self, values: Iterable[Any]) -> Any: """ Evaluate the result of this group. ``values`` should in the same order of ``inner_choices()``. """ return self._evaluate(iter(values), False) def _evaluate(self, values: Iterable[Any], dry_run: bool = False) -> Any: # "values" iterates in the recursion eval_args = [] for arg in self.arguments: if isinstance(arg, ValueChoiceX): # recursive evaluation eval_args.append(arg._evaluate(values, dry_run)) # the recursion will stop when it hits a leaf node (value choice) # the implementation is in `ValueChoice` else: # constant value eval_args.append(arg) return self.function(*eval_args) def _translate(self): """ Try to behave like one of its candidates when used in ``basic_unit``. """ return self.dry_run() def __repr__(self): reprs = [] for arg in self.arguments: if isinstance(arg, ValueChoiceX) and not isinstance(arg, ValueChoice): reprs.append('(' + repr(arg) + ')') # add parenthesis for operator priority else: reprs.append(repr(arg)) return self.repr_template.format(*reprs) # the following are a series of methods to create "ValueChoiceX" # which is a transformed version of value choice # https://docs.python.org/3/reference/datamodel.html#special-method-names # Special operators that can be useful in place of built-in conditional operators. @staticmethod @_valuechoice_staticmethod_helper def to_int(obj: 'ValueChoiceOrAny') -> Union['ValueChoiceX', int]: """ Convert a ``ValueChoice`` to an integer. """ if isinstance(obj, ValueChoiceX): return ValueChoiceX(int, 'int({})', [obj]) return int(obj) @staticmethod @_valuechoice_staticmethod_helper def to_float(obj: 'ValueChoiceOrAny') -> Union['ValueChoiceX', float]: """ Convert a ``ValueChoice`` to a float. """ if isinstance(obj, ValueChoiceX): return ValueChoiceX(float, 'float({})', [obj]) return float(obj) @staticmethod @_valuechoice_staticmethod_helper def condition(pred: 'ValueChoiceOrAny', true: 'ValueChoiceOrAny', false: 'ValueChoiceOrAny') -> 'ValueChoiceOrAny': """ Return ``true`` if the predicate ``pred`` is true else ``false``. Examples -------- >>> ValueChoice.condition(ValueChoice([1, 2]) > ValueChoice([0, 3]), 2, 1) """ if any(isinstance(obj, ValueChoiceX) for obj in [pred, true, false]): return ValueChoiceX(lambda t, c, f: t if c else f, '{} if {} else {}', [true, pred, false]) return true if pred else false @staticmethod @_valuechoice_staticmethod_helper def max(arg0: Union[Iterable['ValueChoiceOrAny'], 'ValueChoiceOrAny'], *args: List['ValueChoiceOrAny']) -> 'ValueChoiceOrAny': """ Returns the maximum value from a list of value choices. The usage should be similar to Python's built-in value choices, where the parameters could be an iterable, or at least two arguments. """ if not args: return ValueChoiceX.max(*list(arg0)) lst = [arg0] + list(args) if any(isinstance(obj, ValueChoiceX) for obj in lst): return ValueChoiceX(max, 'max({})', lst) return max(lst) @staticmethod @_valuechoice_staticmethod_helper def min(arg0: Union[Iterable['ValueChoiceOrAny'], 'ValueChoiceOrAny'], *args: List['ValueChoiceOrAny']) -> 'ValueChoiceOrAny': """ Returns the minunum value from a list of value choices. The usage should be similar to Python's built-in value choices, where the parameters could be an iterable, or at least two arguments. """ if not args: return ValueChoiceX.min(*list(arg0)) lst = [arg0] + list(args) if any(isinstance(obj, ValueChoiceX) for obj in lst): return ValueChoiceX(min, 'min({})', lst) return min(lst) def __hash__(self): # this is required because we have implemented ``__eq__`` return id(self) # NOTE: # Write operations are not supported. Reasons follow: # - Semantics are not clear. It can be applied to "all" the inner candidates, or only the chosen one. # - Implementation effort is too huge. # As a result, inplace operators like +=, *=, magic methods like `__getattr__` are not included in this list. def __getitem__(self, key: Any) -> 'ValueChoiceX': return ValueChoiceX(lambda x, y: x[y], '{}[{}]', [self, key]) # region implement int, float, round, trunc, floor, ceil # because I believe sometimes we need them to calculate #channels # `__int__` and `__float__` are not supported because `__int__` is required to return int. def __round__(self, ndigits: Optional[Any] = None) -> 'ValueChoiceX': if ndigits is not None: return ValueChoiceX(round, 'round({}, {})', [self, ndigits]) return ValueChoiceX(round, 'round({})', [self]) def __trunc__(self) -> 'ValueChoiceX': raise RuntimeError("Try to use `ValueChoice.to_int()` instead of `math.trunc()` on value choices.") def __floor__(self) -> 'ValueChoiceX': return ValueChoiceX(math.floor, 'math.floor({})', [self]) def __ceil__(self) -> 'ValueChoiceX': return ValueChoiceX(math.ceil, 'math.ceil({})', [self]) def __index__(self) -> NoReturn: # https://docs.python.org/3/reference/datamodel.html#object.__index__ raise RuntimeError("`__index__` is not allowed on ValueChoice, which means you can't " "use int(), float(), complex(), range() on a ValueChoice.") def __bool__(self) -> NoReturn: raise RuntimeError('Cannot use bool() on ValueChoice. That means, using ValueChoice in a if-clause is illegal. ' 'Please try methods like `ValueChoice.max(a, b)` to see whether that meets your needs.') # endregion # region the following code is generated with codegen (see above) # Annotated with "region" because I want to collapse them in vscode def __neg__(self) -> 'ValueChoiceX': return ValueChoiceX(operator.neg, '-{}', [self]) def __pos__(self) -> 'ValueChoiceX': return ValueChoiceX(operator.pos, '+{}', [self]) def __invert__(self) -> 'ValueChoiceX': return ValueChoiceX(operator.invert, '~{}', [self]) def __add__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.add, '{} + {}', [self, other]) def __radd__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.add, '{} + {}', [other, self]) def __sub__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.sub, '{} - {}', [self, other]) def __rsub__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.sub, '{} - {}', [other, self]) def __mul__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.mul, '{} * {}', [self, other]) def __rmul__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.mul, '{} * {}', [other, self]) def __matmul__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.matmul, '{} @ {}', [self, other]) def __rmatmul__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.matmul, '{} @ {}', [other, self]) def __truediv__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.truediv, '{} // {}', [self, other]) def __rtruediv__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.truediv, '{} // {}', [other, self]) def __floordiv__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.floordiv, '{} / {}', [self, other]) def __rfloordiv__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.floordiv, '{} / {}', [other, self]) def __mod__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.mod, '{} % {}', [self, other]) def __rmod__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.mod, '{} % {}', [other, self]) def __lshift__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.lshift, '{} << {}', [self, other]) def __rlshift__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.lshift, '{} << {}', [other, self]) def __rshift__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.rshift, '{} >> {}', [self, other]) def __rrshift__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.rshift, '{} >> {}', [other, self]) def __and__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.and_, '{} & {}', [self, other]) def __rand__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.and_, '{} & {}', [other, self]) def __xor__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.xor, '{} ^ {}', [self, other]) def __rxor__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.xor, '{} ^ {}', [other, self]) def __or__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.or_, '{} | {}', [self, other]) def __ror__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.or_, '{} | {}', [other, self]) def __lt__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.lt, '{} < {}', [self, other]) def __le__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.le, '{} <= {}', [self, other]) def __eq__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.eq, '{} == {}', [self, other]) def __ne__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.ne, '{} != {}', [self, other]) def __ge__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.ge, '{} >= {}', [self, other]) def __gt__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.gt, '{} > {}', [self, other]) # endregion # __pow__, __divmod__, __abs__ are special ones. # Not easy to cover those cases with codegen. def __pow__(self, other: Any, modulo: Optional[Any] = None) -> 'ValueChoiceX': if modulo is not None: return ValueChoiceX(pow, 'pow({}, {}, {})', [self, other, modulo]) return ValueChoiceX(lambda a, b: a ** b, '{} ** {}', [self, other]) def __rpow__(self, other: Any, modulo: Optional[Any] = None) -> 'ValueChoiceX': if modulo is not None: return ValueChoiceX(pow, 'pow({}, {}, {})', [other, self, modulo]) return ValueChoiceX(lambda a, b: a ** b, '{} ** {}', [other, self]) def __divmod__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(divmod, 'divmod({}, {})', [self, other]) def __rdivmod__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(divmod, 'divmod({}, {})', [other, self]) def __abs__(self) -> 'ValueChoiceX': return ValueChoiceX(abs, 'abs({})', [self]) ValueChoiceOrAny = TypeVar('ValueChoiceOrAny', ValueChoiceX, Any) class ValueChoice(ValueChoiceX, Mutable): """ ValueChoice is to choose one from ``candidates``. In most use scenarios, ValueChoice should be passed to the init parameters of a serializable module. For example, .. code-block:: python class Net(nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv2d(3, nn.ValueChoice([32, 64]), kernel_size=nn.ValueChoice([3, 5, 7])) def forward(self, x): return self.conv(x) In case, you want to search a parameter that is used repeatedly, this is also possible by sharing the same value choice instance. (Sharing the label should have the same effect.) For example, .. code-block:: python class Net(nn.Module): def __init__(self): super().__init__() hidden_dim = nn.ValueChoice([128, 512]) self.fc = nn.Sequential( nn.Linear(64, hidden_dim), nn.Linear(hidden_dim, 10) ) # the following code has the same effect. # self.fc = nn.Sequential( # nn.Linear(64, nn.ValueChoice([128, 512], label='dim')), # nn.Linear(nn.ValueChoice([128, 512], label='dim'), 10) # ) def forward(self, x): return self.fc(x) Note that ValueChoice should be used directly. Transformations like ``nn.Linear(32, nn.ValueChoice([64, 128]) * 2)`` are not supported. Another common use case is to initialize the values to choose from in init and call the module in forward to get the chosen value. Usually, this is used to pass a mutable value to a functional API like ``torch.xxx`` or ``nn.functional.xxx```. For example, .. code-block:: python class Net(nn.Module): def __init__(self): super().__init__() self.dropout_rate = nn.ValueChoice([0., 1.]) def forward(self, x): return F.dropout(x, self.dropout_rate()) Parameters ---------- candidates : list List of values to choose from. prior : list of float Prior distribution to sample from. label : str Identifier of the value choice. """ # FIXME: prior is designed but not supported yet @classmethod def create_fixed_module(cls, candidates: List[Any], *, label: Optional[str] = None, **kwargs): value = get_fixed_value(label) if value not in candidates: raise ValueError(f'Value {value} does not belong to the candidates: {candidates}.') return value def __init__(self, candidates: List[Any], *, prior: Optional[List[float]] = None, label: Optional[str] = None): super().__init__(None, None, None) self.candidates = candidates self.prior = prior or [1 / len(candidates) for _ in range(len(candidates))] assert abs(sum(self.prior) - 1) < 1e-5, 'Sum of prior distribution is not 1.' self._label = generate_new_label(label) self._accessor = [] @property def label(self): return self._label def forward(self): warnings.warn('You should not run forward of this module directly.') return self.candidates[0] def inner_choices(self) -> Iterable['ValueChoice']: # yield self because self is the only value choice here yield self def dry_run(self) -> Any: return self.candidates[0] def _evaluate(self, values: Iterable[Any], dry_run: bool = False) -> Any: if dry_run: return self.candidates[0] try: value = next(values) except StopIteration: raise ValueError(f'Value list {values} is exhausted when trying to get a chosen value of {self}.') if value not in self.candidates: raise ValueError(f'Value {value} does not belong to the candidates of {self}.') return value def __repr__(self): return f'ValueChoice({self.candidates}, label={repr(self.label)})' @basic_unit class Placeholder(nn.Module): """ The API that creates an empty module for later mutations. For advanced usages only. """ def __init__(self, label, **related_info): self.label = label self.related_info = related_info super().__init__() def forward(self, x): return x
39.107098
134
0.613158
import math import operator import warnings from typing import Any, List, Union, Dict, Optional, Callable, Iterable, NoReturn, TypeVar import torch import torch.nn as nn from nni.common.serializer import Translatable from nni.retiarii.serializer import basic_unit from nni.retiarii.utils import STATE_DICT_PY_MAPPING_PARTIAL from .utils import Mutable, generate_new_label, get_fixed_value __all__ = ['LayerChoice', 'InputChoice', 'ValueChoice', 'Placeholder', 'ChosenInputs'] class LayerChoice(Mutable): @classmethod def create_fixed_module(cls, candidates: Union[Dict[str, nn.Module], List[nn.Module]], *, label: Optional[str] = None, **kwargs): chosen = get_fixed_value(label) if isinstance(candidates, list): result = candidates[int(chosen)] else: result = candidates[chosen] if hasattr(result, STATE_DICT_PY_MAPPING_PARTIAL): prev_mapping = getattr(result, STATE_DICT_PY_MAPPING_PARTIAL) setattr(result, STATE_DICT_PY_MAPPING_PARTIAL, {k: f'{chosen}.{v}' for k, v in prev_mapping.items()}) else: setattr(result, STATE_DICT_PY_MAPPING_PARTIAL, {'__self__': str(chosen)}) return result def __init__(self, candidates: Union[Dict[str, nn.Module], List[nn.Module]], *, prior: Optional[List[float]] = None, label: Optional[str] = None, **kwargs): super(LayerChoice, self).__init__() if 'key' in kwargs: warnings.warn(f'"key" is deprecated. Assuming label.') label = kwargs['key'] if 'return_mask' in kwargs: warnings.warn(f'"return_mask" is deprecated. Ignoring...') if 'reduction' in kwargs: warnings.warn(f'"reduction" is deprecated. Ignoring...') self.candidates = candidates self.prior = prior or [1 / len(candidates) for _ in range(len(candidates))] assert abs(sum(self.prior) - 1) < 1e-5, 'Sum of prior distribution is not 1.' self._label = generate_new_label(label) self.names = [] if isinstance(candidates, dict): for name, module in candidates.items(): assert name not in ["length", "reduction", "return_mask", "_key", "key", "names"], \ "Please don't use a reserved name '{}' for your module.".format(name) self.add_module(name, module) self.names.append(name) elif isinstance(candidates, list): for i, module in enumerate(candidates): self.add_module(str(i), module) self.names.append(str(i)) else: raise TypeError("Unsupported candidates type: {}".format(type(candidates))) self._first_module = self._modules[self.names[0]] @property def key(self): return self._key() @torch.jit.ignore def _key(self): warnings.warn('Using key to access the identifier of LayerChoice is deprecated. Please use label instead.', category=DeprecationWarning) return self._label @property def label(self): return self._label def __getitem__(self, idx): if isinstance(idx, str): return self._modules[idx] return list(self)[idx] def __setitem__(self, idx, module): key = idx if isinstance(idx, str) else self.names[idx] return setattr(self, key, module) def __delitem__(self, idx): if isinstance(idx, slice): for key in self.names[idx]: delattr(self, key) else: if isinstance(idx, str): key, idx = idx, self.names.index(idx) else: key = self.names[idx] delattr(self, key) del self.names[idx] def __len__(self): return len(self.names) def __iter__(self): return map(lambda name: self._modules[name], self.names) @property def choices(self): return self._choices() @torch.jit.ignore def _choices(self): warnings.warn("layer_choice.choices is deprecated. Use `list(layer_choice)` instead.", category=DeprecationWarning) return list(self) def forward(self, x): warnings.warn('You should not run forward of this module directly.') return self._first_module(x) def __repr__(self): return f'LayerChoice({self.candidates}, label={repr(self.label)})' try: from typing import Literal except ImportError: from typing_extensions import Literal ReductionType = Literal['mean', 'concat', 'sum', 'none'] class InputChoice(Mutable): @classmethod def create_fixed_module(cls, n_candidates: int, n_chosen: Optional[int] = 1, reduction: ReductionType = 'sum', *, prior: Optional[List[float]] = None, label: Optional[str] = None, **kwargs): return ChosenInputs(get_fixed_value(label), reduction=reduction) def __init__(self, n_candidates: int, n_chosen: Optional[int] = 1, reduction: str = 'sum', *, prior: Optional[List[float]] = None, label: Optional[str] = None, **kwargs): super(InputChoice, self).__init__() if 'key' in kwargs: warnings.warn(f'"key" is deprecated. Assuming label.') label = kwargs['key'] if 'return_mask' in kwargs: warnings.warn(f'"return_mask" is deprecated. Ignoring...') if 'choose_from' in kwargs: warnings.warn(f'"reduction" is deprecated. Ignoring...') self.n_candidates = n_candidates self.n_chosen = n_chosen self.reduction = reduction self.prior = prior or [1 / n_candidates for _ in range(n_candidates)] assert self.reduction in ['mean', 'concat', 'sum', 'none'] self._label = generate_new_label(label) @property def key(self): return self._key() @torch.jit.ignore def _key(self): warnings.warn('Using key to access the identifier of InputChoice is deprecated. Please use label instead.', category=DeprecationWarning) return self._label @property def label(self): return self._label def forward(self, candidate_inputs: List[torch.Tensor]) -> torch.Tensor: warnings.warn('You should not run forward of this module directly.') return candidate_inputs[0] def __repr__(self): return f'InputChoice(n_candidates={self.n_candidates}, n_chosen={self.n_chosen}, ' \ f'reduction={repr(self.reduction)}, label={repr(self.label)})' class ChosenInputs(nn.Module): def __init__(self, chosen: Union[List[int], int], reduction: ReductionType): super().__init__() self.chosen = chosen if isinstance(chosen, list) else [chosen] self.reduction = reduction def forward(self, candidate_inputs): return self._tensor_reduction(self.reduction, [candidate_inputs[i] for i in self.chosen]) def _tensor_reduction(self, reduction_type, tensor_list): if reduction_type == 'none': return tensor_list if not tensor_list: return None if len(tensor_list) == 1: return tensor_list[0] if reduction_type == 'sum': return sum(tensor_list) if reduction_type == 'mean': return sum(tensor_list) / len(tensor_list) if reduction_type == 'concat': return torch.cat(tensor_list, dim=1) raise ValueError(f'Unrecognized reduction policy: "{reduction_type}"') def _valuechoice_codegen(*, _internal: bool = False): if not _internal: raise RuntimeError("This method is set to be internal. Please don't use it directly.") MAPPING = { # unary 'neg': '-', 'pos': '+', 'invert': '~', # binary 'add': '+', 'sub': '-', 'mul': '*', 'matmul': '@', 'truediv': '//', 'floordiv': '/', 'mod': '%', 'lshift': '<<', 'rshift': '>>', 'and': '&', 'xor': '^', 'or': '|', # no reflection 'lt': '<', 'le': '<=', 'eq': '==', 'ne': '!=', 'ge': '>=', 'gt': '>', # NOTE # Currently we don't support operators like __contains__ (b in a), } binary_template = """ def __{op}__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.{opt}, '{{}} {sym} {{}}', [self, other])""" binary_r_template = """ def __r{op}__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.{opt}, '{{}} {sym} {{}}', [other, self])""" unary_template = """ def __{op}__(self) -> 'ValueChoiceX': return ValueChoiceX(operator.{op}, '{sym}{{}}', [self])""" for op, sym in MAPPING.items(): if op in ['neg', 'pos', 'invert']: print(unary_template.format(op=op, sym=sym) + '\n') else: opt = op + '_' if op in ['and', 'or'] else op print(binary_template.format(op=op, opt=opt, sym=sym) + '\n') if op not in ['lt', 'le', 'eq', 'ne', 'ge', 'gt']: print(binary_r_template.format(op=op, opt=opt, sym=sym) + '\n') def _valuechoice_staticmethod_helper(orig_func): orig_func.__doc__ += """ Notes ----- This function performs lazy evaluation. Only the expression will be recorded when the function is called. The real evaluation happens when the inner value choice has determined its final decision. If no value choice is contained in the parameter list, the evaluation will be intermediate.""" return orig_func class ValueChoiceX(Translatable): def __init__(self, function: Callable[..., Any], repr_template: str, arguments: List[Any], dry_run: bool = True): super().__init__() if function is None: return self.function = function self.repr_template = repr_template self.arguments = arguments assert any(isinstance(arg, ValueChoiceX) for arg in self.arguments) if dry_run: self.dry_run() def inner_choices(self) -> Iterable['ValueChoice']: for arg in self.arguments: if isinstance(arg, ValueChoiceX): yield from arg.inner_choices() def dry_run(self) -> Any: return self._evaluate(iter([]), True) def evaluate(self, values: Iterable[Any]) -> Any: return self._evaluate(iter(values), False) def _evaluate(self, values: Iterable[Any], dry_run: bool = False) -> Any: eval_args = [] for arg in self.arguments: if isinstance(arg, ValueChoiceX): eval_args.append(arg._evaluate(values, dry_run)) else: eval_args.append(arg) return self.function(*eval_args) def _translate(self): return self.dry_run() def __repr__(self): reprs = [] for arg in self.arguments: if isinstance(arg, ValueChoiceX) and not isinstance(arg, ValueChoice): reprs.append('(' + repr(arg) + ')') else: reprs.append(repr(arg)) return self.repr_template.format(*reprs) hod @_valuechoice_staticmethod_helper def to_int(obj: 'ValueChoiceOrAny') -> Union['ValueChoiceX', int]: if isinstance(obj, ValueChoiceX): return ValueChoiceX(int, 'int({})', [obj]) return int(obj) @staticmethod @_valuechoice_staticmethod_helper def to_float(obj: 'ValueChoiceOrAny') -> Union['ValueChoiceX', float]: if isinstance(obj, ValueChoiceX): return ValueChoiceX(float, 'float({})', [obj]) return float(obj) @staticmethod @_valuechoice_staticmethod_helper def condition(pred: 'ValueChoiceOrAny', true: 'ValueChoiceOrAny', false: 'ValueChoiceOrAny') -> 'ValueChoiceOrAny': if any(isinstance(obj, ValueChoiceX) for obj in [pred, true, false]): return ValueChoiceX(lambda t, c, f: t if c else f, '{} if {} else {}', [true, pred, false]) return true if pred else false @staticmethod @_valuechoice_staticmethod_helper def max(arg0: Union[Iterable['ValueChoiceOrAny'], 'ValueChoiceOrAny'], *args: List['ValueChoiceOrAny']) -> 'ValueChoiceOrAny': if not args: return ValueChoiceX.max(*list(arg0)) lst = [arg0] + list(args) if any(isinstance(obj, ValueChoiceX) for obj in lst): return ValueChoiceX(max, 'max({})', lst) return max(lst) @staticmethod @_valuechoice_staticmethod_helper def min(arg0: Union[Iterable['ValueChoiceOrAny'], 'ValueChoiceOrAny'], *args: List['ValueChoiceOrAny']) -> 'ValueChoiceOrAny': if not args: return ValueChoiceX.min(*list(arg0)) lst = [arg0] + list(args) if any(isinstance(obj, ValueChoiceX) for obj in lst): return ValueChoiceX(min, 'min({})', lst) return min(lst) def __hash__(self): return id(self) def __getitem__(self, key: Any) -> 'ValueChoiceX': return ValueChoiceX(lambda x, y: x[y], '{}[{}]', [self, key]) def __round__(self, ndigits: Optional[Any] = None) -> 'ValueChoiceX': if ndigits is not None: return ValueChoiceX(round, 'round({}, {})', [self, ndigits]) return ValueChoiceX(round, 'round({})', [self]) def __trunc__(self) -> 'ValueChoiceX': raise RuntimeError("Try to use `ValueChoice.to_int()` instead of `math.trunc()` on value choices.") def __floor__(self) -> 'ValueChoiceX': return ValueChoiceX(math.floor, 'math.floor({})', [self]) def __ceil__(self) -> 'ValueChoiceX': return ValueChoiceX(math.ceil, 'math.ceil({})', [self]) def __index__(self) -> NoReturn: ntimeError("`__index__` is not allowed on ValueChoice, which means you can't " "use int(), float(), complex(), range() on a ValueChoice.") def __bool__(self) -> NoReturn: raise RuntimeError('Cannot use bool() on ValueChoice. That means, using ValueChoice in a if-clause is illegal. ' 'Please try methods like `ValueChoice.max(a, b)` to see whether that meets your needs.') # endregion # region the following code is generated with codegen (see above) # Annotated with "region" because I want to collapse them in vscode def __neg__(self) -> 'ValueChoiceX': return ValueChoiceX(operator.neg, '-{}', [self]) def __pos__(self) -> 'ValueChoiceX': return ValueChoiceX(operator.pos, '+{}', [self]) def __invert__(self) -> 'ValueChoiceX': return ValueChoiceX(operator.invert, '~{}', [self]) def __add__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.add, '{} + {}', [self, other]) def __radd__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.add, '{} + {}', [other, self]) def __sub__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.sub, '{} - {}', [self, other]) def __rsub__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.sub, '{} - {}', [other, self]) def __mul__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.mul, '{} * {}', [self, other]) def __rmul__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.mul, '{} * {}', [other, self]) def __matmul__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.matmul, '{} @ {}', [self, other]) def __rmatmul__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.matmul, '{} @ {}', [other, self]) def __truediv__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.truediv, '{} // {}', [self, other]) def __rtruediv__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.truediv, '{} // {}', [other, self]) def __floordiv__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.floordiv, '{} / {}', [self, other]) def __rfloordiv__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.floordiv, '{} / {}', [other, self]) def __mod__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.mod, '{} % {}', [self, other]) def __rmod__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.mod, '{} % {}', [other, self]) def __lshift__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.lshift, '{} << {}', [self, other]) def __rlshift__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.lshift, '{} << {}', [other, self]) def __rshift__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.rshift, '{} >> {}', [self, other]) def __rrshift__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.rshift, '{} >> {}', [other, self]) def __and__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.and_, '{} & {}', [self, other]) def __rand__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.and_, '{} & {}', [other, self]) def __xor__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.xor, '{} ^ {}', [self, other]) def __rxor__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.xor, '{} ^ {}', [other, self]) def __or__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.or_, '{} | {}', [self, other]) def __ror__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.or_, '{} | {}', [other, self]) def __lt__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.lt, '{} < {}', [self, other]) def __le__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.le, '{} <= {}', [self, other]) def __eq__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.eq, '{} == {}', [self, other]) def __ne__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.ne, '{} != {}', [self, other]) def __ge__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.ge, '{} >= {}', [self, other]) def __gt__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(operator.gt, '{} > {}', [self, other]) # endregion # __pow__, __divmod__, __abs__ are special ones. # Not easy to cover those cases with codegen. def __pow__(self, other: Any, modulo: Optional[Any] = None) -> 'ValueChoiceX': if modulo is not None: return ValueChoiceX(pow, 'pow({}, {}, {})', [self, other, modulo]) return ValueChoiceX(lambda a, b: a ** b, '{} ** {}', [self, other]) def __rpow__(self, other: Any, modulo: Optional[Any] = None) -> 'ValueChoiceX': if modulo is not None: return ValueChoiceX(pow, 'pow({}, {}, {})', [other, self, modulo]) return ValueChoiceX(lambda a, b: a ** b, '{} ** {}', [other, self]) def __divmod__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(divmod, 'divmod({}, {})', [self, other]) def __rdivmod__(self, other: Any) -> 'ValueChoiceX': return ValueChoiceX(divmod, 'divmod({}, {})', [other, self]) def __abs__(self) -> 'ValueChoiceX': return ValueChoiceX(abs, 'abs({})', [self]) ValueChoiceOrAny = TypeVar('ValueChoiceOrAny', ValueChoiceX, Any) class ValueChoice(ValueChoiceX, Mutable): # FIXME: prior is designed but not supported yet @classmethod def create_fixed_module(cls, candidates: List[Any], *, label: Optional[str] = None, **kwargs): value = get_fixed_value(label) if value not in candidates: raise ValueError(f'Value {value} does not belong to the candidates: {candidates}.') return value def __init__(self, candidates: List[Any], *, prior: Optional[List[float]] = None, label: Optional[str] = None): super().__init__(None, None, None) self.candidates = candidates self.prior = prior or [1 / len(candidates) for _ in range(len(candidates))] assert abs(sum(self.prior) - 1) < 1e-5, 'Sum of prior distribution is not 1.' self._label = generate_new_label(label) self._accessor = [] @property def label(self): return self._label def forward(self): warnings.warn('You should not run forward of this module directly.') return self.candidates[0] def inner_choices(self) -> Iterable['ValueChoice']: # yield self because self is the only value choice here yield self def dry_run(self) -> Any: return self.candidates[0] def _evaluate(self, values: Iterable[Any], dry_run: bool = False) -> Any: if dry_run: return self.candidates[0] try: value = next(values) except StopIteration: raise ValueError(f'Value list {values} is exhausted when trying to get a chosen value of {self}.') if value not in self.candidates: raise ValueError(f'Value {value} does not belong to the candidates of {self}.') return value def __repr__(self): return f'ValueChoice({self.candidates}, label={repr(self.label)})' @basic_unit class Placeholder(nn.Module): def __init__(self, label, **related_info): self.label = label self.related_info = related_info super().__init__() def forward(self, x): return x
true
true
f711203454b2f2654e8b0af1e775e99c49b81bcf
3,176
py
Python
examples/tutorial/tutorial/spiders/rotate_useragent.py
cjymz886/crawl_examples
f8c7d31f60a4df512f83a397491b4ec498a23289
[ "MIT" ]
3
2018-02-11T16:58:48.000Z
2019-11-28T08:33:54.000Z
examples/tutorial/tutorial/spiders/rotate_useragent.py
cjymz886/crawl_examples
f8c7d31f60a4df512f83a397491b4ec498a23289
[ "MIT" ]
null
null
null
examples/tutorial/tutorial/spiders/rotate_useragent.py
cjymz886/crawl_examples
f8c7d31f60a4df512f83a397491b4ec498a23289
[ "MIT" ]
null
null
null
# -*-coding:utf-8-*- import logging """避免被ban策略之一:使用useragent池。 使用注意:需在settings.py中进行相应的设置。 """ import random from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware class RotateUserAgentMiddleware(UserAgentMiddleware): def __init__(self, user_agent=''): self.user_agent = user_agent def process_request(self, request, spider): ua = random.choice(self.user_agent_list) if ua: #显示当前使用的useragent #print "********Current UserAgent:%s************" %ua #记录 logging.log(msg='Current UserAgent: ' + ua, level=logging.DEBUG) request.headers.setdefault('User-Agent', ua) #the default user_agent_list composes chrome,I E,firefox,Mozilla,opera,netscape #for more user agent strings,you can find it in http://www.useragentstring.com/pages/useragentstring.php user_agent_list = [ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 ", "(KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 ", "(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 ", "(KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 ", "(KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1", "(KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5", "(KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5", "(KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24", "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24", "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", ]
47.402985
108
0.627834
import logging import random from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware class RotateUserAgentMiddleware(UserAgentMiddleware): def __init__(self, user_agent=''): self.user_agent = user_agent def process_request(self, request, spider): ua = random.choice(self.user_agent_list) if ua: logging.log(msg='Current UserAgent: ' + ua, level=logging.DEBUG) request.headers.setdefault('User-Agent', ua) user_agent_list = [ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 ", "(KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 ", "(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 ", "(KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 ", "(KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1", "(KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5", "(KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5", "(KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3", "(KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24", "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24", "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", ]
true
true