hexsha
stringlengths
40
40
size
int64
3
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
972
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
78
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
3
972
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
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
3
972
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
78
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
3
1.03M
avg_line_length
float64
1.13
941k
max_line_length
int64
2
941k
alphanum_fraction
float64
0
1
d7c6c7b4aecd7b5e5e03ecbf705e1cd1df022fe7
4,036
py
Python
tests/basics/Branching.py
Mortal/Nuitka
5150eeff7ff845ed4993c773449cd81b7f127c6b
[ "Apache-2.0" ]
null
null
null
tests/basics/Branching.py
Mortal/Nuitka
5150eeff7ff845ed4993c773449cd81b7f127c6b
[ "Apache-2.0" ]
null
null
null
tests/basics/Branching.py
Mortal/Nuitka
5150eeff7ff845ed4993c773449cd81b7f127c6b
[ "Apache-2.0" ]
1
2018-12-16T23:51:18.000Z
2018-12-16T23:51:18.000Z
# Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com # # Python tests originally created or extracted from other peoples work. The # parts were too small to be protected. # # 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. # """ Some random branching to cover most common cases. """ from __future__ import print_function def branchingFunction(a, b, c): print("branchingFunction:", a, b, c) print("a or b", a or b) print("a and b", a and b) print("not a", not a) print("not b", not b) print("Simple branch with both branches") if a: l = "YES" else: l = "NO" print(a, "->", l) print("Simple not branch with both branches") if not a: l = "YES" else: l = "NO" print(not a, "->", l) print("Simple branch with a nested branch in else path:") if a: m = "yes" else: if True: m = "no" print(a, "->", m) print("Triple 'and' chain:") v = "NO" if a and b and c: v = "YES" print(a, b, c, "->", v) print("Triple or chain:") k = "NO" if a or b or c: k = "YES" print(a, b, c, "->", k) print("Nested 'if not' chain:") p = "NO" if not a: if not b: p = "YES" print("not a, not b", not a, not b, "->", p) print("or condition in braces:") q = "NO" if (a or b): q = "YES" print("(a or b) ->", q) print("Braced if not with two 'or'") if not (a or b or c): q = "YES" else: q = "NO" print("not (a or b or c)", q) print("Braced if not with one 'or'") q = "NO" if not (b or b): q = "YES" print("not (b or b)", q) print("Expression a or b", a or b) print("Expression not(a or b)", not(a or b)) print("Expression a and (b+5)", a and (b+5)) print("Expression (b if b else 2)", (b if b else 2)) print("Expression (a and (b if b else 2))", (a and (b if b else 2))) print("Braced if not chain with 'and' and conditional expression:") if not (a and (b if b else 2)): print("oki") print("Nested if chain with outer else:") d=1 if a: if b or c: if d: print("inside nest") else: print("outer else") print("Complex conditional expression:") v = (3 if a-1 else 0) or \ (b or (c*2 if c else 6) if b-1 else a and b and c) print(v) if True: print("Predictable branch taken") branchingFunction(1,0,3) x = 3 def optimizationVictim(): if x: pass else: pass if x: pass pass optimizationVictim() def dontOptimizeSideEffects(): print("Lets see, if conditional expression in known true values are correctly handled:") def returnTrue(): print("function 'returnTrue' was called as expected") return True def returnFalse(): print("function 'returnFalse' should not have beeen called") return False if (returnTrue() or returnFalse(),): print("Taken branch as expected.") else: print("Bad branch taken.") dontOptimizeSideEffects() def dontOptimizeTruthCheck(): class A: def __nonzero__(self): raise ValueError __bool__ = __nonzero__ a = A() if a: pass try: print("Check that branch conditions are not optimized way: ", end = "") dontOptimizeTruthCheck() print("FAIL.") except ValueError: print("OK.")
21.698925
92
0.563677
147ac3c79758847718ccf4809b924d665aab2263
2,273
py
Python
app/views/users/messages/views.py
FundingCircle/DjanGoat
013c7367294682955daf9eba205270bd2f9725cd
[ "MIT" ]
1
2019-05-07T09:49:25.000Z
2019-05-07T09:49:25.000Z
app/views/users/messages/views.py
FundingCircle/DjanGoat
013c7367294682955daf9eba205270bd2f9725cd
[ "MIT" ]
null
null
null
app/views/users/messages/views.py
FundingCircle/DjanGoat
013c7367294682955daf9eba205270bd2f9725cd
[ "MIT" ]
null
null
null
from django.http import HttpResponse from django.contrib import messages from django.views.decorators.http import require_http_methods from django.shortcuts import render, redirect from django.utils import timezone from app.decorators import user_is_authenticated from app.models import User, Message from app.views import utils @require_http_methods(["GET", "POST"]) @user_is_authenticated def user_messages(request, user_id): # pylint: disable=unused-argument current_user = utils.current_user(request) if request.method == "GET": return render(request, "users/messages/index.html", { 'current_user': current_user, 'available_recipients': User.objects.all() }) else: try: cid = int(request.POST['creator_id']) creator = User.objects.get(user_id=cid) rid = int(request.POST['receiver_id']) receiver = User.objects.get(user_id=rid) msg = request.POST['message'] red = int(request.POST['read']) now = timezone.now() Message.objects.create(creator=creator, receiver=receiver, message=msg, read=red, created_at=now, updated_at=now) return redirect("/users/" + str(current_user.id) + "/messages") except Exception as e: messages.add_message(request, messages.INFO, str(e)) return render(request, "users/messages/index.html", { 'current_user': current_user, 'available_receipients': User.objects.all() }) # W0613 = unused-argument @require_http_methods(["GET", "DELETE"]) @user_is_authenticated def user_message(request, user_id, message_id): # pylint: disable=W0613 current_user = utils.current_user(request) try: message = Message.objects.get(pk=message_id) if request.method == "GET": return render(request, "users/messages/show.html", { 'current_user': current_user, 'message': message }) else: message.delete() return HttpResponse("Success!") except Exception: return redirect("/users/" + str(current_user.id) + "/messages")
36.66129
75
0.623405
379721dc94f9a66eaa9247b10c7c63220f02bf26
222
py
Python
setup.py
stuartasims/paycheck_protection_program_eda
cf290e0b10e6a72e43d764c47a128676875ca2e4
[ "FTL" ]
null
null
null
setup.py
stuartasims/paycheck_protection_program_eda
cf290e0b10e6a72e43d764c47a128676875ca2e4
[ "FTL" ]
null
null
null
setup.py
stuartasims/paycheck_protection_program_eda
cf290e0b10e6a72e43d764c47a128676875ca2e4
[ "FTL" ]
null
null
null
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Digging into the released ppp loan data', author='Stuart Sims', license='', )
20.181818
58
0.666667
3130006a91058eaa56b7ac8ea4fcaa305be259e4
780
py
Python
virl/cli/definitions/images/ls/commands.py
ttafsir/virlutils
5cb0e5410023b30d49515be5e3cb731dbd6cbeef
[ "MIT" ]
null
null
null
virl/cli/definitions/images/ls/commands.py
ttafsir/virlutils
5cb0e5410023b30d49515be5e3cb731dbd6cbeef
[ "MIT" ]
null
null
null
virl/cli/definitions/images/ls/commands.py
ttafsir/virlutils
5cb0e5410023b30d49515be5e3cb731dbd6cbeef
[ "MIT" ]
null
null
null
import click from virl.api import VIRLServer from virl.cli.views import image_list_table from virl.helpers import get_cml_client @click.command() @click.option("--image", default=None) def ls(**kwargs): """ list all images or the details of a specific image """ image = kwargs.get("image") server = VIRLServer() client = get_cml_client(server) # Regardless of the argument, we have to get all the flavors # In the case of no arg, we print them all. # In the case of an arg, we have to go back and get details. defs = client.definitions.image_definitions() if image: for f in list(defs): if f["name"] == image: image_list_table([f]) break else: image_list_table(defs)
26
64
0.641026
e15554737b9f3fa36382dde15ded928271679538
7,564
py
Python
python/paddle/fluid/tests/unittests/test_prior_box_op.py
jerrywgz/Paddle
85c4912755b783dd7554a9d6b9dae4a7e40371bc
[ "Apache-2.0" ]
1
2018-08-03T03:33:52.000Z
2018-08-03T03:33:52.000Z
python/paddle/fluid/tests/unittests/test_prior_box_op.py
jerrywgz/Paddle
85c4912755b783dd7554a9d6b9dae4a7e40371bc
[ "Apache-2.0" ]
3
2017-07-15T14:20:08.000Z
2019-05-06T03:16:54.000Z
python/paddle/fluid/tests/unittests/test_prior_box_op.py
jerrywgz/Paddle
85c4912755b783dd7554a9d6b9dae4a7e40371bc
[ "Apache-2.0" ]
1
2018-07-20T07:13:31.000Z
2018-07-20T07:13:31.000Z
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import numpy as np import sys import math from op_test import OpTest class TestPriorBoxOp(OpTest): def set_data(self): self.init_test_params() self.init_test_input() self.init_test_output() self.inputs = {'Input': self.input, 'Image': self.image} self.attrs = { 'min_sizes': self.min_sizes, 'aspect_ratios': self.aspect_ratios, 'variances': self.variances, 'flip': self.flip, 'clip': self.clip, 'min_max_aspect_ratios_order': self.min_max_aspect_ratios_order, 'step_w': self.step_w, 'step_h': self.step_h, 'offset': self.offset } if len(self.max_sizes) > 0: self.attrs['max_sizes'] = self.max_sizes self.outputs = {'Boxes': self.out_boxes, 'Variances': self.out_var} def test_check_output(self): self.check_output() def setUp(self): self.op_type = "prior_box" self.set_data() def set_max_sizes(self): max_sizes = [5, 10] self.max_sizes = np.array(max_sizes).astype('float32').tolist() def set_min_max_aspect_ratios_order(self): self.min_max_aspect_ratios_order = False def init_test_params(self): self.layer_w = 32 self.layer_h = 32 self.image_w = 40 self.image_h = 40 self.step_w = float(self.image_w) / float(self.layer_w) self.step_h = float(self.image_h) / float(self.layer_h) self.input_channels = 2 self.image_channels = 3 self.batch_size = 10 self.min_sizes = [2, 4] self.min_sizes = np.array(self.min_sizes).astype('float32').tolist() self.set_max_sizes() self.aspect_ratios = [2.0, 3.0] self.flip = True self.set_min_max_aspect_ratios_order() self.real_aspect_ratios = [1, 2.0, 1.0 / 2.0, 3.0, 1.0 / 3.0] self.aspect_ratios = np.array( self.aspect_ratios, dtype=np.float).flatten() self.variances = [0.1, 0.1, 0.2, 0.2] self.variances = np.array(self.variances, dtype=np.float).flatten() self.clip = True self.num_priors = len(self.real_aspect_ratios) * len(self.min_sizes) if len(self.max_sizes) > 0: self.num_priors += len(self.max_sizes) self.offset = 0.5 def init_test_input(self): self.image = np.random.random( (self.batch_size, self.image_channels, self.image_w, self.image_h)).astype('float32') self.input = np.random.random( (self.batch_size, self.input_channels, self.layer_w, self.layer_h)).astype('float32') def init_test_output(self): out_dim = (self.layer_h, self.layer_w, self.num_priors, 4) out_boxes = np.zeros(out_dim).astype('float32') out_var = np.zeros(out_dim).astype('float32') idx = 0 for h in range(self.layer_h): for w in range(self.layer_w): c_x = (w + self.offset) * self.step_w c_y = (h + self.offset) * self.step_h idx = 0 for s in range(len(self.min_sizes)): min_size = self.min_sizes[s] if not self.min_max_aspect_ratios_order: # rest of priors for r in range(len(self.real_aspect_ratios)): ar = self.real_aspect_ratios[r] c_w = min_size * math.sqrt(ar) / 2 c_h = (min_size / math.sqrt(ar)) / 2 out_boxes[h, w, idx, :] = [ (c_x - c_w) / self.image_w, (c_y - c_h) / self.image_h, (c_x + c_w) / self.image_w, (c_y + c_h) / self.image_h ] idx += 1 if len(self.max_sizes) > 0: max_size = self.max_sizes[s] # second prior: aspect_ratio = 1, c_w = c_h = math.sqrt(min_size * max_size) / 2 out_boxes[h, w, idx, :] = [ (c_x - c_w) / self.image_w, (c_y - c_h) / self.image_h, (c_x + c_w) / self.image_w, (c_y + c_h) / self.image_h ] idx += 1 else: c_w = c_h = min_size / 2. out_boxes[h, w, idx, :] = [(c_x - c_w) / self.image_w, (c_y - c_h) / self.image_h, (c_x + c_w) / self.image_w, (c_y + c_h) / self.image_h] idx += 1 if len(self.max_sizes) > 0: max_size = self.max_sizes[s] # second prior: aspect_ratio = 1, c_w = c_h = math.sqrt(min_size * max_size) / 2 out_boxes[h, w, idx, :] = [ (c_x - c_w) / self.image_w, (c_y - c_h) / self.image_h, (c_x + c_w) / self.image_w, (c_y + c_h) / self.image_h ] idx += 1 # rest of priors for r in range(len(self.real_aspect_ratios)): ar = self.real_aspect_ratios[r] if abs(ar - 1.) < 1e-6: continue c_w = min_size * math.sqrt(ar) / 2 c_h = (min_size / math.sqrt(ar)) / 2 out_boxes[h, w, idx, :] = [ (c_x - c_w) / self.image_w, (c_y - c_h) / self.image_h, (c_x + c_w) / self.image_w, (c_y + c_h) / self.image_h ] idx += 1 # clip the prior's coordidate such that it is within[0, 1] if self.clip: out_boxes = np.clip(out_boxes, 0.0, 1.0) # set the variance. out_var = np.tile(self.variances, (self.layer_h, self.layer_w, self.num_priors, 1)) self.out_boxes = out_boxes.astype('float32') self.out_var = out_var.astype('float32') class TestPriorBoxOpWithoutMaxSize(TestPriorBoxOp): def set_max_sizes(self): self.max_sizes = [] class TestPriorBoxOpWithSpecifiedOutOrder(TestPriorBoxOp): def set_min_max_aspect_ratios_order(self): self.min_max_aspect_ratios_order = True if __name__ == '__main__': unittest.main()
39.810526
78
0.49762
7101cbfbbec4818d3c2c0a998f8d9ae677e3cf5b
1,845
py
Python
setup.py
waltherg/PubChemPy
e3fd6cc401bfbe605082911911763c54cc02276a
[ "MIT" ]
1
2015-02-18T10:01:17.000Z
2015-02-18T10:01:17.000Z
setup.py
waltherg/PubChemPy
e3fd6cc401bfbe605082911911763c54cc02276a
[ "MIT" ]
null
null
null
setup.py
waltherg/PubChemPy
e3fd6cc401bfbe605082911911763c54cc02276a
[ "MIT" ]
null
null
null
#!/usr/bin/env python import os from setuptools import setup import pubchempy if os.path.exists('README.rst'): long_description = open('README.rst').read() else: long_description = '''PubChemPy is a wrapper around the PubChem PUG REST API that provides a way to interact with PubChem in Python. It allows chemical searches (including by name, substructure and similarity), chemical standardization, conversion between chemical file formats, depiction and retrieval of chemical properties. ''' setup( name='PubChemPy', version=pubchempy.__version__, author=pubchempy.__author__, author_email=pubchempy.__email__, license=pubchempy.__license__, url='https://github.com/mcs07/PubChemPy', py_modules=['pubchempy'], description='A simple Python wrapper around the PubChem PUG REST API.', long_description=long_description, keywords='pubchem python rest api chemistry cheminformatics', extras_require={'pandas': ['pandas']}, test_suite='pubchempy_test', classifiers=[ 'Intended Audience :: Science/Research', 'Intended Audience :: Healthcare Industry', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Topic :: Scientific/Engineering :: Chemistry', 'Topic :: Database :: Front-Ends', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Internet', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
37.653061
118
0.668293
c1e8abf4e62b8efc5c7349b99aabcac94e8186e4
5,692
py
Python
coloring/solver.py
WittgensteinInHisYouth/Discrete-Optimization
07f30058b51eace6a8b12a4a996bb92de99876e1
[ "CNRI-Python" ]
1
2022-01-20T06:41:34.000Z
2022-01-20T06:41:34.000Z
coloring/solver.py
waitaminutewhoareyou/Coursera-Discrete-Optimization
07f30058b51eace6a8b12a4a996bb92de99876e1
[ "CNRI-Python" ]
null
null
null
coloring/solver.py
waitaminutewhoareyou/Coursera-Discrete-Optimization
07f30058b51eace6a8b12a4a996bb92de99876e1
[ "CNRI-Python" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # from mip import * import random from csp import * import gurobipy as gp from gurobipy import GRB # def mip_solver(node_count, edge_count, edges): # m = Model(solver_name=GRB) # M = node_count * 2 # x = [m.add_var(var_type=INTEGER, lb=0, ub=node_count) for _ in range(node_count)] # y = [m.add_var(var_type=BINARY) for _ in range(edge_count)] # decision var for big-M method # C = m.add_var(var_type=INTEGER, lb=0, ub=node_count) # for ix, (i, j) in enumerate(edges): # m += x[j] + 1 - x[i] - M * y[ix] <= 0 # m += x[i] - x[j] + 1 - M * (1 - y[ix]) <= 0 # for i in range(node_count): # m += x[i] - C <= 0 # m.objective = minimize(C) # status = m.optimize(max_seconds=3000) # if status == OptimizationStatus.OPTIMAL: # opti = 1 # else: # opti = 0 # solution = [int(assignment.x) for assignment in x] # return solution, opti def mip_solver(node_count, edge_count, edges): m = gp.Model() M = node_count*2 x = m.addVars(node_count, vtype=GRB.INTEGER, lb=0, ub=node_count, name="x") y = m.addVars(edge_count, vtype=GRB.BINARY) C = m.addVar(vtype=GRB.INTEGER, lb=0, ub=node_count) for ix, (i, j) in enumerate(edges): m.addConstr(x[j] + 1 - x[i] - M * y[ix] <= 0) m.addConstr(x[i] - x[j] + 1 - M * (1 - y[ix]) <= 0) for i in range(node_count): m.addConstr(x[i] - C <= 0) m.setObjective(C, GRB.MINIMIZE) timeLimit = 1.5*60*60 #3 hours to check m.setParam("TimeLimit", timeLimit) m.optimize() # provide an inital solution if there is none if m.solCount == 0: for ix,var in enumerate(x): x[var].start = ix m.Params.MIPFocus = 1 timeLimit = 0.5 * 60 * 60 # 4.5 hours to check m.setParam("TimeLimit", timeLimit) m.optimize() opti = 1 if m.status == GRB.OPTIMAL else 0 solution = [int(v.x) for v in m.getVars()[:node_count]] return solution, opti def solve_semi_magic(num_color, node_count, edge_count, edges,algorithm=backtracking_search, **args): """ From CSP class in csp.py vars A list of variables; each is atomic (e.g. int or string). domains A dict of {var:[possible_value, ...]} entries. neighbors A dict of {var:[var,...]} that for each variable lists the other variables that participate in constraints. constraints A function f(A, a, B, b) that returns true if neighbors A, B satisfy the constraint when they have values A=a, B=b """ # Use the variable names in the figure def shu(x): random.shuffle(x) return x csp_vars = shu([d for d in range(node_count)]) ######################################### # Fill in these definitions csp_domains = {var: shu(list(range(num_color))) for var in csp_vars} csp_neighbor = {var: [] for var in csp_vars} for node_i, node_j in edges: csp_neighbor[node_i].append(node_j) csp_neighbor[node_j].append(node_i) csp_neighbors = {key: shu(val) for key, val in csp_neighbor.items()} def csp_constraints(A, a, B, b): return a != b ######################################### # define the CSP instance csp = CSP(csp_vars, csp_domains, csp_neighbors, csp_constraints) # run the specified algorithm to get an answer (or None) ans = algorithm(csp, **args) # print('number of assignments', csp.nassigns) assign = csp.infer_assignment() # if assign: # for x in sorted(assign.items()): # print(x) # for var in csp_vars: # print(ans[var]) if ans is not None: opti = 1 #solution = [None for _ in range(node_count)] #print(sorted(assign.items())) solution = [val for var, val in sorted(assign.items())] return solution, opti return None def csp_solver(node_count, edge_count, edges): num_color, solution_thus_far = 0, None while solution_thus_far is None: num_color += 1 solution_thus_far = solve_semi_magic(num_color, node_count, edge_count, edges, algorithm=backtracking_search, select_unassigned_variable=mrv,order_domain_values=lcv, inference=mac) return solution_thus_far def solve_it(input_data): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') first_line = lines[0].split() node_count = int(first_line[0]) edge_count = int(first_line[1]) edges = [] for i in range(1, edge_count + 1): line = lines[i] parts = line.split() edges.append((int(parts[0]), int(parts[1]))) #print(node_count, edge_count, edges) # build a trivial solution # every node has its own color solution, opti = mip_solver(node_count, edge_count, edges) #solution, opti = csp_solver(node_count, edge_count, edges) # prepare the solution in the specified output format output_data = str(len(set(solution))) + ' ' + str(opti) + '\n' output_data += ' '.join(map(str, solution)) return output_data import sys if __name__ == '__main__': import sys sys.argv = ['C:/Users/JI YIHONG/Dropbox/Coursera/Discrete Optimization/coloring/solver.py', 'data/gc_4_1'] if len(sys.argv) > 1: file_location = sys.argv[1].strip() with open(file_location, 'r') as input_data_file: input_data = input_data_file.read() print(solve_it(input_data)) else: print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/gc__5)')
35.575
188
0.611384
a85c9fb696feb93674797708f6af445f89b427fa
77,731
py
Python
bin/ADFRsuite/CCSBpckgs/PmvApp/secondaryStructureCmds.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
null
null
null
bin/ADFRsuite/CCSBpckgs/PmvApp/secondaryStructureCmds.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
null
null
null
bin/ADFRsuite/CCSBpckgs/PmvApp/secondaryStructureCmds.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
1
2021-11-04T21:48:14.000Z
2021-11-04T21:48:14.000Z
################################################################################ ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## ## (C) Copyrights Dr. Michel F. Sanner and TSRI 2016 ## ################################################################################ ############################################################################# # # Author: Sophie I. COON, Michel F. SANNER, Anna Omelchenko # # Copyright: M. Sanner TSRI 2014 # ############################################################################# # # $Header: /mnt/raid/services/cvs/PmvApp/secondaryStructureCmds.py,v 1.6.4.1 2017/07/13 20:55:28 annao Exp $ # # $Id: secondaryStructureCmds.py,v 1.6.4.1 2017/07/13 20:55:28 annao Exp $ # import numpy from opengltk.OpenGL import GL from DejaVu2.IndexedPolygons import IndexedPolygons from DejaVu2.Shapes import Shape2D, Triangle2D, Circle2D, Rectangle2D,\ Square2D, Ellipse2D from MolKit2.tree import TreeNodeSet from MolKit2.molecule import Atom, AtomSet, Molecule, MoleculeSet from MolKit2.protein import Protein, Residue, Chain, ResidueSet, ProteinSet from MolKit2.protein import SecondaryStructure, SecondaryStructureSet, \ Helix, Strand, Turn, Coil from NucleicBases import Add_Nucleic_Bases from PmvApp.Pmv import MVCommand from PmvApp.extruder import Sheet2D, ExtrudeSSElt, ExtrudeNA from PmvApp.displayCmds import DisplayCommand from PmvApp.colorCmds import ColorFromPalette from PmvApp.colorPalette import ColorPalette from PmvApp.Pmv import AfterDeleteAtomsEvent from PmvApp.Pmv import DeleteGeomsEvent, AddGeomsEvent, EditGeomsEvent from AppFramework.App import RemoveGeometryEvent, AddGeometryEvent class ComputeSecondaryStructureCommand(MVCommand): """The computeSecondaryStructure command gets the information on the secondary structure of each molecule from the current selection. This information is then used to create objects describing the various secondary structure elements. \n Package : PmvApp \n Module : secondaryStructureCmds \n Class : ComputeSecondaryStructureCommand \n Command name : computeSecondaryStructure \n Description:\n The SS element object belonging to a chain are then grouped into sets.\n A new level is added in the 4 level hierarchy...\n The information is taken from the file when available or using stride when\n available. This command can be used as an interactive command. \n Synopsis:\n None <--- ComputeSS(nodes, molMode={}) \n Required Arguments:\n nodes --- any set for MolKit2.Selection describing molecular components \n Optional Arguments:\n molmode --- dictionary key: molecule name, value : 'From File' or 'From Stride'. \n Required Packages:\n MolKit, DejaVu2, mglutil, OpenGL, ViewerFramework \n Known bugs:\n None \n Examples:\n mol = mv.Mols[0] \n mv.computeSecondaryStructure(mol) """ def __init__(self): MVCommand.__init__(self) #self.flag = self.flag | self.objArgOnly def onRemoveObjectFromViewer(self, obj): """ Method to delete sets created by this command. This is done to prevent circular references and memory leaks. """ if self.app().undoableDelete__: return if not hasattr(obj, 'chains'): return for c in obj.chains: if not hasattr(c, 'secondarystructureset') : continue if c.secondarystructureset is None: delattr(c.secondarystructureset) else: # Cleaning up all the circular references created in this # command while len(c.secondarystructureset)!=0: if hasattr(c.secondarystructureset[0], 'exElt'): delattr(c.secondarystructureset[0], 'exElt') delattr(c.secondarystructureset[0], 'children') delattr(c.secondarystructureset[0], 'residues') delattr(c.secondarystructureset[0], 'start') delattr(c.secondarystructureset[0], 'end') delattr(c.secondarystructureset[0], 'parent') delattr(c.secondarystructureset[0], 'chain') delattr(c.secondarystructureset[0], 'top') del(c.secondarystructureset[0]) def onAddCmdToApp(self): # Try to import stride and set the flag to 1 if succeeds and to 0 if # does not try: import stride self.haveStride = 1 except: self.haveStride = 0 # Load the dependent commands if not already loaded in the # application if not self.app().commands.has_key('saveSet'): self.app().lazyLoad('selectionCmds', commands=['saveSet'], package='PmvApp') def checkArguments(self, nodes, molModes=None): """None <--- computeSecondaryStructure(nodes, molModes = None) \n nodes --- TreeNodeSet holding the current selection. \n moldMode --- dictionary {name of the protein: 'From File', 'From PROSS', or 'From Stride'},\n 'From File' to get the information from the file,\n 'From Pross' to use the pross code to assing SS\n 'From Stride' to use stride (requires stride to be installed). """ if isinstance(nodes, str): self.nodeLogString = "'"+nodes+"'" nodes = self.app().expandNodes(nodes) assert len(nodes) if molModes: assert isinstance(molModes, dict) for mode in molModes.values(): if mode: assert mode in ['From File', 'From Pross', 'From Stride'] kw = {} kw['molModes'] = molModes return (nodes,), kw def doit(self, nodes, molModes=None): molecules, nodeSets = self.app().getNodesByMolecule(nodes) # Loop over the molecules for mol in molecules: try: for c in mol.chains: c.ribbonType() # Determine what mode to use to get the information if not molModes: if mol.hasSS: # Information has already been computed then # continue continue else: # Find out the possibilities and set the mode to # one of them. if mol.parser: if mol.parser.hasSsDataInFile(): # File contains information the mode will be 'From # File' mode = 'From File' else: mode = 'From Pross' elif self.haveStride: # Stride is available on the platform # but no info in the file then stride will be used mode='From Stride' else: mode='From Pross' else: #print molModes # a mode to get the information has been specified # for the given molecules if molModes and not molModes.has_key(mol.name): # if the mode has not been specified for a molecule # print a message and continue raise RuntimeError, '%s: No mode has been specified for %s'% (self.name, mol.name) else: # Set the mode to the given value. mode = molModes[mol.name] # if this mode has already been used pass. if mode in mol.hasSS: continue # if secondarystructure have been computed once using another # mode need to clean up first elif mol.hasSS != []: self.clean(mol) # Then compute using the new given mode. #if mode is None: # mol.secondaryStructureFromFile() if mode == 'From File': # If both modes available try file first if fails use stride # instead. #if not mol.parser.hasSsDataInFile(): # # GIVE FEEDBACK TO THE USER !!!! # self.warningMsg("WARNING: "+mol.name + \ # ".pdb does not contain Secondary \ # Structure information.") # continue #else: mol.secondaryStructureFromFile() #self.savesets(mol) elif mode == 'From Stride': if not self.haveStride: raise RuntimeError , "%s: Stride is not available on \ this computer to compute the secondary structure of " %(self.name, mol.name+".pdb") else: mol.secondaryStructureFromStride() #self.savesets(mol) elif mode == 'From Pross': mol.secondaryStructureFromPross() #self.savesets(mol) #self.savesets(mol) self.app()._executionReport.addSuccess('Computed secondary structure for molecule %s successfully'% mol.name, obj=mol) except: msg = 'Error while computing secondary structure for molecule %s'%mol.name self.app().errorMsg(sys.exc_info(), msg, obj=mol) def savesets(self, mol): for c in mol.chains: if not hasattr(c, 'secondarystructureset'): continue for ss in c.secondarystructureset: name = "%s%s"%(ss.name, ss.chain.id) if ss.residues: #Bugfix for #1033 ## MS calling the command slows this down a lot ## but the sets are needed to extrude, so we add sets 'by hand' ## side effect: no vision nodes for these sets # self.app().saveSet(ss.residues, mol.name+':'+name[-1] # +':'+name[:-1], # '%s-%s' %(ss.residues[0].name, # ss.residues[-1].name), # ) name = mol.name+':'+name[-1] +':'+name[:-1] ss.residues.comments = '%s-%s'%(ss.residues[0].name, ss.residues[-1].name) self.app().sets.add(name, ss.residues) def clean(self, mol): """ This method is called when getting the secondary structure information using stride after having from file and vice versa. It is used to delete all the secondary structure objects and attributes created previously.""" # Compute secondary structure creates the following: # - Secondary structure elements # - Save the secondary structure elements residues as a set # - new mol attribute hasSS which is a list #from PmvApp.selectionCommands import sets__ molName = mol.name mol.hasSS = [] # Here need to check if the secondary structure element have # been extruded or not. If yes need to clean up that as well. if hasattr(mol, '_ExtrudeSecondaryStructureCommand__hasSSGeom')\ and mol._ExtrudeSecondaryStructureCommand__hasSSGeom: self.app().extrudeSecondaryStructure.clean(mol) for chain in mol.chains: # delete the secondarystructureset if not hasattr(chain, 'secondarystructureset'): continue for ss in chain.secondarystructureset: name = "%s%s"%(ss.name, ss.chain.id) setName = mol.name+':'+name[-1]+':'+name[:-1] if self.app().sets.has_key(setName): del self.app().sets[setName] #del sets__[mol.name+':'+name[-1]+':'+name[:-1]] delattr(chain, 'secondarystructureset') # delete the secondarystructure attribute of the residues when # existing. resTest = [delattr(x, 'secondarystructure') for x in chain.residues if hasattr(x, 'secondarystructure')] # call the onRemoveObjectFromViewer for the mol. self.app().undoableDelete__ = False self.onRemoveObjectFromViewer(mol) del self.app().undoableDelete__ # Also need to clean up the sheet2D information. for c in mol.chains: if hasattr(c, 'sheet2D') and c.sheet2D.has_key('ssSheet2D'): del c.sheet2D['ssSheet2D'] class ExtrudeSecondaryStructureCommand(MVCommand): """The ExtrudeCommand allows the user to represent the secondary structure elements by extruding 2D geometries along a 3D path.To execute this command use the entry 'extrude Secondary Structure' under the 'Compute' menu in the menu bar. The panel that appears lets the user choose the 2D shapes for the extrusion. The entry 'default' in the listChooser lets do a traditional ribbon representation.nbchords represents the number of points in the path3D corresponding to one residue. The higher this parameter is the smoother the extruded geometries will look.gapBeg allows the user to introduce a gap of gapBeg points the extruded geometrie before each residue.gapEnd allows the user to introduce a gap of gapEnd points the extruded geometrie after each residue.The value of this two parameters depend on the value of the nbchords parameter and on each other's value.Once you clique OK on this panel another panel appears to let the user caracterize the chosen 2D geometry.Once the user chose all the parameters an ExtrudeSSElt object is created for each secondary structure element. The geometries associated to each secondary structure element are then updated with the new vertices and faces.Finally the displaySSCommand is executed.This command has the objArgsOnly flag. \n Package : PmvApp \n Module : secondaryStructureCommands \n Class : ExtrudeSecondaryStructureCommand \n Command name : extrudeSecondaryStructure \n Synopsis:\n None <--- extrudeSecondaryStructure(nodes, shape1=None, shape2=None,frontcap=1, endcap=True, arrow=True, nbchords=8, gapBeg=False,gapEnd=False, larrow=2, display=True) \n Required Arguments:\n nodes --- TreeNodeSet holding the current selection(mv.getSelection()) \n Optional Arguments:\n shape1 & shape2 --- DejaVu2.Shapes.Shape2D objects. shape1 will be used to represent the helix and strand, shape2 to represent coils and turns. \n frontcap & endcap --- Boolean flag when set to True a cap will be added to the geom either at the front or at the end \n arrow --- Boolean flag when set to True an arow will be added to the geometry representing the strand.\n nbchords --- Nb of points per residues in the smooth array \n gapBeg& gapEnd --- defines gap at the beginning or the end of each residue. \n larrow --- lenth of the arrow if arrow boolean flag set to 1 \n display --- Boolean flag when set to True the displaySecondaryStructure is called automatically """ def __init__(self): MVCommand.__init__(self) #self.flag = self.flag | self.objArgOnly def pickedVerticesToAtoms(self, geom, vertInd): """ This function gets called when a picking or drag select event has happened. It gets called with a geometry and the list of vertex indices of that geometry that have been picked. This function is in charge of turning these indices into an AtomSet This function takes the following arguments: geom : geometry picked, instance of a class derived from DejaVu2.Geom (IndexedPolygons, IndexedPolylines.....) vertInd: list of integer representing the indices of the picked vertices in the given geometry geom. """ # this function gets called when a picking or drag select event has # happened. It gets called with a geometry and the list of vertex # indices of that geometry that have been selected. # This function is in charge of turning these indices into an AtomSet ss = geom.SS l = [] for vi in vertInd: resInd = ss.exElt.getResIndexFromExtrudeVertex( vi ) try: l.append(ss.children[int(resInd)].atoms.get('CA')[0]) except: l.append(ss.children[int(resInd)].atoms[0]) return AtomSet( AtomSet( l ) ) def atomPropToVertices(self, geom, residues, propName, propIndex=None): """Function called to compute the array of properties""" if residues is None or len(residues)==0 : return None propVect = [] if not propIndex is None: propIndex = 'secondarystructure' for r in residues: try: prop = getattr(r.atoms.get('CA')[0], propName) except IndexError: prop = getattr(r.atoms[0], propName) if not propIndex is None: propVect.append(prop.get(propIndex, prop['lines'])) else: propVect.append(prop) geom.SS.exElt.setResProperties(propVect, propName, residues) properties = geom.SS.exElt.getExtrudeProperties( residues, propName ) return properties def onAddObjectToViewer(self, obj): self.objectState[obj] = {'onAddObjectCalled':True} # private flag to specify whether or not the geometries for the SS # have been created. obj.__hasSSGeom = 0 if self.app().commands.has_key('dashboard'): self.app().dashboard.resetColPercent(obj, '_showRibbonStatus') def createGeometries(self, obj): if obj.__hasSSGeom : return from DejaVu2.Geom import Geom geomC = obj.geomContainer if not geomC.geoms.has_key('secondarystructure'): t = Geom('secondarystructure', shape=(0,0), protected=True) geomC.addGeom( t, parent=geomC.masterGeom, redo=0 ) else: t = geomC.geoms['secondarystructure'] for a in obj.allAtoms: a.colors['secondarystructure']=(1.,1.,1.) a.opacities['secondarystructure']=1. for c in obj.chains: if not hasattr(c, 'secondarystructureset'): continue for ss in c.secondarystructureset: name = "%s%s"%(ss.name, ss.chain.id) g = IndexedPolygons(name, visible=0, pickableVertices=1, protected=True,) if self.app().userpref['Sharp Color Boundaries for MSMS']['value'] == 'blur': g.Set(inheritSharpColorBoundaries=False, sharpColorBoundaries=False,) #g.RenderMode(GL.GL_FILL, face=GL.GL_FRONT, redo=0) #g.Set(frontPolyMode=GL.GL_FILL,redo=0) g.SS = ss geomC.atomPropToVertices[name] = self.atomPropToVertices geomC.geomPickToAtoms[name] = self.pickedVerticesToAtoms geomC.geomPickToBonds[name] = None geomC.addGeom(g, parent=t, redo=0 ) self.managedGeometries.append(g) #geomC.addGeom(g,self,parent=t, redo=0 ) geomC.atoms[name] = ResidueSet() obj.__hasSSGeom = 1 def onAddCmdToApp(self): self.app().lazyLoad("secondaryStructureCmds", commands = ['computeSecondaryStructure', 'displayExtrudedSS'], package="PmvApp") self.app().lazyLoad("extrusionCmds", commands=['computeSheet2D', "Nucleic_Acids_properties"], package="PmvApp") def clean(self, obj): if not hasattr(obj, 'chains'): return for c in obj.chains: if hasattr(c, 'residuesInSS'): delattr(c, 'residuesInSS') if not hasattr(c, 'secondarystructureset'): continue for ss in c.secondarystructureset: # Have to remove specifically geoms.SS and geoms.mol # from the geomContainer and the viewer g = obj.geomContainer.geoms[ss.name+c.id] del(g.SS) del(g.mol) g.Set(visible=0, tagModified=False) g.protected = False event = RemoveGeometryEvent(g) self.app.eventHandler.dispatchEvent(event) # the application's GUI should add a listener for this event, # and the method to: #self.app().GUI.VIEWER.RemoveObject(g) del obj.geomContainer.geoms[ss.name+c.id] del obj.geomContainer.atoms[ss.name+c.id] obj.__hasSSGeom=0 def onRemoveObjectFromViewer(self, obj): if self.objectState.has_key(obj): self.objectState.pop(obj) if self.app().undoableDelete__: return if not hasattr(obj, 'chains'): return for c in obj.chains: if hasattr(c, 'residuesInSS'): delattr(c, 'residuesInSS') if not hasattr(c, 'secondarystructureset'): continue for ss in c.secondarystructureset: # Have to remove specifically geoms.SS and geoms.mol # from the geomContainer and the viewer g = obj.geomContainer.geoms[ss.name+c.id] del(g.SS) del(g.mol) g.Set(visible=0, tagModified=False) g.protected = False event = RemoveGeometryEvent(g) self.app.eventHandler.dispatchEvent(event) # the application's GUI should add a listener for this event, # and the method to: #self.app().GUI.VIEWER.RemoveObject(g) del obj.geomContainer.geoms[ss.name+c.id] del obj.geomContainer.atoms[ss.name+c.id] obj.__hasSSGeom=0 def checkArguments(self, nodes, shape1=None, shape2=None, frontcap=True, endcap=True, arrow=True, nbchords=8, gapBeg=0, gapEnd=0, larrow=2, display=True, width=1.2, height=0.2, radius=0.1, updateNucleicAcidsPropertiesGUI=False, only=True, negate=False): """Required Arguments:\n nodes --- TreeNodeSet holding the current selection (mv.getSelection()) \n Optional Arguments:\n shape1 & shape2 --- DejaVu2.Shapes.Shape2D objects. shape1 will be used to \n represent the helix and strand, shape2 to represent coils and\n turns.\n frontcap & endcap --- Boolean flag when set to True a cap will be added to the \n geom either at the front or at the end \n arrow --- Boolean flag when set to True an arow will be added to the \n geometry representing the strand. \n nbchords --- Nb of points per residues in the smooth array \n gapBeg& gapEnd --- defines gap at the beginning or the end of each residue. \n larrow --- length of the arrow if arrow boolean flag set to 1 \n display --- Boolean flag when set to True the displaySecondaryStructure is called automatically width, height, radius --- if shape1 is not specified, these parameters \n are used to create shape1 (Rectangle2D(withd, height)) \n and shape2 (Circle2D(radius)) . """ if isinstance (nodes, str): self.nodeLogString = "'"+nodes+"'" nodes = self.app().expandNodes(nodes) assert isinstance(nbchords, int) assert gapEnd<=len(nodes) assert gapBeg<=len(nodes) if shape1: assert isinstance(shape1 , Shape2D) if shape2: assert isinstance(shape2 , Shape2D) assert frontcap in (True,False, 1, 0) assert endcap in (True, False, 1, 0) assert arrow in (True, False, 1, 0) assert display in (True, False, 1, 0) assert isinstance (larrow, (int, float)) assert isinstance (width, (int, float)) assert isinstance (height, (int, float)) assert isinstance (radius, (int, float)) kw = {} kw['shape1'] = shape1 kw['shape2'] = shape2 kw['frontcap'] = frontcap kw['endcap'] = endcap kw['arrow'] = arrow kw['nbchords'] = nbchords kw['gapBeg'] = gapBeg kw['gapEnd'] = gapEnd kw['larrow'] = larrow kw['display'] = display kw['width'] = width kw['height'] = height kw['radius'] = radius kw['updateNucleicAcidsPropertiesGUI'] = updateNucleicAcidsPropertiesGUI kw['only'] = only kw['negate'] = negate #print "kw.has_key('only')=", kw.has_key('only') #print kw.get('only', 'no_value') return (nodes,), kw def doit(self, nodes, shape1=None, shape2=None, frontcap=True, endcap=True, arrow=True, nbchords=8, gapBeg=0, gapEnd=0, larrow = 2, display=True, width=1.2, height=0.2, radius=0.1, updateNucleicAcidsPropertiesGUI=False, only=True, negate=False): """ nodes, shape1, shape2=None, frontcap=True, endcap=True, arrow=True, nbchords=8, gapBeg=0, gapEnd=1, display=True""" #print "2: kw.has_key('only')=", kw.has_key('only'), ':', #print kw.get('only', 'no_value') shape1o = shape1 shape2o = shape2 molecules, residueSets = self.app().getNodesByMolecule(nodes, Residue) if shape1 is None: shape1 = Rectangle2D(width=width, height=height, vertDup=1) shape2 = Circle2D(radius=radius) # highlight selection selMols, selResidues = self.app().getNodesByMolecule(self.app().activeSelection.get(), Residue) molSelectedResiduesDict = dict( zip( selMols, selResidues) ) # Create a sheet2 object. for mol, residues in map(None, molecules, residueSets): try: if not self.objectState.has_key(mol): self.onAddObjectToViewer(mol) if not mol.hasSS: # Compute the secondarystructure if not there self.app().computeSecondaryStructure(mol) if not hasattr(mol,'__hasSSGeom') or not mol.__hasSSGeom: # Need here to change self.createGeometries(mol) reswithss = residues.get(lambda x: hasattr(x, 'secondarystructure')) if reswithss is None: raise RuntimeError, "%s: no secondary structure in specified nodes of molecule "% (self.name, mol.name) selectionSS = reswithss.secondarystructure.uniq() chains = residues.parent.uniq() # highlight selection if molSelectedResiduesDict.has_key(mol) and len(molSelectedResiduesDict[mol]) > 0: lHighlight = True else: lHighlight = False for i in range(len(chains)): chain = chains[i] chain.ssExtrusionParams = { # used to save session 'shape1' : shape1o, 'shape2' : shape2o, 'frontcap' : frontcap, 'endcap' : endcap, 'arrow' : arrow, 'nbchords' : nbchords, 'gapBeg' : gapBeg, 'gapEnd' : gapEnd, 'larrow' : larrow } newsheet = 0 if not hasattr(chain, 'sheet2D'): chain.sheet2D = {} if not hasattr(chain,'secondarystructureset'): self.app().warningMsg('%s: no secondary structure set for chain %s in molecule %s'%(self.name, chain.id, mol.name)) chain.sheet2D['ssSheet2D'] = None continue ssSet = chain.secondarystructureset # 1- Check if the sheet2D for a secondary structure has been # computed already. if chain.sheet2D.has_key('ssSheet2D'): if chain.sheet2D['ssSheet2D'] is None: newsheet = 0 continue elif chain.sheet2D['ssSheet2D'].chords != nbchords: rt = chain.ribbonType() if rt=='NA': ExtrudeNA(chain) newsheet = 1 elif rt=='AA': self.app().computeSheet2D(chain, 'ssSheet2D', 'CA','O', buildIsHelix=1, nbchords=nbchords) newsheet = 1 else: newsheet = 0 else: newsheet = 0 elif not chain.sheet2D.has_key('ssSheet2D'): rt = chain.ribbonType() if rt=='NA': ExtrudeNA(chain) newsheet = 1 elif rt=='AA': self.app().computeSheet2D(chain, 'ssSheet2D', 'CA', 'O',buildIsHelix=1, nbchords=nbchords) newsheet = 1 else: newsheet = 0 if newsheet: sd = chain.sheet2D['ssSheet2D'] # then create a pointer to the sheet2D for each secondary structures. ssSet.sheet2D = sd if sd is None : continue # Do the extrusion ONLY for the ss having a residue in the # selection removeSS =[] #from PmvApp.selectionCommands import sets__ for SS in ssSet: # test here if all the residues of the sselt are # in the residue set used # to compute the sheet2D. if not remove the ss. if SS.sheet2D is None: continue #if filter(lambda x, rs = SS.sheet2D.resInSheet: # not x in rs, SS.residues): if [x for x in SS.residues if not x in SS.sheet2D.resInSheet]: self.app().warningMsg("%s: Removing %s from secondary structure set(molecule %s). One or more residues doesn't have CA and O"%(self.name, SS.name, mol.name)) # remove the SS from the set and etc.... #delattr(SS.residues, 'secondarystructure') #ssSet.remove(SS) removeSS.append(SS) name = "%s%s"%(SS.name, SS.chain.id) setName = mol.name+':'+name[-1]+':'+name[:-1] if self.app().sets.has_key(setName): del self.app().sets[setName] #del sets__[mol.name+':'+name[-1]+':'+name[:-1]] g = mol.geomContainer.geoms[name] g.protected = False event = RemoveGeometryEvent(g) self.app.eventHandler.dispatchEvent(event) # the application's GUI should add a listener for # this event, and the method to: # self.app().GUI.VIEWER.RemoveObject(g) continue name = "%s%s"%(SS.name, SS.chain.id) if not SS in selectionSS: continue if isinstance(SS, Strand): arrowf = arrow else: arrowf = 0 if not shape2 is None: if SS.__class__.__name__ in ['Strand', 'Helix']: SS.exElt = ExtrudeSSElt( SS, shape1, gapEnd , gapBeg, frontcap, endcap, arrowf,larrow) elif SS.__class__.__name__ in ['Coil', 'Turn']: rt = chain.ribbonType() if rt=='NA': NAp = self.app().Nucleic_Acids_properties if NAp.isLoader(): NAp = NAp.loadCommand() sc = max(NAp.scale_pyrimidine, NAp.scale_purine) #shape2 = Circle2D(radius=sc/2.5) shape3 = Circle2D(radius=sc/5.) SS.exElt = ExtrudeSSElt( SS, shape3, gapEnd, gapBeg, frontcap, endcap, arrowf) elif rt=='AA': SS.exElt = ExtrudeSSElt( SS, shape2, gapEnd, gapBeg, frontcap, endcap, arrowf) else: SS.exElt = ExtrudeSSElt(SS, shape1, gapEnd , gapBeg, frontcap, endcap, arrowf, larrow) resfaces, resfacesDict = SS.exElt.getExtrudeResidues(SS.residues) g = mol.geomContainer.geoms[name] ## # MS triangulate faces ## trifaces = [] ## for f in resfaces: ## trifaces.append( (f[0],f[1],f[3]) ) ## if f[2]!=f[3]: ## trifaces.append( (f[1],f[2],f[3]) ) # highlight selection g.resfacesDict = resfacesDict highlight = [] if lHighlight is True:# and chain in residueSet : highlight = [0]*len(SS.exElt.vertices) for lResidue in molSelectedResiduesDict[mol]: if resfacesDict.has_key(lResidue): for lFace in resfacesDict[lResidue]: for lVertexIndex in lFace: highlight[int(lVertexIndex)] = 1 g.Set(vertices=SS.exElt.vertices, highlight=highlight, faces = resfaces, ## faces=trifaces, vnormals=SS.exElt.vnormals, redo=0, tagModified=False) if chain.ribbonType()=='NA': geom_bases = Add_Nucleic_Bases( g, self.app().Nucleic_Acids_properties) event = AddGeometryEvent(geom_bases, parent=g, redo=False) self.app.eventHandler.dispatchEvent(event) # the GUI of the application should create this event # listenter with the method that will: #self.app().GUI.VIEWER.AddObject(geom_bases, parent=g) if geom_bases not in g.children: g.children.append(geom_bases) geom_bases.parent = g #geom_bases.fullName = g.fullName+'|'+geom_bases.name for SS in removeSS: delattr(SS.residues, 'secondarystructure') ssSet.remove(SS) self.app()._executionReport.addSuccess('Extruded SS for molecule %s successfully'% mol.name, obj=residues) except: msg = 'Error while displaying lines for molecule %s'%mol.name self.app().errorMsg(sys.exc_info(), msg, obj=residues) if display: kw = {'only':True, 'negate':negate} #print "calling displayExtrudedSS with ", kw self.app().displayExtrudedSS(*(nodes,), **kw) # gg = g.viewer.FindObjectByName('root|1dwb_0|secondarystructure|Coil1L') # print 'AFTER DISPLAY', gg #self.app().displayExtrudedSS(nodes) event = EditGeomsEvent( 'SSextrude', [nodes,[shape1, shape2, frontcap, endcap, arrow, nbchords, gapBeg, gapEnd, larrow, display, updateNucleicAcidsPropertiesGUI]]) self.app().eventHandler.dispatchEvent(event) class ExtrudeSecondaryStructureCommandUnic(ExtrudeSecondaryStructureCommand): """The ExtrudeCommand allows the user to represent the secondary structure elements by extruding 2D geometries along a 3D path Package : PmvApp \n Module : secondaryStructureCmds \n Class : ExtrudeSecondaryStructureCommand \n Command name : extrudeSecondaryStructure \n Synopsis:\n None <--- extrudeSecondaryStructure(nodes, shape1=None, shape2=None,frontcap=1, endcap=True, arrow=True, nbchords=8, gapBeg=False,gapEnd=False, larrow=2, display=True) \n Required Arguments:\n nodes --- TreeNodeSet holding the current selection(mv.getSelection()) \n Optional Arguments:\n shape1 & shape2 --- DejaVu2.Shapes.Shape2D objects. shape1 will be used to \n represent the helix and strand, shape2 to represent coils and \n turns. \n frontcap & endcap --- Boolean flag when set to True a cap will be added to the \n geom either at the front or at the end \n arrow --- Boolean flag when set to True an arow will be added to the \n geometry representing the strand. \n nbchords --- Nb of points per residues in the smooth array \n gapBeg& gapEnd --- defines gap at the beginning or the end of each residue. \n larrow --- lenth of the arrow if arrow boolean flag set to 1 \n display --- Boolean flag when set to True the displaySecondaryStructure is called automatically """ def __init__(self): ExtrudeSecondaryStructureCommand.__init__(self) def createGeometries(self, obj): if hasattr(obj,'__hasSSGeom') : return from DejaVu2.Geom import Geom geomC = obj.geomContainer if not geomC.geoms.has_key('SS'): t = Geom('SS', shape=(0,0), protected=True) geomC.addGeom( t, parent=geomC.masterGeom, redo=0 ) else: t = geomC.geoms['SS'] for a in obj.allAtoms: a.colors['SS']=(1.,1.,1.) a.opacities['SS']=1. for c in obj.chains: #if not hasattr(c, 'secondarystructureset'): # continue #for ss in c.secondarystructureset: name = "SS%s"%(c.id) g = IndexedPolygons(name, visible=0, pickableVertices=1, protected=True,) if self.app().userpref['Sharp Color Boundaries for MSMS']['value'] == 'blur': g.Set(inheritSharpColorBoundaries=False, sharpColorBoundaries=False,) g.Set(frontPolyMode=GL.GL_FILL) #g.SS = ss geomC.atomPropToVertices[name] = self.atomPropToVertices geomC.geomPickToAtoms[name] = self.pickedVerticesToAtoms geomC.geomPickToBonds[name] = None geomC.addGeom(g, parent=t, redo=0 ) self.managedGeometries.append(g) #geomC.addGeom(g,self,parent=t, redo=0 ) geomC.atoms[name] = ResidueSet() atoms = c.findType(Atom) for a in atoms: a.colors[name]=(1.,1.,1.) a.opacities[name]=1. for ss in c.secondarystructureset: sname = "%s%s"%(ss.name, ss.chain.id) geomC.atoms[sname] = ResidueSet() obj.__hasSSGeom = 1 def doit(self, nodes, shape1=None, shape2=None, frontcap=True, endcap=True, arrow=True, nbchords=8, gapBeg=0, gapEnd=0, larrow = 2, display=True, width=1.2, height=0.2, radius=0.1, updateNucleicAcidsPropertiesGUI=False, only=True, negate=False): """ nodes, shape1, shape2=None, frontcap=True, endcap=True, arrow=True, nbchords=8, gapBeg=0, gapEnd=1, display=True""" #print "2: kw.has_key('only')=", kw.has_key('only'), ':', #print kw.get('only', 'no_value') molecules, residueSets=self.app().getNodesByMolecule(nodes, Residue) if len(molecules)==0: return if shape1 is None: shape1 = Rectangle2D(width=width, height=height, vertDup=1) shape2 = Circle2D(radius=radius) # highlight selection selMols, selResidues = self.app().getNodesByMolecule(self.app().activeSelection.get(), Residue) molSelectedResiduesDict = dict( zip( selMols, selResidues) ) # Create a sheet2 object. for mol, residues in map(None, molecules, residueSets): try: if not mol.hasSS: # Compute the secondarystructure if not there self.app().computeSecondaryStructure(mol) if not hasattr(mol,'__hasSSGeom') or not mol.__hasSSGeom: # Need here to change self.createGeometries(mol) reswithss = residues.get(lambda x: hasattr(x, 'secondarystructure')) if reswithss is None: raise RuntimeError, '%s: no secondary structure in specified nodes for molecule %s' % (self.name, mol) selectionSS = reswithss.secondarystructure.uniq() chains = residues.parent.uniq() # highlight selection if molSelectedResiduesDict.has_key(mol) and len(molSelectedResiduesDict[mol]) > 0: lHighlight = True else: lHighlight = False for i in range(len(chains)): chain = chains[i] newsheet = 0 if not hasattr(chain, 'sheet2D'): chain.sheet2D = {} if not hasattr(chain,'secondarystructureset'): self.app().warningMsg('%s:no secondary structure set for chain: %s in molecule %s'%(self.name, chain.id, mol.name)) chain.sheet2D['ssSheet2D'] = None continue ssSet = chain.secondarystructureset # 1- Check if the sheet2D for a secondary structure has been # computed already. if chain.sheet2D.has_key('ssSheet2D'): if chain.sheet2D['ssSheet2D'] is None: newsheet = 0 continue elif chain.sheet2D['ssSheet2D'].chords != nbchords: rt = chain.ribbonType() if rt=='NA': ExtrudeNA(chain) newsheet = 1 elif rt=='AA': self.app().computeSheet2D(chain, 'ssSheet2D', 'CA','O', buildIsHelix=1, nbchords=nbchords) newsheet = 1 else: newsheet = 0 else: newsheet = 0 elif not chain.sheet2D.has_key('ssSheet2D'): rt = chain.ribbonType() if rt=='NA': ExtrudeNA(chain) newsheet = 1 elif rt=='AA': self.app().computeSheet2D(chain, 'ssSheet2D', 'CA', 'O',buildIsHelix=1, nbchords=nbchords) newsheet = 1 else: newsheet = 0 if newsheet: sd = chain.sheet2D['ssSheet2D'] # then create a pointer to the sheet2D for each secondary structures. ssSet.sheet2D = sd if sd is None : continue # Do the extrusion ONLY for the ss having a residue in the # selection removeSS =[] faces=[] vertices=[] normals=[] #from PmvApp.selectionCommands import sets__ name = "SS"+chain.id g = mol.geomContainer.geoms[name] for SS in ssSet: # test here if all the residues of the sselt are # in the residue set used # to compute the sheet2D. if not remove the ss. if SS.sheet2D is None: continue if [x for x in SS.residues if not x in SS.sheet2D.resInSheet]: self.app().warningMsg("%s: Removing %s from secondary structure set (%s). One or more residues doesn't have CA and O"%(self.name, SS.name, mol.name)) # remove the SS from the set and etc.... #delattr(SS.residues, 'secondarystructure') #ssSet.remove(SS) removeSS.append(SS) #name = "%s%s"%(SS.name, SS.chain.id) #del self.app().sets[mol.name+':'+name[-1]+':'+name[:-1]] #del sets__[mol.name+':'+name[-1]+':'+name[:-1]] #g = mol.geomContainer.geoms[name] #g.protected = False #if self.app().hasGui:self.app().GUI.VIEWER.RemoveObject(g) continue name = "%s%s"%(SS.name, SS.chain.id) if not SS in selectionSS: continue if isinstance(SS, Strand): arrowf = arrow else: arrowf = 0 if not shape2 is None: if SS.__class__.__name__ in ['Strand', 'Helix']: SS.exElt = ExtrudeSSElt(SS,shape1,gapEnd , gapBeg, frontcap, endcap, arrowf,larrow) elif SS.__class__.__name__ in ['Coil', 'Turn']: if chain.ribbonType()=='NA': NAp = self.app().Nucleic_Acids_properties sc = max(NAp.scale_pyrimidine, NAp.scale_purine) shape2 = Circle2D(radius=sc/2.5) SS.exElt = ExtrudeSSElt(SS,shape2, gapEnd, gapBeg, frontcap, endcap, arrowf) else: SS.exElt = ExtrudeSSElt(SS, shape1, gapEnd , gapBeg, frontcap, endcap, arrowf, larrow) resfaces, resfacesDict = SS.exElt.getExtrudeResidues(SS.residues) #g = mol.geomContainer.geoms[name] ## # MS triangulate faces ## trifaces = [] ## for f in resfaces: ## trifaces.append( (f[0],f[1],f[3]) ) ## if f[2]!=f[3]: ## trifaces.append( (f[1],f[2],f[3]) ) # highlight selection g.resfacesDict = resfacesDict highlight = [] if lHighlight is True:# and chain in residueSet : highlight = [0]*len(SS.exElt.vertices) for lResidue in molSelectedResiduesDict[mol]: if resfacesDict.has_key(lResidue): for lFace in resfacesDict[lResidue]: for lVertexIndex in lFace: highlight[int(lVertexIndex)] = 1 faces.extend(numpy.array(resfaces)+len(vertices)) vertices.extend(SS.exElt.vertices) normals.extend(SS.exElt.vnormals) if chain.ribbonType()=='NA': geom_bases = Add_Nucleic_Bases(g, self.app().Nucleic_Acids_properties) event = AddGeometryEvent(geom_bases, parent=g, redo=False) self.app.eventHandler.dispatchEvent(event) if geom_bases not in g.children: g.children.append(geom_bases) geom_bases.parent = g #geom_bases.fullName = g.fullName+'|'+geom_bases.name g.Set(vertices=vertices, highlight=highlight, faces=faces, vnormals=normals, redo=0, tagModified=False) for SS in removeSS: delattr(SS.residues, 'secondarystructure') ssSet.remove(SS) atoms = chain.findType(Atom) self.app().bindGeomToMolecularFragment(g, atoms) self.app()._executionReport.addSuccess('extruded SS for molecule %s successfully'% mol.name, obj=residues) except: msg = 'Error while extruding SS for molecule %s'%mol.name self.app().errorMsg(sys.exc_info(), msg, obj=residues) if display: kw = {} if kw.get('only', 0): kw['only'] = 1 kw['negate'] = negate #print "calling displayExtrudedSS with ", kw apply(self.app().displayExtrudedSS,(nodes,), kw) class DisplayExtrudedSSCommand(DisplayCommand): """ The DisplaySSCommand displays the geometries representing the secondary structure elements of the current selection.To execute this command use the 'Display Secondary Structure' entry under the 'Display' menu in the menu bar. \n Package : PmvApp \n Module : secondaryStructureCmds \n Class : DisplayExtrudedSSCommand \n Command name : displaySecondaryStructure \n Synopsis:\n None <- displaySecondaryStructure(nodes, only=False, negate=False) \n Required Arguments:\n nodes --- TreeNodeSet holding the current selection \n Optional Arguments:\n only --- allows the user to display only the current selection when set to 1 \n negate --- allows to undisplay the current selection when set to 1. \n This command is undoable. """ def onAddCmdToApp(self): self.app().lazyLoad("secondaryStructureCmds", commands=['computeSecondaryStructure', 'extrudeSecondaryStructure'], package="PmvApp") self.app().lazyLoad("extrusionCmds", commands=['computeSheet2D'], package="PmvApp") self.app().eventHandler.registerListener(AfterDeleteAtomsEvent, self.handleAfterDeleteAtoms) def handleAfterDeleteAtoms(self, event): """Function to update geometry objects created by this command upon atom deletion. \nevent --- instance of a VFEvent object """ # split event.objects into atoms sets per molecule molecules, ats = self.app().getNodesByMolecule(event.objects) # loop over molecules to update geometry objects for mol, atomSet in zip(molecules, ats): #if no backbone atoms are deleted ss does not change if len(atomSet.get("backbone")) == 0: continue for atom in atomSet.get("CA"): atom.parent.hasCA = False atom.parent.CAatom = None for atom in atomSet.get("O"): atom.parent.hasO = False atom.parent.Oatom = None if not mol.geomContainer.geoms.has_key('secondarystructure'): continue kw = mol.geomContainer.geoms['secondarystructure'].kw.copy() #cleanup SS atomset in geomcontainer self.app().computeSecondaryStructure.clean(mol) #this for molparser.hasSsDataInFile to trurn false while 'HELIX' in mol.parser.keys: mol.parser.keys.remove('HELIX') while 'SHEET' in mol.parser.keys: mol.parser.keys.remove('SHEET') while 'TURN' in mol.parser.keys: mol.parser.keys.remove('TURN') for chain in mol.chains: chain.ribbonType(noCache=True) #mol.hasSS = False mol.secondaryStructureFromPross() mol.__hasSSGeom=0 self.app().extrudeSecondaryStructure(mol, display=0) self(mol, **kw) ## def undoCmdBefore(self, nodes, only=False, negate=False, **kw): ## if len(nodes)==0 : return ## #molecules = nodes.top.uniq() ## molecules, residueSets = self.getNodes(nodes) ## #for mol, res in map(None, molecules, residueSets): ## negateCmds = [] ## for mol in molecules: ## resWithSS = mol.findType(Residue).get( ## lambda x:hasattr(x,'secondarystructure')) ## if resWithSS is None: ## continue ## SSinMol = resWithSS.secondarystructure.uniq() ## #resWithSS = res.get(lambda x: hasattr(x,'secondarystructure')) ## #SSinSel = resWithSS.secondarystructure.uniq() ## #mol.geomContainer.atoms['secondarystructure']=resWithSS.atoms ## set = ResidueSet() ## if mol.geomContainer.geoms.has_key('SS'): ## for ch in mol.chains : ## set = set + mol.geomContainer.atoms['SS'+ch.id].parent ## if len(set)==0: # nothing is displayed ## negateCmds.append((self, (mol,), {'negate':True, 'redraw':True},)) ## else: ## negateCmds.append((self, (set,), {'only':True, 'redraw':True}) ) ## else : ## for ss in SSinMol: ## set = set + mol.geomContainer.atoms[ss.name+ss.chain.id] ## if len(set)==0: # nothing is displayed ## negateCmds.append((self, (mol,), {'negate':True, 'redraw':True})) ## else: ## negateCmds.append((self, (set,), {'only':True, 'redraw':True})) ## if len(negateCmds): ## return (negateCmds, self.name) def doit(self, nodes, only=False, negate=False, redraw=True): """ displays the secondary structure for the selected treenodes """ #print self.name, "in display with only=", only, " and negate=", negate ############################################################### def drawResidues(SS, res, only, negate, uniq=False): mol = SS.chain.parent name = '%s%s'%(SS.name, SS.chain.id) _set = mol.geomContainer.atoms[name] inres = [x for x in _set if not x in res] if len(inres) == 0: # res and _set are the same if negate: _set = ResidueSet() setOff = res setOn = None else: _set = res setOff = None setOn = res else: # if negate, remove current res from displayed _set if negate : setOff = res setOn = None _set = _set - res else: # if only, replace displayed _set with current res if only: setOff = _set - res setOn = res _set = res else: _set = res.union(_set) setOff = None setOn = _set ## # if negate, remove current res from displayed _set ## if negate : ## _set = _set - res ## else: # if only, replace displayed _set with current res ## if only: ## _set = res ## else: ## _set = res.union(_set) ## # now, update the geometries: ## if len(_set)==0: ## mol.geomContainer.geoms[name].Set(visible=0, tagModified=False) ## mol.geomContainer.atoms[name] = ResidueSet() ## return #the rest is done only if there are some residues mol.geomContainer.setAtomsForGeom(name, _set) #print _set if not hasattr(SS, 'exElt'): return setOn, setOff if isinstance(SS, Coil): gapBefore = SS.gapBefore gapAfter = SS.gapAfter else: gapBefore = gapAfter = False resfaces, resfacesDict = SS.exElt.getExtrudeResidues( _set, gapBefore, gapAfter) ## # MS triangulate faces ## trifaces = [] ## for f in resfaces: ## trifaces.append( (f[0],f[1],f[3]) ) ## if f[2]!=f[3]: ## trifaces.append( (f[1],f[2],f[3]) ) ## g.Set(faces=trifaces, vnormals=SS.exElt.vnormals, if uniq: return setOn, setOff, resfaces, SS.exElt.vnormals, \ SS.exElt.vertices g = mol.geomContainer.geoms[name] col = mol.geomContainer.getGeomColor(name) g.Set(faces=resfaces, vnormals=SS.exElt.vnormals, visible=1, materials=col, inheritMaterial=False, tagModified=False) if SS.chain.ribbonType()=='NA': faces = [] colors = [] for residue in _set: faces.extend(residue._base_faces) colors.extend(residue._coil_colors) try: atm = residue.atoms.get('CA')[0] except: atm = residue.atoms[0] if len(residue._coil_colors) : atm.colors["secondarystructure"] = residue._coil_colors[0]#?? else: atm.colors["secondarystructure"] = residue._coil_colors g.children[0].Set(faces=faces) if colors: g.Set(materials=colors, inheritMaterial=False) if self.app().Nucleic_Acids_properties.color_backbone: g.Set(inheritMaterial=False) else: g.Set(inheritMaterial=True) mol.geomContainer.atoms['Bases'] = ResidueSet() #mol.geomContainer.atoms[name] = ResidueSet() return setOn, setOff ############################################################### molecules, residueSets = self.app().getNodesByMolecule(nodes, Residue) setOn = ResidueSet([]) setOff = ResidueSet([]) for mol, residues in map(None, molecules, residueSets): try: if not mol.hasSS: self.app().computeSecondaryStructure(mol) self.app().extrudeSecondaryStructure(mol, display=0) reswithss = residues.get(lambda x: hasattr(x,'secondarystructure')) if reswithss is None: raise RuntimeError, '%s: no secondary structure in specified nodes of %s molecule' % (self.name, mol.name) SSInSel = reswithss.secondarystructure.uniq() chainsInSel = residues.parent.uniq() for c in mol.chains: if not hasattr(c, 'secondarystructureset'): continue if not hasattr(c, 'sheet2D'): self.app().warningMsg("%s: chain '%s'(%s) does not have a sheet2D computed"%(self.name, c.full_name(), mol.name)) continue elif (c.sheet2D.has_key('ssSheet2D') and \ c.sheet2D['ssSheet2D'] is None): continue if mol.geomContainer.geoms.has_key('SS') : faces=[] vertices=[] normals=[] name = "SS"+c.id g = mol.geomContainer.geoms[name] SS, resInSS = self.getResiduesBySS(residues, c) for s in xrange(len(c.secondarystructureset)): ss = c.secondarystructureset[s] res = resInSS[s] if ss in SSInSel and not hasattr(ss, 'exElt') \ and negate == 0: self.app().extrudeSecondaryStructure(res, display=0) if mol.geomContainer.geoms.has_key('SS') : son, sof, f, n, v = drawResidues(ss, res, only , negate ,uniq=True) faces.extend(numpy.array(f)+len(v)) vertices.extend(v) normals.extend(n) else : son, sof = drawResidues(ss, res, only , negate ) if son: setOn += son if sof: setOff += sof if mol.geomContainer.geoms.has_key('SS') : g.Set(visible=not negate) kw = {"only":only, "negate":negate} if mol.geomContainer.geoms.has_key('secondarystructure'): mol.geomContainer.geoms['secondarystructure'].kw = kw self.app()._executionReport.addSuccess('displayed secondary structure for molecule %s successfully'% mol.name, obj=residues) except: msg = 'Error while displaying secondary structure for molecule %s'%mol.name self.app().errorMsg(sys.exc_info(), msg, obj=residues) event = EditGeomsEvent('SSdisplay', [nodes,[only, negate,redraw]], setOn=setOn, setOff=setOff) self.app().eventHandler.dispatchEvent(event) def checkArguments(self, nodes, only=False, negate=False, redraw=True): """ Required Arguments:\n nodes --- TreeNodeSet holding the current selection \n Optional Arguments:\n only --- flag when set to 1 only the current selection will be displayed as secondarystructures \n negate --- flag when set to 1 undisplay the current selection""" if isinstance(nodes, str): self.nodeLogString = "'"+nodes+"'" nodes = self.app().expandNodes(nodes) kw = {} assert only in [True, False, 1, 0] assert negate in [True, False, 1, 0] kw['only'] = only kw['negate'] = negate kw['redraw']=redraw return (nodes,),kw def getResiduesBySS(self, residues, chain): resWithSS = residues.get(lambda x: hasattr(x, 'secondarystructure')) residuesInSS = [] for ss in chain.secondarystructureset : res = resWithSS.get(lambda x, ss=ss:x.secondarystructure==ss) if res is None: res = ResidueSet() residuesInSS.append(res) return chain.secondarystructureset, residuesInSS class UndisplayExtrudedSSCommand(DisplayCommand): """ UndisplaySSCommand is an interactive command to undisplay part of the molecule when represented as extruded secondary structure. \n Package : PmvApp \n Module : secondaryStructureCmds \n Class : UndisplayExtrudedSSCommand \n Command name : undisplaySecondaryStructure \n Synopsis:\n None <--- undisplaySecondaryStructure(nodes, **kw) \n Required Arguments:\n nodes --- TreeNodeSet holding the current selection """ def onAddCmdToApp(self): if not self.app().commands.has_key('displayExtrudedSS'): self.app().lazyLoad('secondaryStructureCmds', commands=['displayExtrudedSS'], package='PmvApp') def checkArguments(self, nodes, **kw): """ nodes --- TreeNodeSet holding the current selection """ if isinstance(nodes, str): self.nodeLogString = "'"+nodes+"'" nodes = self.app().expandNodes(nodes) kw = {'negate':1} return (nodes,), kw def doit(self, nodes, **kw): self.app().displayExtrudedSS(nodes, **kw) class RibbonCommand(MVCommand): """ The RibbonCommand is a shortcut to visualize a traditional Ribbon representation of the current selection. It first executes getSSCommand then the extrudeSSCommand with the default values for all the parameters. This command is undoable. \n Package : PmvApp \n Module : secondaryStructureCmds \n Class : RibbonCommand \n Command name : ribbon \n Synopsis:\n None <- ribbon(nodes, only=False, negate=False) \n Required Arguments:\n nodes --- TreeNodeSet holding the current selection \n Optional Arguments:\n only --- flag when set to 1 only the current selection will be displayed \n negate --- flag when set to 1 undisplay the current selection """ def __init__(self): MVCommand.__init__(self) #self.flag = self.flag | self.objArgOnly #self.flag = self.flag | self.negateKw def undoCmdBefore(self, *args, **kw): return None # this prevents this function from trying to create a negation # command since it only calls other VFCommands who can negate themselves def onAddCmdToApp(self): self.app().lazyLoad("secondaryStructureCmds", commands=['extrudeSecondaryStructure', 'displayExtrudedSS', 'computeSecondaryStructure'], package="PmvApp") def checkArguments(self, nodes, shape1=None, shape2=None, frontcap=True, endcap=True, arrow=True, nbchords=8, gapBeg=0, gapEnd=0, larrow=2, display=True, redraw=True, width=1.2, height=0.2, radius=0.1, updateNucleicAcidsPropertiesGUI=False, only=True, negate=False): """Required Arguments:\n nodes --- TreeNodeSet holding the current selection (mv.getSelection()) \n Optional Arguments (will be passed to extrudeSecondaryStructure() ):\n shape1 & shape2 --- DejaVu2.Shapes.Shape2D objects. shape1 will be used to \n represent the helix and strand, shape2 to represent coils and\n turns.\n frontcap & endcap --- Boolean flag when set to True a cap will be added to the \n geom either at the front or at the end \n arrow --- Boolean flag when set to True an arow will be added to the \n geometry representing the strand. \n nbchords --- Nb of points per residues in the smooth array \n gapBeg& gapEnd --- defines gap at the beginning or the end of each residue. \n larrow --- length of the arrow if arrow boolean flag set to 1 \n display --- Boolean flag when set to True the displaySecondaryStructure is called automatically \n only --- flag when set to 1 only the current selection will be displayed \n negate --- flag when set to 1 undisplay the current selection \n width, height, radius --- if shape1 is not specified, these parameters \n are used to create shape1 (Rectangle2D(withd, height)) \n and shape2 (Circle2D(radius)) """ if isinstance (nodes, str): self.nodeLogString = "'"+nodes+"'" nodes = self.app().expandNodes(nodes) assert isinstance(nbchords, int) assert gapEnd<=len(nodes) assert gapBeg<=len(nodes) if shape1: assert isinstance(shape1 , Shape2D) if shape2: assert isinstance(shape2 , Shape2D) assert frontcap in (True,False, 1, 0) assert endcap in (True, False, 1, 0) assert arrow in (True, False, 1, 0) assert display in (True, False, 1, 0) assert isinstance (larrow, (int, float)) assert isinstance (width, (int, float)) assert isinstance (height, (int, float)) assert isinstance (radius, (int, float)) kw = {} kw['shape1'] = shape1 kw['shape2'] = shape2 kw['frontcap'] = frontcap kw['endcap'] = endcap kw['arrow'] = arrow kw['nbchords'] = nbchords kw['gapBeg'] = gapBeg kw['gapEnd'] = gapEnd kw['larrow'] = larrow kw['display'] = display kw['width'] = width kw['height'] = height kw['radius'] = radius kw['updateNucleicAcidsPropertiesGUI'] = updateNucleicAcidsPropertiesGUI kw['only'] = only kw['negate'] = negate kw['redraw']=redraw #print "kw.has_key('only')=", kw.has_key('only') #print kw.get('only', 'no_value') return (nodes,), kw def doit(self, nodes, only=False, negate=False, redraw=True, **kw): self.app().computeSecondaryStructure( nodes) kw.update({'only':only, 'negate':negate}) #print self.name, "doit:", kw self.app().extrudeSecondaryStructure( nodes, **kw) class ColorBySSElementType(ColorFromPalette): """Command to color the given geometry by secondary structure element. (Rasmol color code) \n Package : PmvApp \n Module : secondaryStructureCmds \n Class : ColorBySSElementType """ def onAddCmdToApp(self): from PmvApp.pmvPalettes import SecondaryStructureType c = 'Color palette for secondary structure element type:' self.palette = ColorPalette( 'SecondaryStructureType', SecondaryStructureType, info=c, lookupMember = 'structureType') if not self.app().commands.has_key('color'): self.app().lazyLoad('colorCmds', ['color'], 'PmvApp') self.undoCmdsString= self.app().color.name def getColors(self, nodes): res = nodes.findType(Residue) resWithSS = res.get(lambda x: hasattr(x, 'secondarystructure')) if resWithSS is None: return None, None return resWithSS, self.palette.lookup(resWithSS.secondarystructure) def getNodes(self, nodes, returnNodes=False): """expand nodes argument into a list of atoms and a list of molecules.""" nodes = self.app().expandNodes(nodes) res = nodes.findType(Residue).uniq() resWithSS = res.get(lambda x: hasattr(x,'secondarystructure')) if resWithSS is None or len(resWithSS)==0: atoms = AtomSet() molecules = ProteinSet() else: atoms = resWithSS.atoms molecules= resWithSS.top.uniq() if returnNodes: return molecules, atoms, nodes else: return molecules, atoms def doit(self, nodes, geomsToColor): # this command do not require the color argument since colors are # gotten from a palette # we still can use the ColorCommand.undoCmdBefore but first we get # the colors. This also insures that the colors are not put inside the # command's log string #print self.name , "geomsToColor", geomsToColor #nodes is AtomSet resWithSS, colors = self.getColors(nodes) if colors is None: return for g in geomsToColor: if len(colors)==1 or len(colors)!=len(nodes): for a in nodes: a.colors[g] = tuple( colors[0] ) else: for a, c in map(None, nodes, colors): a.colors[g] = tuple(c) updatedGeomsToColor = [] for mol in self.molSet: try: for gName in geomsToColor: if not mol.geomContainer.geoms.has_key(gName): continue geom = mol.geomContainer.geoms[gName] if geom.children != []: # get geom Name: childrenNames = [x.name for x in geom.children] updatedGeomsToColor = updatedGeomsToColor + childrenNames for childGeom in geom.children: childGeom.Set(inheritMaterial=0, redo=0, tagModified=False) else: updatedGeomsToColor.append(gName) geom.Set(inheritMaterial=0, redo=0, tagModified=False) mol.geomContainer.updateColors(updatedGeomsToColor) self.app()._executionReport.addSuccess('%s: colored molecule %s successfully'% (self.name, mol.name)) except: msg = 'Error while coloring secondary structure for molecule %s'% mol.name self.app().errorMsg(sys.exc_info(), msg, obj=self.atmSet) #geomEditEventss event = EditGeomsEvent("color", [nodes,[geomsToColor, colors, self.name[5:11]]]) self.app().eventHandler.dispatchEvent(event) commandClassFromName = { 'computeSecondaryStructure' : [ComputeSecondaryStructureCommand, None], 'extrudeSecondaryStructure' : [ExtrudeSecondaryStructureCommand, None], 'extrudeSecondaryStructureUnic' : [ExtrudeSecondaryStructureCommandUnic, None], 'displayExtrudedSS' : [DisplayExtrudedSSCommand, None], 'colorBySecondaryStructure' : [ColorBySSElementType, None], 'undisplayExtrudedSS' : [UndisplayExtrudedSSCommand, None], 'ribbon' : [RibbonCommand, None], } def initModule(viewer, gui=False): for cmdName, values in commandClassFromName.items(): cmdClass, guiInstance = values viewer.addCommand(cmdClass(), cmdName, guiInstance)
46.741431
1,042
0.523935
4ac6c95e47f7e0c117f8f3e7d54da78c9fea5a88
32,265
py
Python
truffe2/accounting_tools/migrations/0026_auto__del_field_invoice_unit__del_field_cashbook_unit__del_field_withd.py
JonathanCollaud/truffe2
5cbb055ac1acf7e7dc697340618fcb56c67fbd91
[ "BSD-2-Clause" ]
9
2016-09-14T02:19:19.000Z
2020-10-18T14:52:14.000Z
truffe2/accounting_tools/migrations/0026_auto__del_field_invoice_unit__del_field_cashbook_unit__del_field_withd.py
JonathanCollaud/truffe2
5cbb055ac1acf7e7dc697340618fcb56c67fbd91
[ "BSD-2-Clause" ]
19
2016-11-09T21:28:51.000Z
2021-02-10T22:37:31.000Z
truffe2/accounting_tools/migrations/0026_auto__del_field_invoice_unit__del_field_cashbook_unit__del_field_withd.py
JonathanCollaud/truffe2
5cbb055ac1acf7e7dc697340618fcb56c67fbd91
[ "BSD-2-Clause" ]
13
2016-12-31T14:22:09.000Z
2020-12-27T19:43:19.000Z
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Invoice.unit' db.delete_column(u'accounting_tools_invoice', 'unit_id') # Deleting field 'CashBook.unit' db.delete_column(u'accounting_tools_cashbook', 'unit_id') # Deleting field 'Withdrawal.unit' db.delete_column(u'accounting_tools_withdrawal', 'unit_id') def backwards(self, orm): # Adding field 'Invoice.unit' db.add_column(u'accounting_tools_invoice', 'unit', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['units.Unit']), keep_default=False) # Adding field 'CashBook.unit' db.add_column(u'accounting_tools_cashbook', 'unit', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['units.Unit']), keep_default=False) # Adding field 'Withdrawal.unit' db.add_column(u'accounting_tools_withdrawal', 'unit', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['units.Unit']), keep_default=False) models = { u'accounting_core.account': { 'Meta': {'unique_together': "(('name', 'accounting_year'), ('account_number', 'accounting_year'))", 'object_name': 'Account'}, 'account_number': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountCategory']"}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'visibility': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'accounting_core.accountcategory': { 'Meta': {'unique_together': "(('name', 'accounting_year'),)", 'object_name': 'AccountCategory'}, 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'order': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'parent_hierarchique': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountCategory']", 'null': 'True', 'blank': 'True'}) }, u'accounting_core.accountingyear': { 'Meta': {'object_name': 'AccountingYear'}, 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'end_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_accounting_import': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'0_preparing'", 'max_length': '255'}), 'subvention_deadline': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, u'accounting_core.costcenter': { 'Meta': {'unique_together': "(('name', 'accounting_year'), ('account_number', 'accounting_year'))", 'object_name': 'CostCenter'}, 'account_number': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'unit': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['units.Unit']"}) }, u'accounting_tools.cashbook': { 'Meta': {'object_name': 'CashBook'}, 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}), 'costcenter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.CostCenter']"}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'nb_proofs': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'0_draft'", 'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.cashbookfile': { 'Meta': {'object_name': 'CashBookFile'}, 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'files'", 'null': 'True', 'to': u"orm['accounting_tools.CashBook']"}), 'upload_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'uploader': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.cashbookline': { 'Meta': {'object_name': 'CashBookLine'}, 'account': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.Account']"}), 'cashbook': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'lines'", 'to': u"orm['accounting_tools.CashBook']"}), 'date': ('django.db.models.fields.DateField', [], {}), 'helper': ('django.db.models.fields.CharField', [], {'max_length': '15'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'order': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'proof': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'tva': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}), 'value': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}), 'value_ttc': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}) }, u'accounting_tools.cashbooklogging': { 'Meta': {'object_name': 'CashBookLogging'}, 'extra_data': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'logs'", 'to': u"orm['accounting_tools.CashBook']"}), 'what': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'who': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.expenseclaim': { 'Meta': {'object_name': 'ExpenseClaim'}, 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'costcenter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.CostCenter']"}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'nb_proofs': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'0_draft'", 'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.expenseclaimfile': { 'Meta': {'object_name': 'ExpenseClaimFile'}, 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'files'", 'null': 'True', 'to': u"orm['accounting_tools.ExpenseClaim']"}), 'upload_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'uploader': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.expenseclaimline': { 'Meta': {'object_name': 'ExpenseClaimLine'}, 'account': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.Account']"}), 'expense_claim': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'lines'", 'to': u"orm['accounting_tools.ExpenseClaim']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'order': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'proof': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'tva': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}), 'value': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}), 'value_ttc': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}) }, u'accounting_tools.expenseclaimlogging': { 'Meta': {'object_name': 'ExpenseClaimLogging'}, 'extra_data': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'logs'", 'to': u"orm['accounting_tools.ExpenseClaim']"}), 'what': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'who': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.internaltransfer': { 'Meta': {'object_name': 'InternalTransfer'}, 'account': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.Account']"}), 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}), 'cost_center_from': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'internal_transfer_from'", 'to': u"orm['accounting_core.CostCenter']"}), 'cost_center_to': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'internal_transfer_to'", 'to': u"orm['accounting_core.CostCenter']"}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'0_draft'", 'max_length': '255'}) }, u'accounting_tools.internaltransferlogging': { 'Meta': {'object_name': 'InternalTransferLogging'}, 'extra_data': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'logs'", 'to': u"orm['accounting_tools.InternalTransfer']"}), 'what': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'who': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.internaltransfertag': { 'Meta': {'object_name': 'InternalTransferTag'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tags'", 'to': u"orm['accounting_tools.InternalTransfer']"}), 'tag': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'accounting_tools.invoice': { 'Meta': {'object_name': 'Invoice'}, 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'address': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'annex': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'costcenter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.CostCenter']"}), 'custom_bvr_number': ('django.db.models.fields.CharField', [], {'max_length': '59', 'null': 'True', 'blank': 'True'}), 'date_and_place': ('django.db.models.fields.CharField', [], {'max_length': '512', 'null': 'True', 'blank': 'True'}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'display_account': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'display_bvr': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'ending': ('django.db.models.fields.TextField', [], {'max_length': '1024', 'null': 'True', 'blank': 'True'}), 'greetings': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'preface': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'sign': ('django.db.models.fields.CharField', [], {'max_length': '512', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'0_preparing'", 'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'accounting_tools.invoiceline': { 'Meta': {'object_name': 'InvoiceLine'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invoice': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'lines'", 'to': u"orm['accounting_tools.Invoice']"}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'order': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'quantity': ('django.db.models.fields.DecimalField', [], {'default': '1', 'max_digits': '20', 'decimal_places': '0'}), 'tva': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}), 'value': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}), 'value_ttc': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}) }, u'accounting_tools.invoicelogging': { 'Meta': {'object_name': 'InvoiceLogging'}, 'extra_data': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'logs'", 'to': u"orm['accounting_tools.Invoice']"}), 'what': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'who': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.invoicetag': { 'Meta': {'object_name': 'InvoiceTag'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tags'", 'to': u"orm['accounting_tools.Invoice']"}), 'tag': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'accounting_tools.linkedinfo': { 'Meta': {'object_name': 'LinkedInfo'}, 'address': ('django.db.models.fields.TextField', [], {}), 'bank': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'iban_ccp': ('django.db.models.fields.CharField', [], {'max_length': '128'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'user_pk': ('django.db.models.fields.PositiveIntegerField', [], {}) }, u'accounting_tools.subvention': { 'Meta': {'unique_together': "(('unit', 'unit_blank_name', 'accounting_year'),)", 'object_name': 'Subvention'}, 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'amount_asked': ('django.db.models.fields.IntegerField', [], {}), 'amount_given': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'comment_root': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'kind': ('django.db.models.fields.CharField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}), 'mobility_asked': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'mobility_given': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'0_draft'", 'max_length': '255'}), 'unit': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['units.Unit']", 'null': 'True', 'blank': 'True'}), 'unit_blank_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'unit_blank_user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']", 'null': 'True', 'blank': 'True'}) }, u'accounting_tools.subventionfile': { 'Meta': {'object_name': 'SubventionFile'}, 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'files'", 'null': 'True', 'to': u"orm['accounting_tools.Subvention']"}), 'upload_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'uploader': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.subventionline': { 'Meta': {'object_name': 'SubventionLine'}, 'end_date': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'nb_spec': ('django.db.models.fields.SmallIntegerField', [], {}), 'order': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'place': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'subvention': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'events'", 'to': u"orm['accounting_tools.Subvention']"}) }, u'accounting_tools.subventionlogging': { 'Meta': {'object_name': 'SubventionLogging'}, 'extra_data': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'logs'", 'to': u"orm['accounting_tools.Subvention']"}), 'what': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'who': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.withdrawal': { 'Meta': {'object_name': 'Withdrawal'}, 'accounting_year': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.AccountingYear']"}), 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '20', 'decimal_places': '2'}), 'costcenter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['accounting_core.CostCenter']"}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'desired_date': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'0_draft'", 'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}), 'withdrawn_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}) }, u'accounting_tools.withdrawalfile': { 'Meta': {'object_name': 'WithdrawalFile'}, 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'files'", 'null': 'True', 'to': u"orm['accounting_tools.Withdrawal']"}), 'upload_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'uploader': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.withdrawallogging': { 'Meta': {'object_name': 'WithdrawalLogging'}, 'extra_data': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'logs'", 'to': u"orm['accounting_tools.Withdrawal']"}), 'what': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'who': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'accounting_tools.withdrawaltag': { 'Meta': {'object_name': 'WithdrawalTag'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tags'", 'to': u"orm['accounting_tools.Withdrawal']"}), 'tag': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'units.unit': { 'Meta': {'object_name': 'Unit'}, 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'id_epfl': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'is_commission': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_equipe': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'parent_hierarchique': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['units.Unit']", 'null': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'users.truffeuser': { 'Meta': {'object_name': 'TruffeUser'}, 'adresse': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'body': ('django.db.models.fields.CharField', [], {'default': "'.'", 'max_length': '1'}), 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '255'}), 'email_perso': ('django.db.models.fields.EmailField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), 'iban_ou_ccp': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '25', 'blank': 'True'}), 'nom_banque': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) } } complete_apps = ['accounting_tools']
82.308673
195
0.571083
83dc32f5197cacb81dec4d373e0ef0bdac36eb85
15,976
py
Python
src/map_model.py
akolishchak/doom-net-pytorch
96bad5b15c9c5267d494cd5791481801cd6d2107
[ "MIT" ]
143
2017-01-30T01:43:58.000Z
2021-11-15T07:53:22.000Z
src/map_model.py
akolishchak/doom-net-pytorch
96bad5b15c9c5267d494cd5791481801cd6d2107
[ "MIT" ]
7
2017-12-28T02:42:08.000Z
2020-05-23T23:12:33.000Z
src/map_model.py
akolishchak/doom-net-pytorch
96bad5b15c9c5267d494cd5791481801cd6d2107
[ "MIT" ]
27
2017-02-03T09:20:10.000Z
2020-07-19T21:35:28.000Z
# # map_model.py, doom-net # # Created by Andrey Kolishchak on 03/03/18. # import torch.nn as nn import torch.nn.functional as F class ObjectModel(nn.Module): def __init__(self, args): super().__init__() self.conv1 = nn.Conv2d(3, 16, kernel_size=7, stride=(1, 1), dilation=(1, 1), padding=(0, 3)) self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=(2, 1), dilation=(2, 1), padding=(0, 1)) self.conv3 = nn.Conv2d(32, 64, kernel_size=3, stride=(2, 1), dilation=(4, 1), padding=(0, 1)) self.conv4 = nn.Conv2d(64, 128, kernel_size=3, stride=(2, 1), dilation=(8, 1), padding=(0, 1)) self.conv5 = nn.Conv2d(128, 256, kernel_size=3, stride=(2, 1), dilation=(6, 1), padding=(0, 1)) self.conv6 = nn.Conv2d(256, 6, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 1)) self.bn1 = nn.BatchNorm2d(16) self.bn2 = nn.BatchNorm2d(32) self.bn3 = nn.BatchNorm2d(64) self.bn4 = nn.BatchNorm2d(128) self.bn5 = nn.BatchNorm2d(256) def forward(self, screen): output = self.conv1(screen) output = self.bn1(output) output = F.relu(output, inplace=True) output = self.conv2(output) output = self.bn2(output) output = F.relu(output, inplace=True) output = self.conv3(output) output = self.bn3(output) output = F.relu(output, inplace=True) output = self.conv4(output) output = self.bn4(output) output = F.relu(output, inplace=True) output = self.conv5(output) output = self.bn5(output) output = F.relu(output, inplace=True) output = self.conv6(output) return output class DistanceModel(nn.Module): def __init__(self, args): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=7, stride=(1, 1), dilation=(1, 1), padding=(0, 3)) self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=(2, 1), dilation=(2, 1), padding=(0, 1)) self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=(2, 1), dilation=(4, 1), padding=(0, 1)) self.conv4 = nn.Conv2d(128, 256, kernel_size=3, stride=(2, 1), dilation=(8, 1), padding=(0, 1)) self.conv5 = nn.Conv2d(256, 512, kernel_size=3, stride=(2, 1), dilation=(6, 1), padding=(0, 1)) self.conv6 = nn.Conv2d(512, 129, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 1)) self.bn1 = nn.BatchNorm2d(32) self.bn2 = nn.BatchNorm2d(64) self.bn3 = nn.BatchNorm2d(128) self.bn4 = nn.BatchNorm2d(256) self.bn5 = nn.BatchNorm2d(512) def forward(self, screen): output = self.conv1(screen) output = self.bn1(output) output = F.relu(output, inplace=True) output = self.conv2(output) output = self.bn2(output) output = F.relu(output, inplace=True) output = self.conv3(output) output = self.bn3(output) output = F.relu(output, inplace=True) output = self.conv4(output) output = self.bn4(output) output = F.relu(output, inplace=True) output = self.conv5(output) output = self.bn5(output) output = F.relu(output, inplace=True) output = self.conv6(output) return output class ObjectDistanceModel(nn.Module): def __init__(self, args): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=7, stride=(1, 1), dilation=(1, 1), padding=(0, 3)) self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=(2, 1), dilation=(2, 1), padding=(0, 1)) self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=(2, 1), dilation=(4, 1), padding=(0, 1)) self.conv4 = nn.Conv2d(128, 256, kernel_size=3, stride=(2, 1), dilation=(8, 1), padding=(0, 1)) self.conv51 = nn.Conv2d(256, 512, kernel_size=3, stride=(2, 1), dilation=(6, 1), padding=(0, 1)) self.conv52 = nn.Conv2d(256, 512, kernel_size=3, stride=(2, 1), dilation=(6, 1), padding=(0, 1)) self.conv61 = nn.Conv2d(512, 6, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 1)) self.conv62 = nn.Conv2d(512, 129, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 1)) self.bn1 = nn.BatchNorm2d(32) self.bn2 = nn.BatchNorm2d(64) self.bn3 = nn.BatchNorm2d(128) self.bn4 = nn.BatchNorm2d(256) self.bn51 = nn.BatchNorm2d(512) self.bn52 = nn.BatchNorm2d(512) def forward(self, screen): shared = self.conv1(screen) shared = self.bn1(shared) shared = F.relu(shared, inplace=True) shared = self.conv2(shared) shared = self.bn2(shared) shared = F.relu(shared, inplace=True) shared = self.conv3(shared) shared = self.bn3(shared) shared = F.relu(shared, inplace=True) shared = self.conv4(shared) shared = self.bn4(shared) shared = F.relu(shared, inplace=True) output1 = self.conv51(shared) output1 = self.bn51(output1) output1 = F.relu(output1, inplace=True) output1 = self.conv61(output1) output2 = self.conv52(shared) output2 = self.bn52(output2) output2 = F.relu(output2, inplace=True) output2 = self.conv62(output2) return output1, output2 class DistanceModel2(nn.Module): def __init__(self, args): super().__init__() self.drn = drn.drn_d_22(out_map=True, num_classes=1) self.fc1 = nn.Linear(1*30*40, 320) def forward(self, screen): output = self.drn(screen) output = output.view(output.size(0), -1) #output = F.relu(output) output = self.fc1(output) output = F.sigmoid(output) return output class ObjectDistanceModel2(nn.Module): def __init__(self, args): super().__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=(1, 1), dilation=(1, 1), padding=(0, 3), bias=False) self.conv2 = nn.Conv2d(64, 128, kernel_size=3, stride=(2, 1), dilation=(2, 1), padding=(0, 1)) self.conv3 = nn.Conv2d(128, 256, kernel_size=3, stride=(2, 1), dilation=(4, 1), padding=(0, 1)) self.conv4 = nn.Conv2d(256, 512, kernel_size=3, stride=(2, 1), dilation=(8, 1), padding=(0, 1)) self.conv51 = nn.Conv2d(512, 1024, kernel_size=3, stride=(2, 1), dilation=(6, 1), padding=(0, 1)) self.conv52 = nn.Conv2d(512, 1024, kernel_size=3, stride=(2, 1), dilation=(6, 1), padding=(0, 1)) self.conv61 = nn.Conv2d(1024, 6, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 1)) self.conv62 = nn.Conv2d(1024, 129, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 1)) self.bn1 = nn.BatchNorm2d(64) self.bn2 = nn.BatchNorm2d(128) self.bn3 = nn.BatchNorm2d(256) self.bn4 = nn.BatchNorm2d(512) self.bn51 = nn.BatchNorm2d(1024) self.bn52 = nn.BatchNorm2d(1024) def forward(self, screen): shared = self.conv1(screen) shared = self.bn1(shared) shared = F.relu(shared, inplace=True) shared = self.conv2(shared) shared = self.bn2(shared) shared = F.relu(shared, inplace=True) shared = self.conv3(shared) shared = self.bn3(shared) shared = F.relu(shared, inplace=True) shared = self.conv4(shared) shared = self.bn4(shared) shared = F.relu(shared, inplace=True) output1 = self.conv51(shared) output1 = self.bn51(output1) output1 = F.relu(output1, inplace=True) output1 = self.conv61(output1) output2 = self.conv52(shared) output2 = self.bn52(output2) output2 = F.relu(output2, inplace=True) output2 = self.conv62(output2) return output1, output2 class BasicBlock(nn.Module): def __init__(self, inplanes, planes, stride=(1, 1), padding=(0, 0), dilation=(1, 1)): super(BasicBlock, self).__init__() self.padding = (padding[1], padding[1], padding[0], padding[0]) padding = (0, 0) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=padding, dilation=dilation) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=padding, dilation=dilation) self.bn2 = nn.BatchNorm2d(planes) self.downsample = None if stride != 1 or inplanes != planes: self.downsample = nn.Sequential( nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes), ) def forward(self, x): residual = x out = F.pad(x, self.padding, mode='replicate') out = self.conv1(out) out = self.bn1(out) out = self.relu(out) out = F.pad(out, self.padding, mode='replicate') out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class ObjectDistanceModel3(nn.Module): def __init__(self, args): super().__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=(1, 1), dilation=(1, 1), padding=(0, 0), bias=False) self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.conv3 = BasicBlock(64, 128, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv4 = BasicBlock(128, 128, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv5 = BasicBlock(128, 256, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv6 = BasicBlock(256, 256, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv71 = nn.Conv2d(256, 512, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.conv72 = nn.Conv2d(256, 512, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.conv81 = nn.Conv2d(512, 6, kernel_size=3, stride=(1, 1), dilation=(1, 1), padding=(0, 0)) self.conv82 = nn.Conv2d(512, 129, kernel_size=3, stride=(1, 1), dilation=(1, 1), padding=(0, 0)) self.bn1 = nn.BatchNorm2d(64) self.bn2 = nn.BatchNorm2d(64) self.bn71 = nn.BatchNorm2d(512) self.bn72 = nn.BatchNorm2d(512) def forward(self, screen): screen = F.pad(screen, (3, 3, 0, 0), mode='replicate') shared = self.conv1(screen) shared = self.bn1(shared) shared = F.relu(shared, inplace=True) shared = F.pad(shared, (1, 1, 0, 0), mode='replicate') shared = self.conv2(shared) shared = self.bn2(shared) shared = F.relu(shared, inplace=True) shared = self.conv3(shared) shared = self.conv4(shared) shared = self.conv5(shared) shared = self.conv6(shared) output1 = F.pad(shared, (1, 1, 0, 0), mode='replicate') output1 = self.conv71(output1) output1 = self.bn71(output1) output1 = F.relu(output1, inplace=True) output1 = F.pad(output1, (1, 1, 0, 0), mode='replicate') output1 = self.conv81(output1) output2 = F.pad(shared, (1, 1, 0, 0), mode='replicate') output2 = self.conv72(output2) output2 = self.bn72(output2) output2 = F.relu(output2, inplace=True) output2 = F.pad(output2, (1, 1, 0, 0), mode='replicate') output2 = self.conv82(output2) return output1, output2 class ObjectDistanceModel4(nn.Module): def __init__(self, args): super().__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=(1, 1), dilation=(1, 1), padding=(0, 0), bias=False) self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.conv3 = BasicBlock(64, 128, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv4 = BasicBlock(128, 128, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv5 = BasicBlock(128, 256, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv6 = BasicBlock(256, 256, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv71 = nn.Conv2d(256, 9, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.conv72 = nn.Conv2d(256, 65, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.bn1 = nn.BatchNorm2d(64) self.bn2 = nn.BatchNorm2d(64) def forward(self, screen): screen = F.pad(screen, (3, 3, 0, 0), mode='replicate') shared = self.conv1(screen) shared = self.bn1(shared) shared = F.relu(shared, inplace=True) shared = F.pad(shared, (1, 1, 0, 0), mode='replicate') shared = self.conv2(shared) shared = self.bn2(shared) shared = F.relu(shared, inplace=True) shared = self.conv3(shared) shared = self.conv4(shared) shared = self.conv5(shared) shared = self.conv6(shared) output1 = F.pad(shared, (1, 1, 0, 0), mode='replicate') output1 = self.conv71(output1) output2 = F.pad(shared, (1, 1, 0, 0), mode='replicate') output2 = self.conv72(output2) return output1, output2 ''' class MapModel(nn.Module): def __init__(self, args, use_softmax=True): super().__init__() self.use_softmax = use_softmax #self.object_model = ObjectModel(args) #self.distance_model = DistanceModel(args) self.object_distance_model = ObjectDistanceModel4(args) def forward(self, screen): #objects = self.object_model(screen) #if self.use_softmax: # objects = F.log_softmax(objects, dim=1) #distances = self.distance_model(screen) #if self.use_softmax: # distances = F.log_softmax(distances, dim=1) objects, distances = self.object_distance_model(screen) if self.use_softmax: objects = F.log_softmax(objects, dim=1) distances = F.log_softmax(distances, dim=1) return objects, distances ''' class MapModel(nn.Module): def __init__(self, args, use_softmax=True): super().__init__() self.use_softmax = use_softmax self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=(1, 1), dilation=(1, 1), padding=(0, 0), bias=False) self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.conv3 = BasicBlock(64, 128, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv4 = BasicBlock(128, 128, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv5 = BasicBlock(128, 256, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv6 = BasicBlock(256, 256, stride=(2, 1), dilation=(1, 1), padding=(1, 1)) self.conv71 = nn.Conv2d(256, 9, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.conv72 = nn.Conv2d(256, 65, kernel_size=3, stride=(2, 1), dilation=(1, 1), padding=(0, 0)) self.bn1 = nn.BatchNorm2d(64) self.bn2 = nn.BatchNorm2d(64) def forward(self, screen): screen = F.pad(screen, (3, 3, 0, 0), mode='replicate') shared = self.conv1(screen) shared = self.bn1(shared) shared = F.relu(shared, inplace=True) shared = F.pad(shared, (1, 1, 0, 0), mode='replicate') shared = self.conv2(shared) shared = self.bn2(shared) shared = F.relu(shared, inplace=True) shared = self.conv3(shared) shared = self.conv4(shared) shared = self.conv5(shared) shared = self.conv6(shared) objects = F.pad(shared, (1, 1, 0, 0), mode='replicate') objects = self.conv71(objects) distances = F.pad(shared, (1, 1, 0, 0), mode='replicate') distances = self.conv72(distances) if self.use_softmax: objects = F.log_softmax(objects, dim=1) distances = F.log_softmax(distances, dim=1) return objects, distances
42.376658
114
0.593953
873d7c8a682f0590f140a3a59058647296da7b14
25,473
py
Python
src/pretalx/orga/views/event.py
chriswolfdesign/pretalx
fb6bcf090a5c92e55a79851d60dfc716309da557
[ "Apache-2.0" ]
null
null
null
src/pretalx/orga/views/event.py
chriswolfdesign/pretalx
fb6bcf090a5c92e55a79851d60dfc716309da557
[ "Apache-2.0" ]
null
null
null
src/pretalx/orga/views/event.py
chriswolfdesign/pretalx
fb6bcf090a5c92e55a79851d60dfc716309da557
[ "Apache-2.0" ]
null
null
null
import json from contextlib import suppress from pathlib import Path from csp.decorators import csp_update from django.conf import settings from django.contrib import messages from django.contrib.auth import login from django.core.files.storage import FileSystemStorage from django.db import transaction from django.db.models import Q from django.forms.models import inlineformset_factory from django.http import Http404, JsonResponse from django.shortcuts import get_object_or_404, redirect from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from django.views.generic import ( DeleteView, FormView, ListView, TemplateView, UpdateView, View, ) from django_context_decorator import context from django_scopes import scope, scopes_disabled from formtools.wizard.views import SessionWizardView from pytz import timezone from rest_framework.authtoken.models import Token from pretalx.common.forms import I18nFormSet from pretalx.common.mixins.views import ( ActionFromUrl, EventPermissionRequired, PermissionRequired, SensibleBackWizardMixin, ) from pretalx.common.models import ActivityLog from pretalx.common.tasks import regenerate_css from pretalx.common.templatetags.rich_text import rich_text from pretalx.common.views import is_form_bound from pretalx.event.forms import ( EventWizardBasicsForm, EventWizardCopyForm, EventWizardDisplayForm, EventWizardInitialForm, EventWizardTimelineForm, ReviewPhaseForm, ) from pretalx.event.models import Event, Team, TeamInvite from pretalx.orga.forms import EventForm, EventSettingsForm from pretalx.orga.forms.event import ( MailSettingsForm, ReviewSettingsForm, WidgetGenerationForm, WidgetSettingsForm, ) from pretalx.orga.signals import activate_event from pretalx.person.forms import LoginInfoForm, OrgaProfileForm, UserForm from pretalx.person.models import User from pretalx.submission.models import ReviewPhase class EventSettingsPermission(EventPermissionRequired): permission_required = "orga.change_settings" write_permission_required = "orga.change_settings" @property def permission_object(self): return self.request.event class EventDetail(EventSettingsPermission, ActionFromUrl, UpdateView): model = Event form_class = EventForm permission_required = "orga.change_settings" template_name = "orga/settings/form.html" def get_object(self): return self.object @cached_property def object(self): return self.request.event @context @cached_property def sform(self): return EventSettingsForm( read_only=(self.action == "view"), locales=self.request.event.locales, obj=self.request.event, attribute_name="settings", data=self.request.POST if self.request.method == "POST" else None, prefix="settings", ) def get_form_kwargs(self, *args, **kwargs): response = super().get_form_kwargs(*args, **kwargs) response["is_administrator"] = self.request.user.is_administrator return response @context def url_placeholder(self): return f"https://{self.request.host}/" def get_success_url(self) -> str: return self.object.orga_urls.settings @transaction.atomic def form_valid(self, form): if not self.sform.is_valid(): return self.form_invalid(form) result = super().form_valid(form) self.sform.save() form.instance.log_action( "pretalx.event.update", person=self.request.user, orga=True ) messages.success(self.request, _("The event settings have been saved.")) regenerate_css.apply_async(args=(form.instance.pk,)) return result class EventLive(EventSettingsPermission, TemplateView): template_name = "orga/event/live.html" permission_required = "orga.change_settings" def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) warnings = [] suggestions = [] # TODO: move to signal if ( not self.request.event.cfp.text or len(str(self.request.event.cfp.text)) < 50 ): warnings.append( { "text": _("The CfP doesn't have a full text yet."), "url": self.request.event.cfp.urls.text, } ) if ( not self.request.event.landing_page_text or len(str(self.request.event.landing_page_text)) < 50 ): warnings.append( { "text": _("The event doesn't have a landing page text yet."), "url": self.request.event.orga_urls.settings, } ) # TODO: test that mails can be sent if ( self.request.event.settings.use_tracks and self.request.event.settings.cfp_request_track and self.request.event.tracks.count() < 2 ): suggestions.append( { "text": _( "You want submitters to choose the tracks for their submissions, but you do not offer tracks for selection. Add at least one track!" ), "url": self.request.event.cfp.urls.tracks, } ) if not self.request.event.submission_types.count() > 1: suggestions.append( { "text": _("You have configured only one submission type so far."), "url": self.request.event.cfp.urls.types, } ) if not self.request.event.questions.exists(): suggestions.append( { "text": _("You have configured no questions yet."), "url": self.request.event.cfp.urls.new_question, } ) result["warnings"] = warnings result["suggestions"] = suggestions return result def post(self, request, *args, **kwargs): event = request.event action = request.POST.get("action") if action == "activate": if event.is_public: messages.success(request, _("This event was already live.")) else: responses = activate_event.send_robust(event, request=request) exceptions = [ response[1] for response in responses if isinstance(response[1], Exception) ] if exceptions: messages.error( request, mark_safe("\n".join(rich_text(e) for e in exceptions)), ) else: event.is_public = True event.save() event.log_action( "pretalx.event.activate", person=self.request.user, orga=True, data={}, ) messages.success(request, _("This event is now public.")) else: # action == 'deactivate' if not event.is_public: messages.success(request, _("This event was already hidden.")) else: event.is_public = False event.save() event.log_action( "pretalx.event.deactivate", person=self.request.user, orga=True, data={}, ) messages.success(request, _("This event is now hidden.")) return redirect(event.orga_urls.base) class EventHistory(EventSettingsPermission, ListView): template_name = "orga/event/history.html" model = ActivityLog context_object_name = "log_entries" paginate_by = 200 def get_queryset(self): return ActivityLog.objects.filter(event=self.request.event) class EventReviewSettings(EventSettingsPermission, ActionFromUrl, FormView): form_class = ReviewSettingsForm template_name = "orga/settings/review.html" write_permission_required = "orga.change_settings" def get_success_url(self) -> str: return self.request.event.orga_urls.review_settings def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["obj"] = self.request.event kwargs["attribute_name"] = "settings" kwargs["locales"] = self.request.event.locales return kwargs @transaction.atomic def form_valid(self, form): formset = self.save_formset() if not formset: return self.get(self.request, *self.args, **self.kwargs) form.save() return super().form_valid(form) @context @cached_property def formset(self): formset_class = inlineformset_factory( Event, ReviewPhase, form=ReviewPhaseForm, formset=I18nFormSet, can_delete=True, extra=0, ) return formset_class( self.request.POST if self.request.method == "POST" else None, queryset=ReviewPhase.objects.filter(event=self.request.event), event=self.request.event, ) def save_formset(self): if not self.formset.is_valid(): return False for form in self.formset.initial_forms: # Deleting is handled elsewhere, so we skip it here if form.has_changed(): form.instance.event = self.request.event form.save() extra_forms = [ form for form in self.formset.extra_forms if form.has_changed and not self.formset._should_delete_form(form) ] for form in extra_forms: form.instance.event = self.request.event form.save() return True def phase_move(request, pk, up=True): try: phase = request.event.review_phases.get(pk=pk) except ReviewPhase.DoesNotExist: raise Http404(_("The selected review phase does not exist.")) if not request.user.has_perm("orga.change_settings", phase): messages.error( request, _("Sorry, you are not allowed to reorder review phases.") ) return phases = list(request.event.review_phases.order_by("position")) index = phases.index(phase) if index != 0 and up: phases[index - 1], phases[index] = phases[index], phases[index - 1] elif index != len(phases) - 1 and not up: phases[index + 1], phases[index] = phases[index], phases[index + 1] for i, phase in enumerate(phases): if phase.position != i: phase.position = i phase.save() messages.success(request, _("The order of review phases has been updated.")) def phase_move_up(request, event, pk): phase_move(request, pk, up=True) return redirect(request.event.orga_urls.review_settings) def phase_move_down(request, event, pk): phase_move(request, pk, up=False) return redirect(request.event.orga_urls.review_settings) class PhaseDelete(PermissionRequired, View): permission_required = "orga.change_settings" def get_object(self): return get_object_or_404( ReviewPhase, event=self.request.event, pk=self.kwargs.get("pk") ) def dispatch(self, request, *args, **kwargs): super().dispatch(request, *args, **kwargs) phase = self.get_object() phase.delete() return redirect(self.request.event.orga_urls.review_settings) class PhaseActivate(PermissionRequired, View): permission_required = "orga.change_settings" def get_object(self): return get_object_or_404( ReviewPhase, event=self.request.event, pk=self.kwargs.get("pk") ) def dispatch(self, request, *args, **kwargs): super().dispatch(request, *args, **kwargs) phase = self.get_object() phase.activate() return redirect(self.request.event.orga_urls.review_settings) class EventMailSettings(EventSettingsPermission, ActionFromUrl, FormView): form_class = MailSettingsForm template_name = "orga/settings/mail.html" write_permission_required = "orga.change_settings" def get_success_url(self) -> str: return self.request.event.orga_urls.mail_settings def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["obj"] = self.request.event kwargs["attribute_name"] = "settings" kwargs["locales"] = self.request.event.locales return kwargs def form_valid(self, form): form.save() if self.request.POST.get("test", "0").strip() == "1": backend = self.request.event.get_mail_backend(force_custom=True) try: backend.test(self.request.event.settings.mail_from) except Exception as e: messages.warning( self.request, _("An error occurred while contacting the SMTP server: %s") % str(e), ) return redirect(self.request.event.orga_urls.mail_settings) else: # pragma: no cover if form.cleaned_data.get("smtp_use_custom"): messages.success( self.request, _( "Yay, your changes have been saved and the connection attempt to " "your SMTP server was successful." ), ) else: messages.success( self.request, _( "We've been able to contact the SMTP server you configured. " 'Remember to check the "use custom SMTP server" checkbox, ' "otherwise your SMTP server will not be used." ), ) else: messages.success(self.request, _("Yay! We saved your changes.")) return super().form_valid(form) class InvitationView(FormView): template_name = "orga/invitation.html" form_class = UserForm @context @cached_property def invitation(self): return get_object_or_404(TeamInvite, token__iexact=self.kwargs.get("code")) def post(self, *args, **kwargs): if not self.request.user.is_anonymous: self.accept_invite(self.request.user) return redirect("/orga") return super().post(*args, **kwargs) def form_valid(self, form): form.save() user = User.objects.filter(pk=form.cleaned_data.get("user_id")).first() if not user: messages.error( self.request, _( "There was a problem with your authentication. Please contact the organiser for further help." ), ) return redirect(self.request.event.urls.base) self.accept_invite(user) login(self.request, user, backend="django.contrib.auth.backends.ModelBackend") return redirect("/orga") @transaction.atomic() def accept_invite(self, user): invite = self.invitation invite.team.members.add(user) invite.team.save() invite.team.organiser.log_action( "pretalx.invite.orga.accept", person=user, orga=True ) messages.info(self.request, _("You are now part of the team!")) invite.delete() class UserSettings(TemplateView): form_class = LoginInfoForm template_name = "orga/user.html" def get_success_url(self) -> str: return reverse("orga:user.view") @context @cached_property def login_form(self): return LoginInfoForm( user=self.request.user, data=self.request.POST if is_form_bound(self.request, "login") else None, ) @context @cached_property def profile_form(self): return OrgaProfileForm( instance=self.request.user, data=self.request.POST if is_form_bound(self.request, "profile") else None, ) @context def token(self): return Token.objects.filter( user=self.request.user ).first() or Token.objects.create(user=self.request.user) def post(self, request, *args, **kwargs): if self.login_form.is_bound and self.login_form.is_valid(): self.login_form.save() messages.success(request, _("Your changes have been saved.")) request.user.log_action("pretalx.user.password.update") elif self.profile_form.is_bound and self.profile_form.is_valid(): self.profile_form.save() messages.success(request, _("Your changes have been saved.")) request.user.log_action("pretalx.user.profile.update") elif request.POST.get("form") == "token": request.user.regenerate_token() messages.success( request, _( "Your API token has been regenerated. The previous token will not be usable any longer." ), ) else: messages.error( self.request, _("Oh :( We had trouble saving your input. See below for details."), ) return redirect(self.get_success_url()) def condition_copy(wizard): return EventWizardCopyForm.copy_from_queryset(wizard.request.user).exists() class EventWizard(PermissionRequired, SensibleBackWizardMixin, SessionWizardView): permission_required = "orga.create_events" file_storage = FileSystemStorage(location=Path(settings.MEDIA_ROOT) / "new_event") form_list = [ ("initial", EventWizardInitialForm), ("basics", EventWizardBasicsForm), ("timeline", EventWizardTimelineForm), ("display", EventWizardDisplayForm), ("copy", EventWizardCopyForm), ] condition_dict = {"copy": condition_copy} def get_template_names(self): return f"orga/event/wizard/{self.steps.current}.html" @context def has_organiser(self): return ( self.request.user.teams.filter(can_create_events=True).exists() or self.request.user.is_administrator ) @context def url_placeholder(self): return f"https://{self.request.host}/" @context def organiser(self): return ( self.get_cleaned_data_for_step("initial").get("organiser") if self.steps.current != "initial" else None ) def render(self, form=None, **kwargs): if self.steps.current != "initial": if self.get_cleaned_data_for_step("initial") is None: return self.render_goto_step("initial") if self.steps.current == "timeline": fdata = self.get_cleaned_data_for_step("basics") year = now().year % 100 if ( fdata and not str(year) in fdata["slug"] and not str(year + 1) in fdata["slug"] ): messages.warning( self.request, str( _( "Please consider including your event's year in the slug, e.g. myevent{number}." ) ).format(number=year), ) elif self.steps.current == "display": fdata = self.get_cleaned_data_for_step("timeline") if fdata and fdata.get("date_to") < now().date(): messages.warning( self.request, _("Did you really mean to make your event take place in the past?"), ) return super().render(form, **kwargs) def get_form_kwargs(self, step=None): kwargs = {"user": self.request.user} if step != "initial": fdata = self.get_cleaned_data_for_step("initial") kwargs.update(fdata or {}) return kwargs @transaction.atomic() def done(self, form_list, *args, **kwargs): steps = { step: self.get_cleaned_data_for_step(step) for step in ("initial", "basics", "timeline", "display", "copy") } with scopes_disabled(): event = Event.objects.create( organiser=steps["initial"]["organiser"], locale_array=",".join(steps["initial"]["locales"]), name=steps["basics"]["name"], slug=steps["basics"]["slug"], timezone=steps["basics"]["timezone"], email=steps["basics"]["email"], locale=steps["basics"]["locale"], primary_color=steps["display"]["primary_color"], logo=steps["display"]["logo"], date_from=steps["timeline"]["date_from"], date_to=steps["timeline"]["date_to"], ) with scope(event=event): deadline = steps["timeline"].get("deadline") if deadline: zone = timezone(event.timezone) event.cfp.deadline = zone.localize(deadline.replace(tzinfo=None)) event.cfp.save() for setting in [ "custom_domain", "display_header_data", ]: value = steps["display"].get(setting) if value: event.settings.set(setting, value) has_control_rights = self.request.user.teams.filter( organiser=event.organiser, all_events=True, can_change_event_settings=True, can_change_submissions=True, ).exists() if not has_control_rights: t = Team.objects.create( organiser=event.organiser, name=_(f"Team {event.name}"), can_change_event_settings=True, can_change_submissions=True, ) t.members.add(self.request.user) t.limit_events.add(event) logdata = {} for f in form_list: logdata.update({k: v for k, v in f.cleaned_data.items()}) with scope(event=event): event.log_action( "pretalx.event.create", person=self.request.user, data=logdata, orga=True, ) if steps["copy"] and steps["copy"]["copy_from_event"]: event.copy_data_from(steps["copy"]["copy_from_event"]) return redirect(event.orga_urls.base + "?congratulations") class EventDelete(PermissionRequired, DeleteView): template_name = "orga/event/delete.html" permission_required = "person.is_administrator" model = Event def get_object(self): return self.request.event def delete(self, request, *args, **kwargs): self.get_object().shred() return redirect("/orga/") def event_list(request): query = json.dumps(str(request.GET.get("query", "")))[1:-1] page = 1 with suppress(ValueError): page = int(request.GET.get("page", "1")) qs = ( request.user.get_events_with_any_permission() .filter( Q(name__icontains=query) | Q(slug__icontains=query) | Q(organiser__name__icontains=query) | Q(organiser__slug__icontains=query) ) .order_by("-date_from") ) total = qs.count() pagesize = 20 offset = (page - 1) * pagesize doc = { "results": [ { "id": event.pk, "slug": event.slug, "organiser": str(event.organiser.name), "name": str(event.name), "text": str(event.name), "date_range": event.get_date_range_display(), "url": event.orga_urls.base, } for event in qs.select_related("organiser")[offset : offset + pagesize] ], "pagination": {"more": total >= (offset + pagesize)}, } return JsonResponse(doc) @method_decorator(csp_update(SCRIPT_SRC="'self' 'unsafe-eval'"), name="dispatch") class WidgetSettings(EventPermissionRequired, FormView): form_class = WidgetSettingsForm permission_required = "orga.change_settings" template_name = "orga/settings/widget.html" def form_valid(self, form): messages.success(self.request, _("The widget settings have been saved.")) form.save() return super().form_valid(form) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["obj"] = self.request.event kwargs["attribute_name"] = "settings" return kwargs def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) result["extra_form"] = WidgetGenerationForm(instance=self.request.event) return result def get_success_url(self) -> str: return self.request.event.orga_urls.widget_settings
34.70436
156
0.593256
96e3fe5b369e81e2300fa94697e053928e6a1658
542
py
Python
cloudaux/__about__.py
Deepak1100/cloudaux
322b26b9c47e5f4fcd5cd11fc4aa5fa830c050f9
[ "Apache-2.0" ]
null
null
null
cloudaux/__about__.py
Deepak1100/cloudaux
322b26b9c47e5f4fcd5cd11fc4aa5fa830c050f9
[ "Apache-2.0" ]
null
null
null
cloudaux/__about__.py
Deepak1100/cloudaux
322b26b9c47e5f4fcd5cd11fc4aa5fa830c050f9
[ "Apache-2.0" ]
null
null
null
__all__ = [ '__title__', '__summary__', '__uri__', '__version__', '__author__', '__email__', '__license__', '__copyright__' ] __title__ = 'cloudaux' __summary__ = 'Cloud Auxiliary is a python wrapper and orchestration module for interacting with cloud providers' __uri__ = 'https://github.com/Netflix-Skunkworks/cloudaux' __version__ = '1.8.3' __author__ = 'The Cloudaux Developers' __email__ = 'oss@netflix.com' __license__ = 'Apache License, Version 2.0' __copyright__ = 'Copyright 2020 %s' % __author__
23.565217
113
0.706642
711272a29e309d0368aa59cd19ec68d01df72892
1,040
py
Python
leetcode/number_of_submatrices_that_sum_to_target/number_of_submatrices_that_sum_to_target.py
sagasu/python-algorithms
d630777a3f17823165e4d72ab780ede7b10df752
[ "MIT" ]
null
null
null
leetcode/number_of_submatrices_that_sum_to_target/number_of_submatrices_that_sum_to_target.py
sagasu/python-algorithms
d630777a3f17823165e4d72ab780ede7b10df752
[ "MIT" ]
null
null
null
leetcode/number_of_submatrices_that_sum_to_target/number_of_submatrices_that_sum_to_target.py
sagasu/python-algorithms
d630777a3f17823165e4d72ab780ede7b10df752
[ "MIT" ]
null
null
null
class Solution: def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: rows = len(matrix) cols = len(matrix[0]) prefix = [[0] * (cols + 1) for _ in range(rows + 1)] for r in range(rows): for c in range(cols): prefix[r + 1][c+ 1] = matrix[r][c] for r in range(rows + 1): for c in range(cols): prefix[r][c+ 1] += prefix[r][c] for r in range(rows): for c in range(cols + 1): prefix[r + 1][c] += prefix[r][c] total = 0 for r1 in range(1, rows + 1): for r2 in range(r1): lookup = collections.defaultdict(int) lookup[0] = 1 current = 0 for c in range(1, cols + 1): current += prefix[r1][c] - prefix[r2][c] - prefix[r1][c - 1] + prefix[r2][c-1] total += lookup[current - target] lookup[current] += 1 return total
31.515152
98
0.447115
67ab8681787575ceb510c757b407af173e428376
2,901
py
Python
DataStructures/Stack/Stack.py
chrisphil335/structlinks
61aee24ec15c7caab9ce99e1f97ce30e7f21157c
[ "MIT" ]
9
2021-04-09T21:20:46.000Z
2022-03-25T12:14:43.000Z
DataStructures/Stack/Stack.py
chrisphil335/structlinks
61aee24ec15c7caab9ce99e1f97ce30e7f21157c
[ "MIT" ]
19
2021-03-22T07:52:39.000Z
2021-04-07T20:04:05.000Z
DataStructures/Stack/Stack.py
chrisphil335/structlinks
61aee24ec15c7caab9ce99e1f97ce30e7f21157c
[ "MIT" ]
7
2021-04-10T21:08:12.000Z
2022-03-20T12:55:23.000Z
""" This is an implementation of the stack data structure, with code pulled from the University of Toronto's CSC110 course notes. """ from __future__ import annotations from typing import Any, Optional, Callable, Sequence class Stack: """ This class represents a stack data structure """ def __init__(self, items: Optional[list] = None) -> None: """ Initialize a stack, empty at first """ self.items = [] if items: self.items = items def is_empty(self) -> bool: """ Returns whether the stack is empty """ return self.items == [] def push(self, item: Any) -> None: """ Adds a new element to the top of the stack """ self.items.append(item) def push_multiple(self, items: Sequence) -> None: """Push multiple items in the stack""" for item in items: self.push(item) def pop(self) -> Any: """ Removes the element at the top of the stack and returns it. Raises IndexError if list is empty """ if self.is_empty(): raise EmptyStackError else: return self.items.pop() def __len__(self) -> int: """Return the length of the stack""" return len(self.items) def to_list(self) -> list: """Return list of the stack""" return self.items def __copy__(self) -> Stack: """Return a copy of the stack""" return Stack(items=self.items) def copy(self) -> Stack: """Return a copy of the stack""" return Stack(items=self.items) def map(self, key: Callable) -> Stack: """Map a function to the stack""" return Stack(items=[key(item) for item in self.items]) def invert(self) -> None: """Invert the stack""" self.items.reverse() def extend(self, other: Stack): """extend the stack by putting other stack on top of self""" self.push_multiple(other.items) def __add__(self, other) -> Stack: """Return a stack with other stack on top of self""" return Stack(items=self.items + other.items) def __str__(self) -> str: """Return string representation of the stack""" string_so_far = '' gap = 10 for index in range(len(self) - 1, -1, -1): item = self.items[index] string_rep = str(item) gap_left = gap - len(string_rep) string_so_far += '|' + ' ' * gap + string_rep + ' ' * gap_left + '| \n' string_so_far += '|' + '_' * (2 * gap) + '|' return string_so_far def __repr__(self) -> str: return f'Stack({self.items})' class EmptyStackError(Exception): def __str__(self) -> str: """String representation of the error""" return "Popping from an empty stack is not allowed"
26.614679
83
0.567046
798966c28e6ad03ae4ebc8f6597b896df7d759f3
9,528
py
Python
devel/lib/python2.7/dist-packages/costmap_prohibition_layer/srv/_GetProhibitedPoints.py
Jam-cpu/Masters-Project---Final
0b266b1f117a579b96507249f0a128d0e3cc082a
[ "BSD-3-Clause-Clear" ]
null
null
null
devel/lib/python2.7/dist-packages/costmap_prohibition_layer/srv/_GetProhibitedPoints.py
Jam-cpu/Masters-Project---Final
0b266b1f117a579b96507249f0a128d0e3cc082a
[ "BSD-3-Clause-Clear" ]
null
null
null
devel/lib/python2.7/dist-packages/costmap_prohibition_layer/srv/_GetProhibitedPoints.py
Jam-cpu/Masters-Project---Final
0b266b1f117a579b96507249f0a128d0e3cc082a
[ "BSD-3-Clause-Clear" ]
null
null
null
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from costmap_prohibition_layer/GetProhibitedPointsRequest.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class GetProhibitedPointsRequest(genpy.Message): _md5sum = "d41d8cd98f00b204e9800998ecf8427e" _type = "costmap_prohibition_layer/GetProhibitedPointsRequest" _has_header = False # flag to mark the presence of a Header object _full_text = """ """ __slots__ = [] _slot_types = [] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(GetProhibitedPointsRequest, self).__init__(*args, **kwds) def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: pass except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: pass except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: end = 0 return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I # This Python file uses the following encoding: utf-8 """autogenerated by genpy from costmap_prohibition_layer/GetProhibitedPointsResponse.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geometry_msgs.msg class GetProhibitedPointsResponse(genpy.Message): _md5sum = "e85019b57cf217e7d529d6333370e839" _type = "costmap_prohibition_layer/GetProhibitedPointsResponse" _has_header = False # flag to mark the presence of a Header object _full_text = """geometry_msgs/Polygon[] polygons ================================================================================ MSG: geometry_msgs/Polygon #A specification of a polygon where the first and last points are assumed to be connected Point32[] points ================================================================================ MSG: geometry_msgs/Point32 # This contains the position of a point in free space(with 32 bits of precision). # It is recommeded to use Point wherever possible instead of Point32. # # This recommendation is to promote interoperability. # # This message is designed to take up less space when sending # lots of points at once, as in the case of a PointCloud. float32 x float32 y float32 z""" __slots__ = ['polygons'] _slot_types = ['geometry_msgs/Polygon[]'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: polygons :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(GetProhibitedPointsResponse, self).__init__(*args, **kwds) # message fields cannot be None, assign default values for those that are if self.polygons is None: self.polygons = [] else: self.polygons = [] def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: length = len(self.polygons) buff.write(_struct_I.pack(length)) for val1 in self.polygons: length = len(val1.points) buff.write(_struct_I.pack(length)) for val2 in val1.points: _x = val2 buff.write(_get_struct_3f().pack(_x.x, _x.y, _x.z)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: if self.polygons is None: self.polygons = None end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.polygons = [] for i in range(0, length): val1 = geometry_msgs.msg.Polygon() start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) val1.points = [] for i in range(0, length): val2 = geometry_msgs.msg.Point32() _x = val2 start = end end += 12 (_x.x, _x.y, _x.z,) = _get_struct_3f().unpack(str[start:end]) val1.points.append(val2) self.polygons.append(val1) return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: length = len(self.polygons) buff.write(_struct_I.pack(length)) for val1 in self.polygons: length = len(val1.points) buff.write(_struct_I.pack(length)) for val2 in val1.points: _x = val2 buff.write(_get_struct_3f().pack(_x.x, _x.y, _x.z)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ if python3: codecs.lookup_error("rosmsg").msg_type = self._type try: if self.polygons is None: self.polygons = None end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) self.polygons = [] for i in range(0, length): val1 = geometry_msgs.msg.Polygon() start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) val1.points = [] for i in range(0, length): val2 = geometry_msgs.msg.Point32() _x = val2 start = end end += 12 (_x.x, _x.y, _x.z,) = _get_struct_3f().unpack(str[start:end]) val1.points.append(val2) self.polygons.append(val1) return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_3f = None def _get_struct_3f(): global _struct_3f if _struct_3f is None: _struct_3f = struct.Struct("<3f") return _struct_3f class GetProhibitedPoints(object): _type = 'costmap_prohibition_layer/GetProhibitedPoints' _md5sum = 'e85019b57cf217e7d529d6333370e839' _request_class = GetProhibitedPointsRequest _response_class = GetProhibitedPointsResponse
34.150538
145
0.651448
8200a1d71664903771a6575ebea3f92a9515b957
5,621
py
Python
stanza/models/mwt/trainer.py
turtlesoupy/stanza
8511620010ba22123f29ea1a7ec3606ec96aaf69
[ "Apache-2.0" ]
null
null
null
stanza/models/mwt/trainer.py
turtlesoupy/stanza
8511620010ba22123f29ea1a7ec3606ec96aaf69
[ "Apache-2.0" ]
null
null
null
stanza/models/mwt/trainer.py
turtlesoupy/stanza
8511620010ba22123f29ea1a7ec3606ec96aaf69
[ "Apache-2.0" ]
null
null
null
""" A trainer class to handle training and testing of models. """ import sys import numpy as np from collections import Counter import logging import torch from torch import nn import torch.nn.init as init import stanza.models.common.seq2seq_constant as constant from stanza.models.common.trainer import Trainer as BaseTrainer from stanza.models.common.seq2seq_model import Seq2SeqModel from stanza.models.common import utils, loss from stanza.models.mwt.vocab import Vocab logger = logging.getLogger('stanza') def unpack_batch(batch, use_cuda): """ Unpack a batch from the data loader. """ if use_cuda: inputs = [b.cuda() if b is not None else None for b in batch[:4]] else: inputs = [b if b is not None else None for b in batch[:4]] orig_idx = batch[4] return inputs, orig_idx class Trainer(object): """ A trainer for training models. """ def __init__(self, args=None, vocab=None, emb_matrix=None, model_file=None, use_cuda=False): self.use_cuda = use_cuda if model_file is not None: # load from file self.load(model_file, use_cuda) else: self.args = args self.model = None if args['dict_only'] else Seq2SeqModel(args, emb_matrix=emb_matrix) self.vocab = vocab self.expansion_dict = dict() if not self.args['dict_only']: self.crit = loss.SequenceLoss(self.vocab.size) self.parameters = [p for p in self.model.parameters() if p.requires_grad] if use_cuda: self.model.cuda() self.crit.cuda() else: self.model.cpu() self.crit.cpu() self.optimizer = utils.get_optimizer(self.args['optim'], self.parameters, self.args['lr']) def update(self, batch, eval=False): inputs, orig_idx = unpack_batch(batch, self.use_cuda) src, src_mask, tgt_in, tgt_out = inputs if eval: self.model.eval() else: self.model.train() self.optimizer.zero_grad() log_probs, _ = self.model(src, src_mask, tgt_in) loss = self.crit(log_probs.view(-1, self.vocab.size), tgt_out.view(-1)) loss_val = loss.data.item() if eval: return loss_val loss.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args['max_grad_norm']) self.optimizer.step() return loss_val def predict(self, batch, unsort=True): inputs, orig_idx = unpack_batch(batch, self.use_cuda) src, src_mask, tgt, tgt_mask = inputs self.model.eval() batch_size = src.size(0) preds, _ = self.model.predict(src, src_mask, self.args['beam_size']) pred_seqs = [self.vocab.unmap(ids) for ids in preds] # unmap to tokens pred_seqs = utils.prune_decoded_seqs(pred_seqs) pred_tokens = ["".join(seq) for seq in pred_seqs] # join chars to be tokens if unsort: pred_tokens = utils.unsort(pred_tokens, orig_idx) return pred_tokens def train_dict(self, pairs): """ Train a MWT expander given training word-expansion pairs. """ # accumulate counter ctr = Counter() ctr.update([(p[0], p[1]) for p in pairs]) seen = set() # find the most frequent mappings for p, _ in ctr.most_common(): w, l = p if w not in seen and w != l: self.expansion_dict[w] = l seen.add(w) return def predict_dict(self, words): """ Predict a list of expansions given words. """ expansions = [] for w in words: if w in self.expansion_dict: expansions += [self.expansion_dict[w]] elif w.lower() in self.expansion_dict: expansions += [self.expansion_dict[w.lower()]] else: expansions += [w] return expansions def ensemble(self, cands, other_preds): """ Ensemble the dict with statistical model predictions. """ expansions = [] assert len(cands) == len(other_preds) for c, pred in zip(cands, other_preds): if c in self.expansion_dict: expansions += [self.expansion_dict[c]] elif c.lower() in self.expansion_dict: expansions += [self.expansion_dict[c.lower()]] else: expansions += [pred] return expansions def save(self, filename): params = { 'model': self.model.state_dict() if self.model is not None else None, 'dict': self.expansion_dict, 'vocab': self.vocab.state_dict(), 'config': self.args } try: torch.save(params, filename) logger.info("Model saved to {}".format(filename)) except BaseException: logger.warning("Saving failed... continuing anyway.") def load(self, filename, use_cuda=False): try: checkpoint = torch.load(filename, lambda storage, loc: storage) except BaseException: logger.exception("Cannot load model from {}".format(filename)) raise self.args = checkpoint['config'] self.expansion_dict = checkpoint['dict'] if not self.args['dict_only']: self.model = Seq2SeqModel(self.args, use_cuda=use_cuda) self.model.load_state_dict(checkpoint['model']) else: self.model = None self.vocab = Vocab.load_state_dict(checkpoint['vocab'])
36.5
102
0.595446
da8df67cb8f662318407cbf704123e31c5895238
12,584
py
Python
tensorflow/python/layers/core.py
connectthefuture/tensorflow
93812423fcd5878aa2c1d0b68dc0496980c8519d
[ "Apache-2.0" ]
1
2018-11-15T08:44:10.000Z
2018-11-15T08:44:10.000Z
tensorflow/python/layers/core.py
connectthefuture/tensorflow
93812423fcd5878aa2c1d0b68dc0496980c8519d
[ "Apache-2.0" ]
null
null
null
tensorflow/python/layers/core.py
connectthefuture/tensorflow
93812423fcd5878aa2c1d0b68dc0496980c8519d
[ "Apache-2.0" ]
1
2020-07-20T18:02:33.000Z
2020-07-20T18:02:33.000Z
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= # pylint: disable=unused-import,g-bad-import-order """Contains the core layers: Dense, Dropout. Also contains their functional aliases. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from six.moves import xrange # pylint: disable=redefined-builtin import numpy as np from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import nn from tensorflow.python.ops import standard_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.ops import control_flow_ops from tensorflow.python.layers import base class Dense(base._Layer): # pylint: disable=protected-access """Densely-connected layer class. This layer implements the operation `outputs = activation(inputs.w + b)` Where `activation` is the activation function passed as the `activation` argument (if not `None`), `w` is a weights matrix created by the layer, and `b` is a bias vector created by the layer (only if `use_bias` is `True`). Note: if the input to the layer has a rank greater than 2, then it is flattened prior to the initial matrix multiply by `w`. Arguments: units: Integer or Long, dimensionality of the output space. activation: Activation function (callable). Set it to None to maintain a linear activation. use_bias: Boolean, whether the layer uses a bias. weights_initializer: Initializer function for the weight matrix. bias_initializer: Initializer function for the bias. weights_regularizer: Regularizer function for the weight matrix. bias_regularizer: Regularizer function for the bias. activity_regularizer: Regularizer function for the output. trainable: Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). name: String, the name of the layer. Layers with the same name will share weights, but to avoid mistakes we require reuse=True in such cases. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Properties: units: Python integer, dimensionality of the output space. activation: Activation function (callable). use_bias: Boolean, whether the layer uses a bias. weights_initializer: Initializer instance (or name) for the weight matrix. bias_initializer: Initializer instance (or name) for the bias. weights_regularizer: Regularizer instance for the weight matrix (callable) bias_regularizer: Regularizer instance for the bias (callable). activity_regularizer: Regularizer instance for the output (callable) weights: Weight matrix (TensorFlow variable or tensor). bias: Bias vector, if applicable (TensorFlow variable or tensor). """ def __init__(self, units, activation=None, use_bias=True, weights_initializer=None, bias_initializer=init_ops.zeros_initializer, weights_regularizer=None, bias_regularizer=None, activity_regularizer=None, trainable=True, name=None, **kwargs): super(Dense, self).__init__(trainable=trainable, name=name, **kwargs) self.units = units self.activation = activation self.use_bias = use_bias self.weights_initializer = weights_initializer self.bias_initializer = bias_initializer self.weights_regularizer = weights_regularizer self.bias_regularizer = bias_regularizer self.activity_regularizer = activity_regularizer def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) if input_shape.ndims is None: raise ValueError('Inputs to `Dense` should have known rank.') if len(input_shape) < 2: raise ValueError('Inputs to `Dense` should have rank >= 2.') if input_shape[-1].value is None: raise ValueError('The last dimension of the inputs to `Dense` ' 'should be defined. Found `None`.') # Note that we set `trainable=True` because this is a trainable # weight of the layer. If the layer is not trainable # (self.trainable = False), the variable will not be added to # tf.trainable_variables(), and self.trainable_weights will be empty. self.w = vs.get_variable('weights', shape=[input_shape[-1].value, self.units], initializer=self.weights_initializer, regularizer=self.weights_regularizer, dtype=self.dtype, trainable=True) if self.use_bias: self.bias = vs.get_variable('bias', shape=[self.units,], initializer=self.bias_initializer, regularizer=self.bias_regularizer, dtype=self._dtype, trainable=True) else: self.bias = None def call(self, inputs): shape = inputs.get_shape().as_list() input_dim = shape[-1] output_shape = shape[:-1] + [self.units] if len(output_shape) > 2: # Reshape the input to 2D. output_shape_tensors = array_ops.unpack(array_ops.shape(inputs)) output_shape_tensors[-1] = self.units output_shape_tensor = array_ops.pack(output_shape_tensors) inputs = array_ops.reshape(inputs, [-1, input_dim]) outputs = standard_ops.matmul(inputs, self.w) if self.use_bias: outputs = nn.bias_add(outputs, self.bias) if len(output_shape) > 2: # Reshape the output back to the original ndim of the input. outputs = array_ops.reshape(outputs, output_shape_tensor) outputs.set_shape(output_shape) if self.activation is not None: return self.activation(outputs) # pylint: disable=not-callable return outputs def dense( inputs, units, activation=None, use_bias=True, weights_initializer=None, bias_initializer=init_ops.zeros_initializer, weights_regularizer=None, bias_regularizer=None, activity_regularizer=None, trainable=True, name=None, reuse=False): """Functional interface for the densely-connected layer. This layer implements the operation `outputs = activation(inputs.w + b)` Where `activation` is the activation function passed as the `activation` argument (if not `None`), `w` is a weights matrix created by the layer, and `b` is a bias vector created by the layer (only if `use_bias` is `True`). Note: if the `inputs` tensor has a rank greater than 2, then it is flattened prior to the initial matrix multiply by `w`. Arguments: inputs: Tensor input. units: Integer or Long, dimensionality of the output space. activation: Activation function (callable). Set it to None to maintain a linear activation. use_bias: Boolean, whether the layer uses a bias. weights_initializer: Initializer function for the weight matrix. bias_initializer: Initializer function for the bias. weights_regularizer: Regularizer function for the weight matrix. bias_regularizer: Regularizer function for the bias. activity_regularizer: Regularizer function for the output. trainable: Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). name: String, the name of the layer. reuse: Boolean, whether to reuse the weights of a previous layer by the same name. Returns: Output tensor. """ layer = Dense(units, activation=activation, use_bias=use_bias, weights_initializer=weights_initializer, bias_initializer=bias_initializer, weights_regularizer=weights_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, trainable=trainable, name=name, dtype=inputs.dtype.base_dtype, _scope=name, _reuse=reuse) return layer.apply(inputs) class Dropout(base._Layer): # pylint: disable=protected-access """Applies Dropout to the input. Dropout consists in randomly setting a fraction `rate` of input units to 0 at each update during training time, which helps prevent overfitting. The units that are kept are scaled by `1 / (1 - rate)`, so that their sum is unchanged at training time and inference time. Arguments: rate: The dropout rate, between 0 and 1. E.g. "rate=0.1" would drop out 10% of input units. noise_shape: 1D tensor of type `int32` representing the shape of the binary dropout mask that will be multiplied with the input. For instance, if your inputs have shape `(batch_size, timesteps, features)`, and you want the dropout mask to be the same for all timesteps, you can use `noise_shape=[batch_size, 1, features]`. seed: A Python integer. Used to create random seeds. See [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed) for behavior. name: The name of the layer (string). """ def __init__(self, rate=0.5, noise_shape=None, seed=None, name=None, **kwargs): super(Dropout, self).__init__(name=name, **kwargs) self.rate = rate self.noise_shape = noise_shape self.seed = seed def call(self, inputs, training=False): if isinstance(training, bool): training_bool = training else: training_bool = tensor_util.constant_value(training) if training_bool is False: return array_ops.identity(inputs) dropped_inputs = nn.dropout(inputs, 1 - self.rate, noise_shape=self.noise_shape, seed=self.seed) if training_bool is True: return dropped_inputs return control_flow_ops.cond(training, lambda: dropped_inputs, lambda: inputs) def dropout(inputs, rate=0.5, noise_shape=None, seed=None, training=False, name=None): """Applies Dropout to the input. Dropout consists in randomly setting a fraction `rate` of input units to 0 at each update during training time, which helps prevent overfitting. The units that are kept are scaled by `1 / (1 - rate)`, so that their sum is unchanged at training time and inference time. Arguments: inputs: Tensor input. rate: The dropout rate, between 0 and 1. E.g. "rate=0.1" would drop out 10% of input units. noise_shape: 1D tensor of type `int32` representing the shape of the binary dropout mask that will be multiplied with the input. For instance, if your inputs have shape `(batch_size, timesteps, features)`, and you want the dropout mask to be the same for all timesteps, you can use `noise_shape=[batch_size, 1, features]`. seed: A Python integer. Used to create random seeds. See [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed) for behavior. training: Either a Python boolean, or a TensorFlow boolean scalar tensor (e.g. a placeholder). Whether to return the output in training mode (apply dropout) or in inference mode (return the input untouched). name: The name of the layer (string). Returns: Output tensor. """ layer = Dropout(rate, noise_shape=noise_shape, seed=seed, name=name) return layer.apply(inputs, training=training) # Aliases FullyConnected = Dense fully_connected = dense
40.857143
79
0.681739
3566024b052f30b3746eca7d117e413e0afc46d9
134,832
py
Python
tests/models/validators/v1_3_0/jsd_7ab9a8bd4f3b86a4.py
daxm/dnacentersdk
5baa0cb151fb9e72cf7af1ae29e7541d89c3f06b
[ "MIT" ]
null
null
null
tests/models/validators/v1_3_0/jsd_7ab9a8bd4f3b86a4.py
daxm/dnacentersdk
5baa0cb151fb9e72cf7af1ae29e7541d89c3f06b
[ "MIT" ]
null
null
null
tests/models/validators/v1_3_0/jsd_7ab9a8bd4f3b86a4.py
daxm/dnacentersdk
5baa0cb151fb9e72cf7af1ae29e7541d89c3f06b
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """DNA Center Retrieves previous Pathtrace data model. Copyright (c) 2019 Cisco and/or its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import fastjsonschema import json from dnacentersdk.exceptions import MalformedRequest from builtins import * class JSONSchemaValidator7Ab9A8Bd4F3B86A4(object): """Retrieves previous Pathtrace request schema definition.""" def __init__(self): super(JSONSchemaValidator7Ab9A8Bd4F3B86A4, self).__init__() self._validator = fastjsonschema.compile(json.loads( '''{ "properties": { "response": { "description": "", "properties": { "detailedStatus": { "description": "", "properties": { "aclTraceCalculation": { "description": "", "type": [ "string", "null" ] }, "aclTraceCalculationFailureReason": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "lastUpdate": { "description": "", "type": [ "string", "null", "number" ] }, "networkElements": { "description": "", "items": { "properties": { "accuracyList": { "description": "", "items": { "properties": { "percent": { "type": [ "number", "null" ] }, "reason": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "detailedStatus": { "description": "", "properties": { "aclTraceCalculation": { "description": "", "type": [ "string", "null" ] }, "aclTraceCalculationFailureReason": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "deviceStatistics": { "description": "", "properties": { "cpuStatistics": { "description": "", "properties": { "fiveMinUsageInPercentage": { "type": [ "number", "null" ] }, "fiveSecsUsageInPercentage": { "type": [ "number", "null" ] }, "oneMinUsageInPercentage": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "memoryStatistics": { "description": "", "properties": { "memoryUsage": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] }, "totalMemory": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "deviceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "deviceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "egressPhysicalInterface": { "description": "", "properties": { "aclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "interfaceStatistics": { "description": "", "properties": { "adminStatus": { "description": "", "type": [ "string", "null" ] }, "inputPackets": { "type": [ "number", "null" ] }, "inputQueueCount": { "type": [ "number", "null" ] }, "inputQueueDrops": { "type": [ "number", "null" ] }, "inputQueueFlushes": { "type": [ "number", "null" ] }, "inputQueueMaxDepth": { "type": [ "number", "null" ] }, "inputRatebps": { "type": [ "number", "null" ] }, "operationalStatus": { "description": "", "type": [ "string", "null" ] }, "outputDrop": { "type": [ "number", "null" ] }, "outputPackets": { "type": [ "number", "null" ] }, "outputQueueCount": { "type": [ "number", "null" ] }, "outputQueueDepth": { "type": [ "number", "null" ] }, "outputRatebps": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "interfaceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "interfaceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "pathOverlayInfo": { "description": "", "items": { "properties": { "controlPlane": { "description": "", "type": [ "string", "null" ] }, "dataPacketEncapsulation": { "description": "", "type": [ "string", "null" ] }, "destIp": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIp": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "vxlanInfo": { "description": "", "properties": { "dscp": { "description": "", "type": [ "string", "null" ] }, "vnid": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatistics": { "description": "", "items": { "properties": { "classMapName": { "description": "", "type": [ "string", "null" ] }, "dropRate": { "type": [ "number", "null" ] }, "numBytes": { "type": [ "number", "null" ] }, "numPackets": { "type": [ "number", "null" ] }, "offeredRate": { "type": [ "number", "null" ] }, "queueBandwidthbps": { "description": "", "type": [ "string", "null" ] }, "queueDepth": { "type": [ "number", "null" ] }, "queueNoBufferDrops": { "type": [ "number", "null" ] }, "queueTotalDrops": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatsCollection": { "description": "", "type": [ "string", "null" ] }, "qosStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "usedVlan": { "description": "", "type": [ "string", "null" ] }, "vrfName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "egressVirtualInterface": { "description": "", "properties": { "aclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "interfaceStatistics": { "description": "", "properties": { "adminStatus": { "description": "", "type": [ "string", "null" ] }, "inputPackets": { "type": [ "number", "null" ] }, "inputQueueCount": { "type": [ "number", "null" ] }, "inputQueueDrops": { "type": [ "number", "null" ] }, "inputQueueFlushes": { "type": [ "number", "null" ] }, "inputQueueMaxDepth": { "type": [ "number", "null" ] }, "inputRatebps": { "type": [ "number", "null" ] }, "operationalStatus": { "description": "", "type": [ "string", "null" ] }, "outputDrop": { "type": [ "number", "null" ] }, "outputPackets": { "type": [ "number", "null" ] }, "outputQueueCount": { "type": [ "number", "null" ] }, "outputQueueDepth": { "type": [ "number", "null" ] }, "outputRatebps": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "interfaceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "interfaceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "pathOverlayInfo": { "description": "", "items": { "properties": { "controlPlane": { "description": "", "type": [ "string", "null" ] }, "dataPacketEncapsulation": { "description": "", "type": [ "string", "null" ] }, "destIp": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIp": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "vxlanInfo": { "description": "", "properties": { "dscp": { "description": "", "type": [ "string", "null" ] }, "vnid": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatistics": { "description": "", "items": { "properties": { "classMapName": { "description": "", "type": [ "string", "null" ] }, "dropRate": { "type": [ "number", "null" ] }, "numBytes": { "type": [ "number", "null" ] }, "numPackets": { "type": [ "number", "null" ] }, "offeredRate": { "type": [ "number", "null" ] }, "queueBandwidthbps": { "description": "", "type": [ "string", "null" ] }, "queueDepth": { "type": [ "number", "null" ] }, "queueNoBufferDrops": { "type": [ "number", "null" ] }, "queueTotalDrops": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatsCollection": { "description": "", "type": [ "string", "null" ] }, "qosStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "usedVlan": { "description": "", "type": [ "string", "null" ] }, "vrfName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "flexConnect": { "description": "", "properties": { "authentication": { "description": "", "enum": [ "LOCAL", "CENTRAL", null ], "type": [ "string", "null" ] }, "dataSwitching": { "description": "", "enum": [ "LOCAL", "CENTRAL", null ], "type": [ "string", "null" ] }, "egressAclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "ingressAclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "wirelessLanControllerId": { "description": "", "type": [ "string", "null" ] }, "wirelessLanControllerName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "ingressPhysicalInterface": { "description": "", "properties": { "aclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "interfaceStatistics": { "description": "", "properties": { "adminStatus": { "description": "", "type": [ "string", "null" ] }, "inputPackets": { "type": [ "number", "null" ] }, "inputQueueCount": { "type": [ "number", "null" ] }, "inputQueueDrops": { "type": [ "number", "null" ] }, "inputQueueFlushes": { "type": [ "number", "null" ] }, "inputQueueMaxDepth": { "type": [ "number", "null" ] }, "inputRatebps": { "type": [ "number", "null" ] }, "operationalStatus": { "description": "", "type": [ "string", "null" ] }, "outputDrop": { "type": [ "number", "null" ] }, "outputPackets": { "type": [ "number", "null" ] }, "outputQueueCount": { "type": [ "number", "null" ] }, "outputQueueDepth": { "type": [ "number", "null" ] }, "outputRatebps": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "interfaceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "interfaceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "pathOverlayInfo": { "description": "", "items": { "properties": { "controlPlane": { "description": "", "type": [ "string", "null" ] }, "dataPacketEncapsulation": { "description": "", "type": [ "string", "null" ] }, "destIp": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIp": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "vxlanInfo": { "description": "", "properties": { "dscp": { "description": "", "type": [ "string", "null" ] }, "vnid": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatistics": { "description": "", "items": { "properties": { "classMapName": { "description": "", "type": [ "string", "null" ] }, "dropRate": { "type": [ "number", "null" ] }, "numBytes": { "type": [ "number", "null" ] }, "numPackets": { "type": [ "number", "null" ] }, "offeredRate": { "type": [ "number", "null" ] }, "queueBandwidthbps": { "description": "", "type": [ "string", "null" ] }, "queueDepth": { "type": [ "number", "null" ] }, "queueNoBufferDrops": { "type": [ "number", "null" ] }, "queueTotalDrops": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatsCollection": { "description": "", "type": [ "string", "null" ] }, "qosStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "usedVlan": { "description": "", "type": [ "string", "null" ] }, "vrfName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "ingressVirtualInterface": { "description": "", "properties": { "aclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "interfaceStatistics": { "description": "", "properties": { "adminStatus": { "description": "", "type": [ "string", "null" ] }, "inputPackets": { "type": [ "number", "null" ] }, "inputQueueCount": { "type": [ "number", "null" ] }, "inputQueueDrops": { "type": [ "number", "null" ] }, "inputQueueFlushes": { "type": [ "number", "null" ] }, "inputQueueMaxDepth": { "type": [ "number", "null" ] }, "inputRatebps": { "type": [ "number", "null" ] }, "operationalStatus": { "description": "", "type": [ "string", "null" ] }, "outputDrop": { "type": [ "number", "null" ] }, "outputPackets": { "type": [ "number", "null" ] }, "outputQueueCount": { "type": [ "number", "null" ] }, "outputQueueDepth": { "type": [ "number", "null" ] }, "outputRatebps": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "interfaceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "interfaceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "pathOverlayInfo": { "description": "", "items": { "properties": { "controlPlane": { "description": "", "type": [ "string", "null" ] }, "dataPacketEncapsulation": { "description": "", "type": [ "string", "null" ] }, "destIp": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIp": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "vxlanInfo": { "description": "", "properties": { "dscp": { "description": "", "type": [ "string", "null" ] }, "vnid": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatistics": { "description": "", "items": { "properties": { "classMapName": { "description": "", "type": [ "string", "null" ] }, "dropRate": { "type": [ "number", "null" ] }, "numBytes": { "type": [ "number", "null" ] }, "numPackets": { "type": [ "number", "null" ] }, "offeredRate": { "type": [ "number", "null" ] }, "queueBandwidthbps": { "description": "", "type": [ "string", "null" ] }, "queueDepth": { "type": [ "number", "null" ] }, "queueNoBufferDrops": { "type": [ "number", "null" ] }, "queueTotalDrops": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatsCollection": { "description": "", "type": [ "string", "null" ] }, "qosStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "usedVlan": { "description": "", "type": [ "string", "null" ] }, "vrfName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "ip": { "description": "", "type": [ "string", "null" ] }, "linkInformationSource": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "perfMonCollection": { "description": "", "type": [ "string", "null" ] }, "perfMonCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "perfMonStatistics": { "description": "", "items": { "properties": { "byteRate": { "type": [ "number", "null" ] }, "destIpAddress": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "inputInterface": { "description": "", "type": [ "string", "null" ] }, "ipv4DSCP": { "description": "", "type": [ "string", "null" ] }, "ipv4TTL": { "type": [ "number", "null" ] }, "outputInterface": { "description": "", "type": [ "string", "null" ] }, "packetBytes": { "type": [ "number", "null" ] }, "packetCount": { "type": [ "number", "null" ] }, "packetLoss": { "type": [ "number", "null" ] }, "packetLossPercentage": { "type": [ "number", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] }, "rtpJitterMax": { "type": [ "number", "null" ] }, "rtpJitterMean": { "type": [ "number", "null" ] }, "rtpJitterMin": { "type": [ "number", "null" ] }, "sourceIpAddress": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "role": { "description": "", "type": [ "string", "null" ] }, "ssid": { "description": "", "type": [ "string", "null" ] }, "tunnels": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "type": { "description": "", "type": [ "string", "null" ] }, "wlanId": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "networkElementsInfo": { "description": "", "items": { "properties": { "accuracyList": { "description": "", "items": { "properties": { "percent": { "type": [ "number", "null" ] }, "reason": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "detailedStatus": { "description": "", "properties": { "aclTraceCalculation": { "description": "", "type": [ "string", "null" ] }, "aclTraceCalculationFailureReason": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "deviceStatistics": { "description": "", "properties": { "cpuStatistics": { "description": "", "properties": { "fiveMinUsageInPercentage": { "type": [ "number", "null" ] }, "fiveSecsUsageInPercentage": { "type": [ "number", "null" ] }, "oneMinUsageInPercentage": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "memoryStatistics": { "description": "", "properties": { "memoryUsage": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] }, "totalMemory": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "deviceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "deviceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "egressInterface": { "description": "", "properties": { "physicalInterface": { "description": "", "properties": { "aclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "interfaceStatistics": { "description": "", "properties": { "adminStatus": { "description": "", "type": [ "string", "null" ] }, "inputPackets": { "type": [ "number", "null" ] }, "inputQueueCount": { "type": [ "number", "null" ] }, "inputQueueDrops": { "type": [ "number", "null" ] }, "inputQueueFlushes": { "type": [ "number", "null" ] }, "inputQueueMaxDepth": { "type": [ "number", "null" ] }, "inputRatebps": { "type": [ "number", "null" ] }, "operationalStatus": { "description": "", "type": [ "string", "null" ] }, "outputDrop": { "type": [ "number", "null" ] }, "outputPackets": { "type": [ "number", "null" ] }, "outputQueueCount": { "type": [ "number", "null" ] }, "outputQueueDepth": { "type": [ "number", "null" ] }, "outputRatebps": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "interfaceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "interfaceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "pathOverlayInfo": { "description": "", "items": { "properties": { "controlPlane": { "description": "", "type": [ "string", "null" ] }, "dataPacketEncapsulation": { "description": "", "type": [ "string", "null" ] }, "destIp": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIp": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "vxlanInfo": { "description": "", "properties": { "dscp": { "description": "", "type": [ "string", "null" ] }, "vnid": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatistics": { "description": "", "items": { "properties": { "classMapName": { "description": "", "type": [ "string", "null" ] }, "dropRate": { "type": [ "number", "null" ] }, "numBytes": { "type": [ "number", "null" ] }, "numPackets": { "type": [ "number", "null" ] }, "offeredRate": { "type": [ "number", "null" ] }, "queueBandwidthbps": { "description": "", "type": [ "string", "null" ] }, "queueDepth": { "type": [ "number", "null" ] }, "queueNoBufferDrops": { "type": [ "number", "null" ] }, "queueTotalDrops": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatsCollection": { "description": "", "type": [ "string", "null" ] }, "qosStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "usedVlan": { "description": "", "type": [ "string", "null" ] }, "vrfName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "virtualInterface": { "description": "", "items": { "properties": { "aclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "interfaceStatistics": { "description": "", "properties": { "adminStatus": { "description": "", "type": [ "string", "null" ] }, "inputPackets": { "type": [ "number", "null" ] }, "inputQueueCount": { "type": [ "number", "null" ] }, "inputQueueDrops": { "type": [ "number", "null" ] }, "inputQueueFlushes": { "type": [ "number", "null" ] }, "inputQueueMaxDepth": { "type": [ "number", "null" ] }, "inputRatebps": { "type": [ "number", "null" ] }, "operationalStatus": { "description": "", "type": [ "string", "null" ] }, "outputDrop": { "type": [ "number", "null" ] }, "outputPackets": { "type": [ "number", "null" ] }, "outputQueueCount": { "type": [ "number", "null" ] }, "outputQueueDepth": { "type": [ "number", "null" ] }, "outputRatebps": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "interfaceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "interfaceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "pathOverlayInfo": { "description": "", "items": { "properties": { "controlPlane": { "description": "", "type": [ "string", "null" ] }, "dataPacketEncapsulation": { "description": "", "type": [ "string", "null" ] }, "destIp": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIp": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "vxlanInfo": { "description": "", "properties": { "dscp": { "description": "", "type": [ "string", "null" ] }, "vnid": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatistics": { "description": "", "items": { "properties": { "classMapName": { "description": "", "type": [ "string", "null" ] }, "dropRate": { "type": [ "number", "null" ] }, "numBytes": { "type": [ "number", "null" ] }, "numPackets": { "type": [ "number", "null" ] }, "offeredRate": { "type": [ "number", "null" ] }, "queueBandwidthbps": { "description": "", "type": [ "string", "null" ] }, "queueDepth": { "type": [ "number", "null" ] }, "queueNoBufferDrops": { "type": [ "number", "null" ] }, "queueTotalDrops": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatsCollection": { "description": "", "type": [ "string", "null" ] }, "qosStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "usedVlan": { "description": "", "type": [ "string", "null" ] }, "vrfName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "flexConnect": { "description": "", "properties": { "authentication": { "description": "", "enum": [ "LOCAL", "CENTRAL", null ], "type": [ "string", "null" ] }, "dataSwitching": { "description": "", "enum": [ "LOCAL", "CENTRAL", null ], "type": [ "string", "null" ] }, "egressAclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "ingressAclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "wirelessLanControllerId": { "description": "", "type": [ "string", "null" ] }, "wirelessLanControllerName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "ingressInterface": { "description": "", "properties": { "physicalInterface": { "description": "", "properties": { "aclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "interfaceStatistics": { "description": "", "properties": { "adminStatus": { "description": "", "type": [ "string", "null" ] }, "inputPackets": { "type": [ "number", "null" ] }, "inputQueueCount": { "type": [ "number", "null" ] }, "inputQueueDrops": { "type": [ "number", "null" ] }, "inputQueueFlushes": { "type": [ "number", "null" ] }, "inputQueueMaxDepth": { "type": [ "number", "null" ] }, "inputRatebps": { "type": [ "number", "null" ] }, "operationalStatus": { "description": "", "type": [ "string", "null" ] }, "outputDrop": { "type": [ "number", "null" ] }, "outputPackets": { "type": [ "number", "null" ] }, "outputQueueCount": { "type": [ "number", "null" ] }, "outputQueueDepth": { "type": [ "number", "null" ] }, "outputRatebps": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "interfaceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "interfaceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "pathOverlayInfo": { "description": "", "items": { "properties": { "controlPlane": { "description": "", "type": [ "string", "null" ] }, "dataPacketEncapsulation": { "description": "", "type": [ "string", "null" ] }, "destIp": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIp": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "vxlanInfo": { "description": "", "properties": { "dscp": { "description": "", "type": [ "string", "null" ] }, "vnid": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatistics": { "description": "", "items": { "properties": { "classMapName": { "description": "", "type": [ "string", "null" ] }, "dropRate": { "type": [ "number", "null" ] }, "numBytes": { "type": [ "number", "null" ] }, "numPackets": { "type": [ "number", "null" ] }, "offeredRate": { "type": [ "number", "null" ] }, "queueBandwidthbps": { "description": "", "type": [ "string", "null" ] }, "queueDepth": { "type": [ "number", "null" ] }, "queueNoBufferDrops": { "type": [ "number", "null" ] }, "queueTotalDrops": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatsCollection": { "description": "", "type": [ "string", "null" ] }, "qosStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "usedVlan": { "description": "", "type": [ "string", "null" ] }, "vrfName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "virtualInterface": { "description": "", "items": { "properties": { "aclAnalysis": { "description": "", "properties": { "aclName": { "description": "", "type": [ "string", "null" ] }, "matchingAces": { "description": "", "items": { "properties": { "ace": { "description": "", "type": [ "string", "null" ] }, "matchingPorts": { "description": "", "items": { "properties": { "ports": { "description": "", "items": { "properties": { "destPorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "sourcePorts": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "result": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "interfaceStatistics": { "description": "", "properties": { "adminStatus": { "description": "", "type": [ "string", "null" ] }, "inputPackets": { "type": [ "number", "null" ] }, "inputQueueCount": { "type": [ "number", "null" ] }, "inputQueueDrops": { "type": [ "number", "null" ] }, "inputQueueFlushes": { "type": [ "number", "null" ] }, "inputQueueMaxDepth": { "type": [ "number", "null" ] }, "inputRatebps": { "type": [ "number", "null" ] }, "operationalStatus": { "description": "", "type": [ "string", "null" ] }, "outputDrop": { "type": [ "number", "null" ] }, "outputPackets": { "type": [ "number", "null" ] }, "outputQueueCount": { "type": [ "number", "null" ] }, "outputQueueDepth": { "type": [ "number", "null" ] }, "outputRatebps": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "interfaceStatsCollection": { "description": "", "type": [ "string", "null" ] }, "interfaceStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "pathOverlayInfo": { "description": "", "items": { "properties": { "controlPlane": { "description": "", "type": [ "string", "null" ] }, "dataPacketEncapsulation": { "description": "", "type": [ "string", "null" ] }, "destIp": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIp": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "vxlanInfo": { "description": "", "properties": { "dscp": { "description": "", "type": [ "string", "null" ] }, "vnid": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatistics": { "description": "", "items": { "properties": { "classMapName": { "description": "", "type": [ "string", "null" ] }, "dropRate": { "type": [ "number", "null" ] }, "numBytes": { "type": [ "number", "null" ] }, "numPackets": { "type": [ "number", "null" ] }, "offeredRate": { "type": [ "number", "null" ] }, "queueBandwidthbps": { "description": "", "type": [ "string", "null" ] }, "queueDepth": { "type": [ "number", "null" ] }, "queueNoBufferDrops": { "type": [ "number", "null" ] }, "queueTotalDrops": { "type": [ "number", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "qosStatsCollection": { "description": "", "type": [ "string", "null" ] }, "qosStatsCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "usedVlan": { "description": "", "type": [ "string", "null" ] }, "vrfName": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] } }, "type": [ "object", "null" ] }, "ip": { "description": "", "type": [ "string", "null" ] }, "linkInformationSource": { "description": "", "type": [ "string", "null" ] }, "name": { "description": "", "type": [ "string", "null" ] }, "perfMonCollection": { "description": "", "type": [ "string", "null" ] }, "perfMonCollectionFailureReason": { "description": "", "type": [ "string", "null" ] }, "perfMonitorStatistics": { "description": "", "items": { "properties": { "byteRate": { "type": [ "number", "null" ] }, "destIpAddress": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "inputInterface": { "description": "", "type": [ "string", "null" ] }, "ipv4DSCP": { "description": "", "type": [ "string", "null" ] }, "ipv4TTL": { "type": [ "number", "null" ] }, "outputInterface": { "description": "", "type": [ "string", "null" ] }, "packetBytes": { "type": [ "number", "null" ] }, "packetCount": { "type": [ "number", "null" ] }, "packetLoss": { "type": [ "number", "null" ] }, "packetLossPercentage": { "type": [ "number", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "refreshedAt": { "type": [ "number", "null" ] }, "rtpJitterMax": { "type": [ "number", "null" ] }, "rtpJitterMean": { "type": [ "number", "null" ] }, "rtpJitterMin": { "type": [ "number", "null" ] }, "sourceIpAddress": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "role": { "description": "", "type": [ "string", "null" ] }, "ssid": { "description": "", "type": [ "string", "null" ] }, "tunnels": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "type": { "description": "", "type": [ "string", "null" ] }, "wlanId": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] }, "type": [ "array", "null" ] }, "properties": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "request": { "description": "", "properties": { "controlPath": { "type": [ "boolean", "null" ] }, "createTime": { "type": [ "number", "null" ] }, "destIP": { "description": "", "type": [ "string", "null" ] }, "destPort": { "description": "", "type": [ "string", "null" ] }, "failureReason": { "description": "", "type": [ "string", "null" ] }, "id": { "description": "", "type": [ "string", "null" ] }, "inclusions": { "description": "", "items": { "type": [ "string", "null" ] }, "type": [ "array", "null" ] }, "lastUpdateTime": { "type": [ "number", "null" ] }, "periodicRefresh": { "type": [ "boolean", "null" ] }, "protocol": { "description": "", "type": [ "string", "null" ] }, "sourceIP": { "description": "", "type": [ "string", "null" ] }, "sourcePort": { "description": "", "type": [ "string", "null" ] }, "status": { "description": "", "type": [ "string", "null" ] } }, "type": [ "object", "null" ] } }, "type": [ "object", "null" ] }, "version": { "description": "", "type": [ "string", "null" ] } }, "type": "object" }'''.replace("\n" + ' ' * 16, '') )) def validate(self, request): try: self._validator(request) except fastjsonschema.exceptions.JsonSchemaException as e: raise MalformedRequest( '{} is invalid. Reason: {}'.format(request, e.message) )
24.631348
78
0.189176
4f0028bfdc39633b26fe4910dd0e09c9293c9928
2,533
py
Python
backend/opnreco/models/dbmeta.py
OpenPaymentNetwork/opnreco
99c8955d7e200fe11fc23c3568879c543940b168
[ "MIT" ]
null
null
null
backend/opnreco/models/dbmeta.py
OpenPaymentNetwork/opnreco
99c8955d7e200fe11fc23c3568879c543940b168
[ "MIT" ]
null
null
null
backend/opnreco/models/dbmeta.py
OpenPaymentNetwork/opnreco
99c8955d7e200fe11fc23c3568879c543940b168
[ "MIT" ]
null
null
null
from opnreco.render import get_json_default from sqlalchemy import engine_from_config from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import configure_mappers import json import os import zope.sqlalchemy # import or define all models here to ensure they are attached to the # Base.metadata prior to any initialization routines from opnreco.models.db import all_metadata_defined as __all # noqa # run configure_mappers after defining all of the models to ensure # all relationships can be setup configure_mappers() def json_dumps_extra(value): return json.dumps( value, separators=(',', ':'), indent='', sort_keys=True, default=get_json_default) def get_engine(prefix='sqlalchemy_'): return engine_from_config( os.environ, prefix, json_serializer=json_dumps_extra) def get_dbsession_factory(engine): factory = sessionmaker() factory.configure(bind=engine) return factory def get_tm_dbsession(dbsession_factory, transaction_manager): """ Get a ``sqlalchemy.orm.Session`` instance backed by a transaction. This function will hook the session to the transaction manager which will take care of committing any changes. - When using pyramid_tm it will automatically be committed or aborted depending on whether an exception is raised. - When using scripts you should wrap the session in a manager yourself. For example:: import transaction engine = get_engine(settings) session_factory = get_session_factory(engine) with transaction.manager: dbsession = get_tm_session(session_factory, transaction.manager) """ dbsession = dbsession_factory() zope.sqlalchemy.register( dbsession, transaction_manager=transaction_manager) return dbsession def includeme(config): """ Initialize the model for a Pyramid app. Activate this setup using ``config.include('testalchemy.models')``. """ # use pyramid_tm to hook the transaction lifecycle to the request config.include('pyramid_tm') dbsession_factory = get_dbsession_factory(get_engine()) config.registry['dbsession_factory'] = dbsession_factory def dbsession(request): return get_tm_dbsession(dbsession_factory, request.tm) # make request.dbsession available for use in Pyramid config.add_request_method( # request.tm is the transaction manager provided by pyramid_tm. dbsession, 'dbsession', reify=True)
29.453488
78
0.72878
f4ca004cbafc8c4521bde01f0bd6bb227a41f93e
1,741
py
Python
memodrop/urls.py
mhndlsz/memodrop
7ba39143c8e4fbe67881b141accedef535e936e6
[ "MIT" ]
18
2018-04-15T14:01:25.000Z
2022-03-16T14:57:28.000Z
memodrop/urls.py
mhndlsz/memodrop
7ba39143c8e4fbe67881b141accedef535e936e6
[ "MIT" ]
null
null
null
memodrop/urls.py
mhndlsz/memodrop
7ba39143c8e4fbe67881b141accedef535e936e6
[ "MIT" ]
4
2018-04-15T14:16:12.000Z
2020-08-10T14:31:48.000Z
"""memodrop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ import watchman.views from django.conf.urls import url, include from django.contrib import admin from django.urls import reverse_lazy from django.views.generic import RedirectView from rest_framework.authtoken import views as auth_token_views urlpatterns = [ url(r'^$', RedirectView.as_view(url=reverse_lazy('braindump-index'), permanent=False), name='index'), url(r'^authentication/', include('authentication.urls.gui')), url(r'^admin/', admin.site.urls), url(r'^admin/health/$', watchman.views.bare_status), url(r'^api/(?P<version>(v1))/auth/', include('rest_framework.urls')), url(r'^api/(?P<version>(v1))/authentication/', include('authentication.urls.api')), url(r'^api/(?P<version>(v1))/auth-token/', auth_token_views.obtain_auth_token), url(r'^api/(?P<version>(v1))/categories/', include('categories.urls.api')), url(r'^api/(?P<version>(v1))/cards/', include('cards.urls.api')), url(r'^braindump/', include('braindump.urls')), url(r'^cards/', include('cards.urls.gui')), url(r'^categories/', include('categories.urls.gui')), ]
44.641026
87
0.693854
ab4a75c04a0fe9097c592c76275e2b7a52a27174
28,660
py
Python
wemake_python_styleguide/violations/refactoring.py
toennifer/wemake-python-styleguide
12f942035aec4a34d38e24df89b150b88f35e021
[ "MIT" ]
null
null
null
wemake_python_styleguide/violations/refactoring.py
toennifer/wemake-python-styleguide
12f942035aec4a34d38e24df89b150b88f35e021
[ "MIT" ]
null
null
null
wemake_python_styleguide/violations/refactoring.py
toennifer/wemake-python-styleguide
12f942035aec4a34d38e24df89b150b88f35e021
[ "MIT" ]
null
null
null
""" These checks ensure that you don't have patterns that can be refactored. There are so many ways of doing the same thing in Python. Here we collect know patterns that can be rewritten into much easier or just more pythonic version. .. currentmodule:: wemake_python_styleguide.violations.refactoring Summary ------- .. autosummary:: :nosignatures: UselessLoopElseViolation UselessFinallyViolation SimplifiableIfViolation UselessReturningElseViolation NegatedConditionsViolation NestedTryViolation UselessLambdaViolation UselessLenCompareViolation NotOperatorWithCompareViolation NestedTernaryViolation WrongInCompareTypeViolation UnmergedIsinstanceCallsViolation WrongIsinstanceWithTupleViolation ImplicitElifViolation ImplicitInConditionViolation OpenWithoutContextManagerViolation TypeCompareViolation PointlessStarredViolation ImplicitEnumerateViolation ImplicitSumViolation FalsyConstantCompareViolation WrongIsCompareViolation ImplicitPrimitiveViolation AlmostSwappedViolation MisrefactoredAssignmentViolation InCompareWithSingleItemContainerViolation ImplicitYieldFromViolation NotATupleArgumentViolation ImplicitItemsIteratorViolation ImplicitDictGetViolation ImplicitNegativeIndexViolation SimplifiableReturningIfViolation Refactoring opportunities ------------------------- .. autoclass:: UselessLoopElseViolation .. autoclass:: UselessFinallyViolation .. autoclass:: SimplifiableIfViolation .. autoclass:: UselessReturningElseViolation .. autoclass:: NegatedConditionsViolation .. autoclass:: NestedTryViolation .. autoclass:: UselessLambdaViolation .. autoclass:: UselessLenCompareViolation .. autoclass:: NotOperatorWithCompareViolation .. autoclass:: NestedTernaryViolation .. autoclass:: WrongInCompareTypeViolation .. autoclass:: UnmergedIsinstanceCallsViolation .. autoclass:: WrongIsinstanceWithTupleViolation .. autoclass:: ImplicitElifViolation .. autoclass:: ImplicitInConditionViolation .. autoclass:: OpenWithoutContextManagerViolation .. autoclass:: TypeCompareViolation .. autoclass:: PointlessStarredViolation .. autoclass:: ImplicitEnumerateViolation .. autoclass:: ImplicitSumViolation .. autoclass:: FalsyConstantCompareViolation .. autoclass:: WrongIsCompareViolation .. autoclass:: ImplicitPrimitiveViolation .. autoclass:: AlmostSwappedViolation .. autoclass:: MisrefactoredAssignmentViolation .. autoclass:: InCompareWithSingleItemContainerViolation .. autoclass:: ImplicitYieldFromViolation .. autoclass:: NotATupleArgumentViolation .. autoclass:: ImplicitItemsIteratorViolation .. autoclass:: ImplicitDictGetViolation .. autoclass:: ImplicitNegativeIndexViolation .. autoclass:: SimplifiableReturningIfViolation """ from typing_extensions import final from wemake_python_styleguide.violations.base import ( ASTViolation, TokenizeViolation, ) @final class UselessLoopElseViolation(ASTViolation): """ Forbid ``else`` without ``break`` in a loop. We use the same logic for ``for`` and ``while`` loops. Reasoning: When there's no ``break`` keyword in loop's body it means that ``else`` will always be called. This rule will reduce complexity, improve readability, and protect from possible errors. Solution: Refactor your ``else`` case logic to be inside the loop's body. Or right after it. Example:: # Correct: for letter in 'abc': if letter == 'b': break else: print('"b" is not found') for letter in 'abc': print(letter) print('always called') # Wrong: for letter in 'abc': print(letter) else: print('always called') .. versionadded:: 0.3.0 .. versionchanged:: 0.11.0 """ error_template = 'Found `else` in a loop without `break`' code = 500 previous_codes = {436} @final class UselessFinallyViolation(ASTViolation): """ Forbid ``finally`` in ``try`` block without ``except`` block. However, we allow to use ``try`` with just ``finally`` block when function or method is decorated. Because we cannot control what is going on in this decorator. It might be ``@contextmanager`` or similar thing that requires this API. Reasoning: This rule will reduce complexity and improve readability. Solution: Refactor your ``try`` logic. Replace the ``try-finally`` statement with a ``with`` statement. Example:: # Correct: with open("filename") as f: f.write(...) # Wrong: try: f = open("filename") f.write(...) finally: f.close() .. versionadded:: 0.3.0 .. versionchanged:: 0.11.0 .. versionchanged:: 0.14.0 """ error_template = 'Found `finally` in `try` block without `except`' code = 501 previous_codes = {437} @final class SimplifiableIfViolation(ASTViolation): """ Forbid simplifiable ``if`` conditions. Reasoning: These complex constructions can cause frustration among other developers. They are longer, more verbose, and more complex. Solution: Either use ``bool()`` to convert test values to boolean values, or just leave it as it is in case your test already returns a boolean value. Use can also use ``not`` keyword to switch boolean values. Example:: # Correct: my_bool = bool(some_call()) other_value = 8 if some_call() else None # Wrong: my_bool = True if some_call() else False We only check ``if`` nodes where ``True`` and ``False`` values are used. We check both ``if`` nodes and ``if`` expressions. .. versionadded:: 0.7.0 .. versionchanged:: 0.11.0 """ error_template = 'Found simplifiable `if` condition' code = 502 previous_codes = {451} @final class UselessReturningElseViolation(ASTViolation): """ Forbid useless ``else`` cases in returning functions. We check single ``if`` statements that all contain ``return`` or ``raise`` or ``break`` statements with this rule. We do not check ``if`` statements with ``elif`` cases. Reasoning: Using extra ``else`` creates a situation when the whole node could and should be dropped without any changes in logic. So, we prefer to have less code than more code. Solution: Remove useless ``else`` case. Example:: # Correct: def some_function(): if some_call(): return 'yeap' return 'nope' # Wrong: def some_function(): if some_call(): raise ValueError('yeap') else: raise ValueError('nope') .. versionadded:: 0.7.0 .. versionchanged:: 0.11.0 """ error_template = 'Found useless returning `else` statement' code = 503 previous_codes = {457} @final class NegatedConditionsViolation(ASTViolation): """ Forbid negated conditions together with ``else`` clause. Reasoning: It easier to read and name regular conditions. Not negated ones. Solution: Move actions from the negated ``if`` condition to the ``else`` condition. Example:: # Correct: if some == 1: ... else: ... if not some: ... if not some: ... elif other: ... # Wrong: if not some: ... else: ... .. versionadded:: 0.8.0 .. versionchanged:: 0.11.0 """ error_template = 'Found negated condition' code = 504 previous_codes = {463} @final class NestedTryViolation(ASTViolation): """ Forbid nested ``try`` blocks. Notice, we check all possible slots for ``try`` block: 1. the ``try`` block itself 2. all ``except`` cases 3. ``else`` case 4. and ``finally`` case Reasoning: Nesting ``try`` blocks indicates that something really bad happens to your logic. Why does it require two separate exception handlers? It is a perfect case to refactor your code. Solution: Collapse two exception handlers together. Or create a separate function that will handle this second nested case. Example:: # Wrong: try: try: ... except SomeException: ... except SomeOtherException: ... try: ... except SomeOtherException: try: ... except SomeException: ... .. versionadded:: 0.8.0 .. versionchanged:: 0.11.0 """ error_template = 'Found nested `try` block' code = 505 previous_codes = {464} @final class UselessLambdaViolation(ASTViolation): """ Forbid useless proxy ``lambda`` expressions. Reasoning: Sometimes developers tend to overuse ``lambda`` expressions and they wrap code that can be passed as is, without extra wrapping. The code without extra ``lambda`` is easier to read and is more performant. Solution: Remove wrapping ``lambda`` declaration, use just the internal function. Example:: # Correct: numbers = map(int, ['1', '2']) # Wrong: numbers = map(lambda string: int(string), ['1', '2']) .. versionadded:: 0.10.0 .. versionchanged:: 0.11.0 """ error_template = 'Found useless lambda declaration' code = 506 previous_codes = {467} @final class UselessLenCompareViolation(ASTViolation): """ Forbid unpythonic zero-length compare. Note, that we allow to check arbitrary length, like ``len(arr) == 3``. Reasoning: Python's structures like dicts, lists, sets, and tuples all have ``__bool__`` method to checks their length. So, there's no point in wrapping them into ``len(...)`` and checking that it is bigger that ``0`` or less then ``1``, etc. Solution: Remove extra ``len()`` call. Example:: # Correct: if some_array or not other_array or len(third_array) == 1: ... # Wrong: if len(some_array) > 0 or len(other_array) < 1: ... .. versionadded:: 0.10.0 .. versionchanged:: 0.11.0 """ error_template = 'Found useless `len()` compare' code = 507 previous_codes = {468} @final class NotOperatorWithCompareViolation(ASTViolation): """ Forbid ``not`` with compare expressions. Reasoning: This version of ``not`` operator is unreadable. Solution: Refactor the expression without ``not`` operator. Change the compare signs. Example:: # Correct: if x <= 5: ... # Wrong: if not x > 5: ... .. versionadded:: 0.10.0 .. versionchanged:: 0.11.0 """ error_template = 'Found incorrect `not` with compare usage' code = 508 previous_codes = {470} @final class NestedTernaryViolation(ASTViolation): """ Forbid nesting ternary expressions in certain places. Note, that we restrict to nest ternary expressions inside: - ``if`` conditions - boolean and binary operations like ``and`` or ``+`` - unary operators Reasoning: Nesting ternary in random places can lead to very hard debug and testing problems. Solution: Refactor the ternary expression to be either a new variable, or nested ``if`` statement, or a new function. Example:: # Correct: some = x if cond() else y # Wrong: if x if cond() else y: ... .. versionadded:: 0.10.0 .. versionchanged:: 0.11.0 """ error_template = 'Found incorrectly nested ternary' code = 509 previous_codes = {472} @final class WrongInCompareTypeViolation(ASTViolation): """ Forbid ``in`` with static containers except ``set`` nodes. We enforce people to use sets as a static containers. You can also use variables, calls, methods, etc. Dynamic values are not checked. Reasoning: Using static ``list``, ``tuple``, or ``dict`` elements to check that some element is inside the container is a bad practice. Because we need to iterate all over the container to find the element. Sets are the best suit for this task. Moreover, it makes your code consistent. Solution: Use ``set`` elements or comprehensions to check that something is contained in a container. Example:: # Correct: print(needle in {'one', 'two'}) # Wrong: print(needle in ['one', 'two']) .. versionadded:: 0.10.0 .. versionchanged:: 0.11.0 .. versionchanged:: 0.14.0 """ error_template = 'Found `in` used with a non-set container' code = 510 previous_codes = {473} @final class UnmergedIsinstanceCallsViolation(ASTViolation): """ Forbid multiple ``isinstance`` calls on the same variable. Reasoning: The best practice is to use ``isinstance`` with tuple as the second argument, instead of multiple conditions joined with ``or``. Solution: Use tuple of types as the second argument. Example:: # Correct: isinstance(some, (int, float)) # Wrong: isinstance(some, int) or isinstance(some, float) See also: https://docs.python.org/3/library/functions.html#isinstance .. versionadded:: 0.10.0 .. versionchanged:: 0.11.0 """ error_template = ( 'Found separate `isinstance` calls that can be merged for: {0}' ) code = 511 previous_codes = {474} @final class WrongIsinstanceWithTupleViolation(ASTViolation): """ Forbid multiple ``isinstance`` calls with single-item tuples. Reasoning: There's no need to use tuples with single elements. You can use single variables or tuples with multiple elements. Solution: Use tuples with multiple elements or a single variable. Example:: # Correct: isinstance(some, (int, float)) isinstance(some, int) # Wrong: isinstance(some, (int, )) See: https://docs.python.org/3/library/functions.html#isinstance .. versionadded:: 0.10.0 .. versionchanged:: 0.11.0 """ error_template = 'Found `isinstance` call with a single element tuple' code = 512 previous_codes = {475} @final class ImplicitElifViolation(TokenizeViolation): """ Forbid implicit ``elif`` conditions. Reasoning: Nested ``if`` in ``else`` cases are bad for readability because of the nesting level. Solution: Use ``elif`` on the same level. Example:: # Correct: if some: ... elif other: ... # Wrong: if some: ... else: if other: ... .. versionadded:: 0.12.0 """ error_template = 'Found implicit `elif` condition' code = 513 @final class ImplicitInConditionViolation(ASTViolation): """ Forbid multiple equality comparisons with the same variable. Reasoning: Using double+ equality compare with ``or`` or double+ non-equality compare with ``and`` indicates that you have implicit ``in`` or ``not in`` condition. It is just hidden from you. Solution: Refactor compares to use ``in`` or ``not in`` clauses. Example:: # Correct: print(some in {'first', 'second'}) print(some not in {'first', 'second'}) # Wrong: print(some == 'first' or some == 'second') print(some != 'first' and some != 'second') .. versionadded:: 0.10.0 .. versionchanged:: 0.12.0 """ code = 514 error_template = 'Found implicit `in` condition' previous_codes = {336} @final class OpenWithoutContextManagerViolation(ASTViolation): """ Forbid ``open()`` without a context manager. Reasoning: When you ``open()`` something, you need to close it. When using a context manager - it is automatically done for you. When not using it - you might find yourself in a situation when file is not closed and is not accessible anymore. Solution: Refactor ``open()`` call to use ``with``. Example:: # Correct: with open(filename) as file_obj: ... # Wrong: file_obj = open(filename) .. versionadded:: 0.12.0 """ code = 515 error_template = 'Found `open()` used without a context manager' @final class TypeCompareViolation(ASTViolation): """ Forbid comparing types with ``type()`` function. Reasoning: When you compare types with ``type()`` function call it means that you break polymorphism and disallow child classes of a node to work here. That's incorrect. Solution: Use ``isinstance`` to compare types. Example:: # Correct: print(something, type(something)) # Wrong: if type(something) == int: ... .. versionadded:: 0.12.0 """ code = 516 error_template = 'Found `type()` used to compare types' @final class PointlessStarredViolation(ASTViolation): """ Forbid useless starred expressions. Reasoning: Using starred expression with constants is useless. This piece of code can be rewritten to be flat. Eg.: ``print(*[1, 2, 3])`` is ``print(1, 2, 3)``. Solution: Refactor your code not to use starred expressions with ``list``, ``dict``, ``tuple``, and ``set`` constants. Use regular argument passing instead. Example:: # Correct: my_list = [1, 2, 3, *other_iterable] # Wrong: print(*[1, 2, 3], **{{}}) .. versionadded:: 0.12.0 """ code = 517 error_template = 'Found pointless starred expression' @final class ImplicitEnumerateViolation(ASTViolation): """ Forbid implicit ``enumerate()`` calls. Reasoning: Using ``range(len(...))`` is not pythonic. Python uses collection iterators, not index-based loops. Solution: Use ``enumerate(...)`` instead of ``range(len(...))``. Example:: # Correct: for index, person in enumerate(people): ... # Wrong: for index in range(len(people)): ... See also: https://docs.python.org/3/library/functions.html#enumerate .. versionadded:: 0.12.0 """ code = 518 error_template = 'Found implicit `enumerate()` call' @final class ImplicitSumViolation(ASTViolation): """ Forbid implicit ``sum()`` calls. When summing types different from numbers, you might need to provide the second argument to the ``sum`` function: ``sum([[1], [2], [3]], [])`` You might also use ``str.join`` to join iterable of strings. Reasoning: Using ``for`` loops with ``+=`` assign inside indicates that you iteratively sum things inside your collection. That's what ``sum()`` builtin function does. Solution: Use ``sum(...)`` instead of a loop with ``+=`` operation. Example:: # Correct: sum_result = sum(get_elements()) # Wrong: sum_result = 0 for to_sum in get_elements(): sum_result += to_sum See also: https://docs.python.org/3/library/functions.html#sum https://docs.python.org/3/library/stdtypes.html#str.join .. versionadded:: 0.12.0 """ code = 519 error_template = 'Found implicit `sum()` call' @final class FalsyConstantCompareViolation(ASTViolation): """ Forbid comparing with explicit falsy constants. We allow to compare with falsy numbers, strings, booleans, ``None``. We disallow complex constants like tuple, dicts, and lists. Reasoning: When comparing ``something`` with explicit falsy constants what we really mean is ``not something``. Solution: Use ``not`` with your variable. Fix your data types. Example:: # Correct: if not my_check: ... if some_other is None: ... if some_num == 0: ... # Wrong: if my_check == []: ... .. versionadded:: 0.12.0 """ code = 520 error_template = 'Found compare with falsy constant' @final class WrongIsCompareViolation(ASTViolation): """ Forbid comparing values with constants using ``is`` or ``is not``. However, we allow to compare with ``None`` and booleans. Reasoning: ``is`` compares might not do what you want them to do. Firstly, they check for the same object, not equality. Secondly, they behave unexpectedly even with the simple values like ``257``. Solution: Use ``==`` to compare with constants. Example:: # Correct: if my_check == [1, 2, 3]: ... # Wrong: if my_check is [1, 2, 3]: ... See also: https://stackoverflow.com/a/33130014/4842742 .. versionadded:: 0.12.0 """ code = 521 error_template = 'Found wrong `is` compare' @final class ImplicitPrimitiveViolation(ASTViolation): """ Forbid implicit primitives in the form of ``lambda`` functions. Reasoning: When you use ``lambda`` that returns a primitive value and takes no arguments, it means that you should use a primitive type instead. Solution: Replace ``lambda`` with ``int``, ``float``, ``list``, or any other primitive. Example:: # Correct: defaultdict(int) # Wrong: defaultdict(lambda: 0) .. versionadded:: 0.13.0 """ code = 522 error_template = 'Found implicit primitive in a form of `lambda`' @final class AlmostSwappedViolation(ASTViolation): """ Forbid unpythonic variable swaps. We check for ``a = b; b = a`` sequences. Reasoning: This looks like a failed attempt to swap. Solution: Use standard way to swap two variables. Example:: # Correct: a, b = b, a # Wrong: a = b b = a temp = a a = b b = temp .. versionadded:: 0.13.0 """ error_template = 'Found incorrectly swapped variables' code = 523 @final class MisrefactoredAssignmentViolation(ASTViolation): """ Forbid misrefactored self assignment. Reasoning: Self assignment does not need to have the same operand on the left hand side and on the right hand side. Solution: Refactor you code to use multiple self assignments or fix your code. Example:: # Correct: test += 1 test *= 2 # Wrong: test += test + 1 See :py:data:`~wemake_python_styleguide.constants.MATH_APPROXIMATE_CONSTANTS` for full list of math constants that we check for. .. versionadded:: 0.13.0 """ error_template = 'Found self assignment with refactored assignment' code = 524 @final class InCompareWithSingleItemContainerViolation(ASTViolation): """ Forbid comparisons where ``in`` is compared with single item container. Reasoning: ``in`` comparison with a container which contains only one item looks like overhead and unneeded complexity. Solution: Refactor your code to use ``==`` instead ``in``. Example:: # Correct: a == 's' # Wrong: a in {'s'} .. versionadded:: 0.13.0 """ error_template = 'Found wrong `in` compare with single item container' code = 525 @final class ImplicitYieldFromViolation(ASTViolation): """ Forbid ``yield`` inside ``for`` loop instead of ``yield from``. Reasoning: It is known that ``yield from`` is a semantically identical to a ``for`` loop with a ``yield`` inside. But, it is way more readable. Solution: Use ``yield from`` some iterable directly instead iterating over it inside a loop and ``yield`` it one by one. Example:: # Correct: yield from some() yield from ( value[index:index + chunk_size] for index in range(0, len(value), chunk_size) ) # Wrong: for index in chunk: yield index .. versionadded:: 0.13.0 """ error_template = 'Found implicit `yield from` usage' code = 526 @final class NotATupleArgumentViolation(ASTViolation): """ Require tuples as arguments for certain functions. Reasoning: For some functions, it is better to use tuples instead of another iterable types (list, sets,...) as arguments. Solution: Use tuples as arguments. Example:: # Correct: a = frozenset((2,)) # Wrong: a = frozenset([2]) See :py:data:`~wemake_python_styleguide.constants.TUPLE_ARGUMENTS_METHODS` for full list of methods that we check for. .. versionadded:: 0.13.0 """ error_template = 'Found not a tuple used as an argument' code = 527 @final class ImplicitItemsIteratorViolation(ASTViolation): """ Forbid implicit ``.items()`` iterator. Reasoning: When iterating over collection it is easy to forget to use ``.items()`` when you need to access both keys and values. So, when you access the iterable with the key inside a ``for`` loop, that's a sign to refactor your code. Solution: Use ``.items()`` with direct keys and values when you need them. Example:: # Correct: for some_key, some_value in collection.items(): print(some_key, some_value) # Wrong: for some_key in collection: print(some_key, collection[some_key]) .. versionadded:: 0.13.0 """ error_template = 'Found implicit `.items()` usage' code = 528 @final class ImplicitDictGetViolation(ASTViolation): """ Forbid implicit ``.get()`` dict method. Reasoning: When using ``in`` with a dict key it is hard to keep the code clean. It is more convenient to use ``.get()`` and check for ``None`` later. Solution: Use ``.get()`` with the key you need. Check for ``None`` in case you need it, or just act with the default value of the same type. Example:: # Correct: value = collection.get(key) if value is not None: print(value) # Wrong: if key in collection: print(collection[key]) .. versionadded:: 0.13.0 """ error_template = 'Found implicit `.get()` dict usage' code = 529 @final class ImplicitNegativeIndexViolation(ASTViolation): """ Forbid implicit negative indexes. Reasoning: There's no need in getting the length of an iterable and then having a negative offset, when you can specify negative indexes in the first place. Solution: Use negative indexes. Example:: # Correct: some_list[-1] # Wrong: some_list[len(some_list) - 1] .. versionadded:: 0.13.0 """ error_template = 'Found implicit negative index' code = 530 @final class SimplifiableReturningIfViolation(ASTViolation): """ Forbid if statements that simply return booleans in functions or methods. Reasoning: There is no need to test a condition and simply return a boolean depending on its outcome if there is not going to be any additional code. Solution: Instead of testing the condition and returning a boolean, return the condition itself. This applies to early returning ifs too. Example:: # Correct: def some_function(): return some_condition # Wrong: def some_function(): if some_condition: return True else: return False .. versionadded:: 0.15.0 """ error_template = 'Found simplifiable returning `if` condition in a function' code = 531
23.225284
80
0.612247
8b66471d95f20132753bef73defd69edb21ae489
1,202
py
Python
ott/core/__init__.py
meyerscetbon/ott
7f9aede929b8f202cb56d60bc7bf9d731bd94645
[ "Apache-2.0" ]
null
null
null
ott/core/__init__.py
meyerscetbon/ott
7f9aede929b8f202cb56d60bc7bf9d731bd94645
[ "Apache-2.0" ]
null
null
null
ott/core/__init__.py
meyerscetbon/ott
7f9aede929b8f202cb56d60bc7bf9d731bd94645
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2022 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OTT core libraries: the engines behind most computations happening in OTT.""" # pytype: disable=import-error # kwargs-checking from . import anderson from . import dataclasses from . import discrete_barycenter from . import gromov_wasserstein from . import implicit_differentiation from . import momentum from . import problems from . import sinkhorn from . import sinkhorn_lr from . import neuraldual from .implicit_differentiation import ImplicitDiff from .problems import LinearProblem from .sinkhorn import Sinkhorn from .sinkhorn_lr import LRSinkhorn # pytype: enable=import-error # kwargs-checking
34.342857
80
0.785358
513255dc3f549b45b87b3d0a9de57ee2557de556
2,323
py
Python
tests/test_ratelimit.py
komuw/xyzabc
80a3aafc6d098cc7af7e08d8ebdea7d55cef50b0
[ "MIT" ]
4
2019-07-23T20:40:46.000Z
2019-08-16T15:30:54.000Z
tests/test_ratelimit.py
komuw/wiji
80a3aafc6d098cc7af7e08d8ebdea7d55cef50b0
[ "MIT" ]
73
2019-02-28T10:16:12.000Z
2019-07-25T00:53:38.000Z
tests/test_ratelimit.py
komuw/xyzabc
80a3aafc6d098cc7af7e08d8ebdea7d55cef50b0
[ "MIT" ]
1
2019-08-16T15:31:06.000Z
2019-08-16T15:31:06.000Z
import time import asyncio from unittest import TestCase, mock import wiji def AsyncMock(*args, **kwargs): """ see: https://blog.miguelgrinberg.com/post/unit-testing-asyncio-code """ m = mock.MagicMock(*args, **kwargs) async def mock_coro(*args, **kwargs): return m(*args, **kwargs) mock_coro.mock = m return mock_coro class TestRateLimit(TestCase): """ run tests as: python -m unittest discover -v -s . run one testcase as: python -m unittest -v tests.test_ratelimit.TestRateLimit.test_something """ def setUp(self): self.logger = wiji.logger.SimpleLogger("myTestLogger") self.execution_rate = 1.00 self.rateLimiter = wiji.ratelimiter.SimpleRateLimiter(execution_rate=self.execution_rate) def tearDown(self): pass @staticmethod def _run(coro): loop = asyncio.get_event_loop() return loop.run_until_complete(coro) def test_no_rlimit(self): with mock.patch("wiji.ratelimiter.asyncio.sleep", new=AsyncMock()) as mock_sleep: for _ in range(0, int(self.execution_rate)): self._run(self.rateLimiter.limit()) self.assertFalse(mock_sleep.mock.called) def test_token_exhaustion_causes_rlimit(self): with mock.patch("wiji.ratelimiter.asyncio.sleep", new=AsyncMock()) as mock_sleep: for _ in range(0, int(self.execution_rate) * 2): self._run(self.rateLimiter.limit()) self.assertTrue(mock_sleep.mock.called) self.assertEqual(mock_sleep.mock.call_args[0][0], self.rateLimiter.delay_for_tokens) def test_execution_rate(self): execution_rate = 3.00 rLimiter = wiji.ratelimiter.SimpleRateLimiter( log_handler=self.logger, execution_rate=execution_rate ) msgs_delivered = [] now = time.monotonic() for _ in range(0, int(execution_rate) * 4): z = self._run(rLimiter.limit()) msgs_delivered.append(z) then = time.monotonic() time_taken_to_deliver = then - now # seconds total_msgs_delivered = len(msgs_delivered) effective_message_rate = total_msgs_delivered / time_taken_to_deliver self.assertAlmostEqual(effective_message_rate, execution_rate, 0)
32.71831
97
0.658631
98b1982dd87dc971ddad5b7fbdad15627c83848a
1,877
py
Python
gist/cli.py
thisisibrahimd/gist
846248afdcb4ca6b0990c358f70c600a31659386
[ "Apache-2.0" ]
null
null
null
gist/cli.py
thisisibrahimd/gist
846248afdcb4ca6b0990c358f70c600a31659386
[ "Apache-2.0" ]
null
null
null
gist/cli.py
thisisibrahimd/gist
846248afdcb4ca6b0990c358f70c600a31659386
[ "Apache-2.0" ]
null
null
null
import os import logging import click import os from gist.core import get_gist_score from gist.repo import CritRepo, EhrRepo from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) logger = logging.getLogger(__name__) @click.command() @click.option('-d', '--debug', is_flag=True, envvar="GIST_DEBUG", help="Show debug output. Automatically pulls from environment") @click.option('-ehr', '--ehr-conn-str', required=True, envvar="GIST_EHR_CONN_STR", help="EHR db connection string. Automatically pulls from current environment") @click.option('-crit', '--crit-conn-str', required=True, envvar="GIST_CRIT_CONN_STR", help="CRIT db connection string. Automatically pulls from current environment") @click.option('-t', '--trial_id', 'trial_ids', required=True, multiple=True, envvar="GIST_TRIAL_IDS", help="Trial ID(s)") def cli(debug, trial_ids, ehr_conn_str, crit_conn_str): """OMOP CDM Based Automatic Clinical Trial Generalizability Assessment Framework.""" logging.basicConfig(level=logging.DEBUG if debug else logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.info(f"logging level set to {'debug' if debug else 'info'}") ehr_repo = EhrRepo(ehr_conn_str) crit_repo = CritRepo(crit_conn_str) ehr = ehr_repo.get_ehr() criteria_by_trial_ids = [] for trial_id in trial_ids: criteria_by_trial_id = { 'trial_id': trial_id, 'criteria': crit_repo.get_criteria_by_trial_id(trial_id) } criteria_by_trial_ids.append(criteria_by_trial_id) gist_scores = [] for criteria_by_trial_id in criteria_by_trial_ids: gist_score = get_gist_score(criteria_by_trial_id['trial_id'], criteria_by_trial_id['criteria'], ehr) gist_scores.append(gist_score) logger.info(gist_scores) if __name__ == '__main__': cli(auto_envvar_prefix='GIST')
43.651163
165
0.733617
a23996e5dee23e0a712ecd799abbfaf136634840
11,152
py
Python
sk_dsp_comm/coeff2header.py
toddrme2178/scikit-dsp-comm
e08427dfcf75d8389e921ab4d01ea3d2c7173a52
[ "BSD-2-Clause" ]
null
null
null
sk_dsp_comm/coeff2header.py
toddrme2178/scikit-dsp-comm
e08427dfcf75d8389e921ab4d01ea3d2c7173a52
[ "BSD-2-Clause" ]
null
null
null
sk_dsp_comm/coeff2header.py
toddrme2178/scikit-dsp-comm
e08427dfcf75d8389e921ab4d01ea3d2c7173a52
[ "BSD-2-Clause" ]
null
null
null
""" Digital Filter Coefficient Conversion to C Header Files Copyright (c) March 2017, Mark Wickert All rights reserved. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. """ import numpy as np import scipy.signal as signal import matplotlib.pyplot as plt from matplotlib import pylab from numpy import int16, rint, loadtxt import os def FIR_header(fname_out, h): """ Write FIR Filter Header Files Mark Wickert February 2015 """ M = len(h) N = 3 # Coefficients per line f = open(fname_out, 'wt') f.write('//define a FIR coefficient Array\n\n') f.write('#include <stdint.h>\n\n') f.write('#ifndef M_FIR\n') f.write('#define M_FIR %d\n' % M) f.write('#endif\n') f.write('/************************************************************************/\n'); f.write('/* FIR Filter Coefficients */\n'); f.write('float32_t h_FIR[M_FIR] = {') kk = 0; for k in range(M): # k_mod = k % M if (kk < N - 1) and (k < M - 1): f.write('%15.12f,' % h[k]) kk += 1 elif (kk == N - 1) & (k < M - 1): f.write('%15.12f,\n' % h[k]) if k < M: f.write(' ') kk = 0 else: f.write('%15.12f' % h[k]) f.write('};\n') f.write('/************************************************************************/\n') f.close() def FIR_fix_header(fname_out, h): """ Write FIR Fixed-Point Filter Header Files Mark Wickert February 2015 """ M = len(h) hq = int16(rint(h * 2 ** 15)) N = 8 # Coefficients per line f = open(fname_out, 'wt') f.write('//define a FIR coefficient Array\n\n') f.write('#include <stdint.h>\n\n') f.write('#ifndef M_FIR\n') f.write('#define M_FIR %d\n' % M) f.write('#endif\n') f.write('/************************************************************************/\n'); f.write('/* FIR Filter Coefficients */\n'); f.write('int16_t h_FIR[M_FIR] = {') kk = 0; for k in range(M): # k_mod = k % M if (kk < N - 1) and (k < M - 1): f.write('%5d,' % hq[k]) kk += 1 elif (kk == N - 1) & (k < M - 1): f.write('%5d,\n' % hq[k]) if k < M: f.write(' ') kk = 0 else: f.write('%5d' % hq[k]) f.write('};\n') f.write('/************************************************************************/\n') f.close() def IIR_sos_header(fname_out, SOS_mat): """ Write IIR SOS Header Files File format is compatible with CMSIS-DSP IIR Directform II Filter Functions Mark Wickert March 2015-October 2016 """ Ns, Mcol = SOS_mat.shape f = open(fname_out, 'wt') f.write('//define a IIR SOS CMSIS-DSP coefficient array\n\n') f.write('#include <stdint.h>\n\n') f.write('#ifndef STAGES\n') f.write('#define STAGES %d\n' % Ns) f.write('#endif\n') f.write('/*********************************************************/\n'); f.write('/* IIR SOS Filter Coefficients */\n'); f.write('float32_t ba_coeff[%d] = { //b0,b1,b2,a1,a2,... by stage\n' % (5 * Ns)) for k in range(Ns): if (k < Ns - 1): f.write(' %+-13e, %+-13e, %+-13e,\n' % \ (SOS_mat[k, 0], SOS_mat[k, 1], SOS_mat[k, 2])) f.write(' %+-13e, %+-13e,\n' % \ (-SOS_mat[k, 4], -SOS_mat[k, 5])) else: f.write(' %+-13e, %+-13e, %+-13e,\n' % \ (SOS_mat[k, 0], SOS_mat[k, 1], SOS_mat[k, 2])) f.write(' %+-13e, %+-13e\n' % \ (-SOS_mat[k, 4], -SOS_mat[k, 5])) # for k in range(Ns): # if (k < Ns-1): # f.write(' %15.12f, %15.12f, %15.12f,\n' % \ # (SOS_mat[k,0],SOS_mat[k,1],SOS_mat[k,2])) # f.write(' %15.12f, %15.12f,\n' % \ # (-SOS_mat[k,4],-SOS_mat[k,5])) # else: # f.write(' %15.12f, %15.12f, %15.12f,\n' % \ # (SOS_mat[k,0],SOS_mat[k,1],SOS_mat[k,2])) # f.write(' %15.12f, %15.12f\n' % \ # (-SOS_mat[k,4],-SOS_mat[k,5])) f.write('};\n') f.write('/*********************************************************/\n') f.close() def freqz_resp_list(b, a=np.array([1]), mode='dB', fs=1.0, Npts=1024, fsize=(6, 4)): """ A method for displaying digital filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freq_resp(self,mode = 'dB',Npts = 1024) A method for displaying the filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freqz_resp(b,a=[1],mode = 'dB',Npts = 1024,fsize=(6,4)) Parameters ---------- b : ndarray of numerator coefficients a : ndarray of denominator coefficents mode : display mode: 'dB' magnitude, 'phase' in radians, or 'groupdelay_s' in samples and 'groupdelay_t' in sec, all versus frequency in Hz Npts : number of points to plot; default is 1024 fsize : figure size; defult is (6,4) inches Mark Wickert, January 2015 """ if type(b) == list: # We have a list of filters N_filt = len(b) f = np.arange(0, Npts) / (2.0 * Npts) for n in range(N_filt): w, H = signal.freqz(b[n], a[n], 2 * np.pi * f) if n == 0: plt.figure(figsize=fsize) if mode.lower() == 'db': plt.plot(f * fs, 20 * np.log10(np.abs(H))) if n == N_filt - 1: plt.xlabel('Frequency (Hz)') plt.ylabel('Gain (dB)') plt.title('Frequency Response - Magnitude') elif mode.lower() == 'phase': plt.plot(f * fs, np.angle(H)) if n == N_filt - 1: plt.xlabel('Frequency (Hz)') plt.ylabel('Phase (rad)') plt.title('Frequency Response - Phase') elif (mode.lower() == 'groupdelay_s') or (mode.lower() == 'groupdelay_t'): """ Notes ----- Since this calculation involves finding the derivative of the phase response, care must be taken at phase wrapping points and when the phase jumps by +/-pi, which occurs when the amplitude response changes sign. Since the amplitude response is zero when the sign changes, the jumps do not alter the group delay results. """ theta = np.unwrap(np.angle(H)) # Since theta for an FIR filter is likely to have many pi phase # jumps too, we unwrap a second time 2*theta and divide by 2 theta2 = np.unwrap(2 * theta) / 2. theta_dif = np.diff(theta2) f_diff = np.diff(f) Tg = -np.diff(theta2) / np.diff(w) # For gain almost zero set groupdelay = 0 idx = pylab.find(20 * np.log10(H[:-1]) < -400) Tg[idx] = np.zeros(len(idx)) max_Tg = np.max(Tg) # print(max_Tg) if mode.lower() == 'groupdelay_t': max_Tg /= fs plt.plot(f[:-1] * fs, Tg / fs) plt.ylim([0, 1.2 * max_Tg]) else: plt.plot(f[:-1] * fs, Tg) plt.ylim([0, 1.2 * max_Tg]) if n == N_filt - 1: plt.xlabel('Frequency (Hz)') if mode.lower() == 'groupdelay_t': plt.ylabel('Group Delay (s)') else: plt.ylabel('Group Delay (samples)') plt.title('Frequency Response - Group Delay') else: s1 = 'Error, mode must be "dB", "phase, ' s2 = '"groupdelay_s", or "groupdelay_t"' print(s1 + s2) def CA_code_header(fname_out, Nca): """ Write 1023 bit CA (Gold) Code Header Files Mark Wickert February 2015 """ dir_path = os.path.dirname(os.path.realpath(__file__)) ca = loadtxt(dir_path + '/ca1thru37.txt', dtype=int16, usecols=(Nca - 1,), unpack=True) M = 1023 # code period N = 23 # code bits per line Sca = 'ca' + str(Nca) f = open(fname_out, 'wt') f.write('//define a CA code\n\n') f.write('#include <stdint.h>\n\n') f.write('#ifndef N_CA\n') f.write('#define N_CA %d\n' % M) f.write('#endif\n') f.write('/*******************************************************************/\n'); f.write('/* 1023 Bit CA Gold Code %2d */\n' \ % Nca); f.write('int8_t ca%d[N_CA] = {' % Nca) kk = 0; for k in range(M): # k_mod = k % M if (kk < N - 1) and (k < M - 1): f.write('%d,' % ca[k]) kk += 1 elif (kk == N - 1) & (k < M - 1): f.write('%d,\n' % ca[k]) if k < M: if Nca < 10: f.write(' ') else: f.write(' ') kk = 0 else: f.write('%d' % ca[k]) f.write('};\n') f.write('/*******************************************************************/\n') f.close()
38.857143
93
0.483411
fce784836dbbb9d0f9dd9db1c3315c65c4afaabf
65,342
py
Python
ceilometer/tests/network/test_notifications.py
shahbazn/ceilometer
6308a46f14b21fb39c0e728c150ab4efde5b532a
[ "Apache-2.0" ]
null
null
null
ceilometer/tests/network/test_notifications.py
shahbazn/ceilometer
6308a46f14b21fb39c0e728c150ab4efde5b532a
[ "Apache-2.0" ]
null
null
null
ceilometer/tests/network/test_notifications.py
shahbazn/ceilometer
6308a46f14b21fb39c0e728c150ab4efde5b532a
[ "Apache-2.0" ]
null
null
null
# # Copyright 2012 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for ceilometer.network.notifications """ import mock from ceilometer.network import notifications from ceilometer.tests import base as test NOTIFICATION_NETWORK_CREATE = { u'_context_roles': [u'anotherrole', u'Member'], u'_context_read_deleted': u'no', u'event_type': u'network.create.end', u'timestamp': u'2012-09-27 14:11:27.086575', u'_context_tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'payload': {u'network': {u'status': u'ACTIVE', u'subnets': [], u'name': u'abcedf', u'router:external': False, u'tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'admin_state_up': True, u'shared': False, u'id': u'7fd4eb2f-a38e-4c25-8490-71ca8800c9be'}}, u'priority': u'INFO', u'_context_is_admin': False, u'_context_timestamp': u'2012-09-27 14:11:26.924779', u'_context_user_id': u'b44b7ce67fc84414a5c1660a92a1b862', u'publisher_id': u'network.ubuntu-VirtualBox', u'message_id': u'9e839576-cc47-4c60-a7d8-5743681213b1'} NOTIFICATION_BULK_NETWORK_CREATE = { '_context_roles': [u'_member_', u'heat_stack_owner', u'admin'], u'_context_request_id': u'req-a2dfdefd-b773-4400-9d52-5e146e119950', u'_context_read_deleted': u'no', u'event_type': u'network.create.end', u'_context_user_name': u'admin', u'_context_project_name': u'admin', u'timestamp': u'2014-05-1510: 24: 56.335612', u'_context_tenant_id': u'980ec4870033453ead65c0470a78b8a8', u'_context_tenant_name': u'admin', u'_context_tenant': u'980ec4870033453ead65c0470a78b8a8', u'message_id': u'914eb601-9390-4a72-8629-f013a4c84467', u'priority': 'info', u'_context_is_admin': True, u'_context_project_id': u'980ec4870033453ead65c0470a78b8a8', u'_context_timestamp': u'2014-05-1510: 24: 56.285975', u'_context_user': u'7520940056d54cceb25cbce888300bea', u'_context_user_id': u'7520940056d54cceb25cbce888300bea', u'publisher_id': u'network.devstack', u'payload': { u'networks': [{u'status': u'ACTIVE', u'subnets': [], u'name': u'test2', u'provider: physical_network': None, u'admin_state_up': True, u'tenant_id': u'980ec4870033453ead65c0470a78b8a8', u'provider: network_type': u'local', u'shared': False, u'id': u'7cbc7a66-bbd0-41fc-a186-81c3da5c9843', u'provider: segmentation_id': None}, {u'status': u'ACTIVE', u'subnets': [], u'name': u'test3', u'provider: physical_network': None, u'admin_state_up': True, u'tenant_id': u'980ec4870033453ead65c0470a78b8a8', u'provider: network_type': u'local', u'shared': False, u'id': u'5a7cb86f-1638-4cc1-8dcc-8bbbc8c7510d', u'provider: segmentation_id': None}] } } NOTIFICATION_SUBNET_CREATE = { u'_context_roles': [u'anotherrole', u'Member'], u'_context_read_deleted': u'no', u'event_type': u'subnet.create.end', u'timestamp': u'2012-09-27 14:11:27.426620', u'_context_tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'payload': { u'subnet': { u'name': u'mysubnet', u'enable_dhcp': True, u'network_id': u'7fd4eb2f-a38e-4c25-8490-71ca8800c9be', u'tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'dns_nameservers': [], u'allocation_pools': [{u'start': u'192.168.42.2', u'end': u'192.168.42.254'}], u'host_routes': [], u'ip_version': 4, u'gateway_ip': u'192.168.42.1', u'cidr': u'192.168.42.0/24', u'id': u'1a3a170d-d7ce-4cc9-b1db-621da15a25f5'}}, u'priority': u'INFO', u'_context_is_admin': False, u'_context_timestamp': u'2012-09-27 14:11:27.214490', u'_context_user_id': u'b44b7ce67fc84414a5c1660a92a1b862', u'publisher_id': u'network.ubuntu-VirtualBox', u'message_id': u'd86dfc66-d3c3-4aea-b06d-bf37253e6116'} NOTIFICATION_BULK_SUBNET_CREATE = { '_context_roles': [u'_member_', u'heat_stack_owner', u'admin'], u'_context_request_id': u'req-b77e278a-0cce-4987-9f82-15957b234768', u'_context_read_deleted': u'no', u'event_type': u'subnet.create.end', u'_context_user_name': u'admin', u'_context_project_name': u'admin', u'timestamp': u'2014-05-1510: 47: 08.133888', u'_context_tenant_id': u'980ec4870033453ead65c0470a78b8a8', u'_context_tenant_name': u'admin', u'_context_tenant': u'980ec4870033453ead65c0470a78b8a8', u'message_id': u'c7e6f9fd-ead2-415f-8493-b95bedf72e43', u'priority': u'info', u'_context_is_admin': True, u'_context_project_id': u'980ec4870033453ead65c0470a78b8a8', u'_context_timestamp': u'2014-05-1510: 47: 07.970043', u'_context_user': u'7520940056d54cceb25cbce888300bea', u'_context_user_id': u'7520940056d54cceb25cbce888300bea', u'publisher_id': u'network.devstack', u'payload': { u'subnets': [{u'name': u'', u'enable_dhcp': True, u'network_id': u'3ddfe60b-34b4-4e9d-9440-43c904b1c58e', u'tenant_id': u'980ec4870033453ead65c0470a78b8a8', u'dns_nameservers': [], u'ipv6_ra_mode': None, u'allocation_pools': [{u'start': u'10.0.4.2', u'end': u'10.0.4.254'}], u'host_routes': [], u'ipv6_address_mode': None, u'ip_version': 4, u'gateway_ip': u'10.0.4.1', u'cidr': u'10.0.4.0/24', u'id': u'14020d7b-6dd7-4349-bb8e-8f954c919022'}, {u'name': u'', u'enable_dhcp': True, u'network_id': u'3ddfe60b-34b4-4e9d-9440-43c904b1c58e', u'tenant_id': u'980ec4870033453ead65c0470a78b8a8', u'dns_nameservers': [], u'ipv6_ra_mode': None, u'allocation_pools': [{u'start': u'10.0.5.2', u'end': u'10.0.5.254'}], u'host_routes': [], u'ipv6_address_mode': None, u'ip_version': 4, u'gateway_ip': u'10.0.5.1', u'cidr': u'10.0.5.0/24', u'id': u'a080991b-a32a-4bf7-a558-96c4b77d075c'}] } } NOTIFICATION_PORT_CREATE = { u'_context_roles': [u'anotherrole', u'Member'], u'_context_read_deleted': u'no', u'event_type': u'port.create.end', u'timestamp': u'2012-09-27 14:28:31.536370', u'_context_tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'payload': { u'port': { u'status': u'ACTIVE', u'name': u'', u'admin_state_up': True, u'network_id': u'7fd4eb2f-a38e-4c25-8490-71ca8800c9be', u'tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'device_owner': u'', u'mac_address': u'fa:16:3e:75:0c:49', u'fixed_ips': [{ u'subnet_id': u'1a3a170d-d7ce-4cc9-b1db-621da15a25f5', u'ip_address': u'192.168.42.3'}], u'id': u'9cdfeb92-9391-4da7-95a1-ca214831cfdb', u'device_id': u''}}, u'priority': u'INFO', u'_context_is_admin': False, u'_context_timestamp': u'2012-09-27 14:28:31.438919', u'_context_user_id': u'b44b7ce67fc84414a5c1660a92a1b862', u'publisher_id': u'network.ubuntu-VirtualBox', u'message_id': u'7135b8ab-e13c-4ac8-bc31-75e7f756622a'} NOTIFICATION_BULK_PORT_CREATE = { u'_context_roles': [u'_member_', u'SwiftOperator'], u'_context_request_id': u'req-678be9ad-c399-475a-b3e8-8da0c06375aa', u'_context_read_deleted': u'no', u'event_type': u'port.create.end', u'_context_project_name': u'demo', u'timestamp': u'2014-05-0909: 19: 58.317548', u'_context_tenant_id': u'133087d90fc149528b501dd8b75ea965', u'_context_timestamp': u'2014-05-0909: 19: 58.160011', u'_context_tenant': u'133087d90fc149528b501dd8b75ea965', u'payload': { u'ports': [{u'status': u'DOWN', u'name': u'port--1501135095', u'allowed_address_pairs': [], u'admin_state_up': True, u'network_id': u'acf63fdc-b43b-475d-8cca-9429b843d5e8', u'tenant_id': u'133087d90fc149528b501dd8b75ea965', u'binding: vnic_type': u'normal', u'device_owner': u'', u'mac_address': u'fa: 16: 3e: 37: 10: 39', u'fixed_ips': [], u'id': u'296c2c9f-14e9-48da-979d-78b213454c59', u'security_groups': [ u'a06f7c9d-9e5a-46b0-9f6c-ce812aa2e5ff'], u'device_id': u''}, {u'status': u'DOWN', u'name': u'', u'allowed_address_pairs': [], u'admin_state_up': False, u'network_id': u'0a8eea59-0146-425c-b470-e9ddfa99ec61', u'tenant_id': u'133087d90fc149528b501dd8b75ea965', u'binding: vnic_type': u'normal', u'device_owner': u'', u'mac_address': u'fa: 16: 3e: 8e: 6e: 53', u'fixed_ips': [], u'id': u'd8bb667f-5cd3-4eca-a984-268e25b1b7a5', u'security_groups': [ u'a06f7c9d-9e5a-46b0-9f6c-ce812aa2e5ff'], u'device_id': u''}] }, u'_unique_id': u'60b1650f17fc4fa59492f447321fb26c', u'_context_is_admin': False, u'_context_project_id': u'133087d90fc149528b501dd8b75ea965', u'_context_tenant_name': u'demo', u'_context_user': u'b1eb48f9c54741f4adc1b4ea512d400c', u'_context_user_name': u'demo', u'publisher_id': u'network.os-ci-test12', u'message_id': u'04aa45e1-3c30-4c69-8638-e7ff8621e9bc', u'_context_user_id': u'b1eb48f9c54741f4adc1b4ea512d400c', u'priority': u'INFO' } NOTIFICATION_PORT_UPDATE = { u'_context_roles': [u'anotherrole', u'Member'], u'_context_read_deleted': u'no', u'event_type': u'port.update.end', u'timestamp': u'2012-09-27 14:35:09.514052', u'_context_tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'payload': { u'port': { u'status': u'ACTIVE', u'name': u'bonjour', u'admin_state_up': True, u'network_id': u'7fd4eb2f-a38e-4c25-8490-71ca8800c9be', u'tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'device_owner': u'', u'mac_address': u'fa:16:3e:75:0c:49', u'fixed_ips': [{ u'subnet_id': u'1a3a170d-d7ce-4cc9-b1db-621da15a25f5', u'ip_address': u'192.168.42.3'}], u'id': u'9cdfeb92-9391-4da7-95a1-ca214831cfdb', u'device_id': u''}}, u'priority': u'INFO', u'_context_is_admin': False, u'_context_timestamp': u'2012-09-27 14:35:09.447682', u'_context_user_id': u'b44b7ce67fc84414a5c1660a92a1b862', u'publisher_id': u'network.ubuntu-VirtualBox', u'message_id': u'07b0a3a1-c0b5-40ab-a09c-28dee6bf48f4'} NOTIFICATION_NETWORK_EXISTS = { u'_context_roles': [u'anotherrole', u'Member'], u'_context_read_deleted': u'no', u'event_type': u'network.exists', u'timestamp': u'2012-09-27 14:11:27.086575', u'_context_tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'payload': {u'network': {u'status': u'ACTIVE', u'subnets': [], u'name': u'abcedf', u'router:external': False, u'tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'admin_state_up': True, u'shared': False, u'id': u'7fd4eb2f-a38e-4c25-8490-71ca8800c9be'}}, u'priority': u'INFO', u'_context_is_admin': False, u'_context_timestamp': u'2012-09-27 14:11:26.924779', u'_context_user_id': u'b44b7ce67fc84414a5c1660a92a1b862', u'publisher_id': u'network.ubuntu-VirtualBox', u'message_id': u'9e839576-cc47-4c60-a7d8-5743681213b1'} NOTIFICATION_ROUTER_EXISTS = { u'_context_roles': [u'anotherrole', u'Member'], u'_context_read_deleted': u'no', u'event_type': u'router.exists', u'timestamp': u'2012-09-27 14:11:27.086575', u'_context_tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'payload': {u'router': {'status': u'ACTIVE', 'external_gateway_info': {'network_id': u'89d55642-4dec-43a4-a617-6cec051393b5'}, 'name': u'router1', 'admin_state_up': True, 'tenant_id': u'bb04a2b769c94917b57ba49df7783cfd', 'id': u'ab8bb3ed-df23-4ca0-8f03-b887abcd5c23'}}, u'priority': u'INFO', u'_context_is_admin': False, u'_context_timestamp': u'2012-09-27 14:11:26.924779', u'_context_user_id': u'b44b7ce67fc84414a5c1660a92a1b862', u'publisher_id': u'network.ubuntu-VirtualBox', u'message_id': u'9e839576-cc47-4c60-a7d8-5743681213b1'} NOTIFICATION_FLOATINGIP_EXISTS = { u'_context_roles': [u'anotherrole', u'Member'], u'_context_read_deleted': u'no', u'event_type': u'floatingip.exists', u'timestamp': u'2012-09-27 14:11:27.086575', u'_context_tenant_id': u'82ed0c40ebe64d0bb3310027039c8ed2', u'payload': {u'floatingip': {'router_id': None, 'tenant_id': u'6e5f9df9b3a249ab834f25fe1b1b81fd', 'floating_network_id': u'001400f7-1710-4245-98c3-39ba131cc39a', 'fixed_ip_address': None, 'floating_ip_address': u'172.24.4.227', 'port_id': None, 'id': u'2b7cc28c-6f78-4735-9246-257168405de6'}}, u'priority': u'INFO', u'_context_is_admin': False, u'_context_timestamp': u'2012-09-27 14:11:26.924779', u'_context_user_id': u'b44b7ce67fc84414a5c1660a92a1b862', u'publisher_id': u'network.ubuntu-VirtualBox', u'message_id': u'9e839576-cc47-4c60-a7d8-5743681213b1'} NOTIFICATION_FLOATINGIP_UPDATE_START = { '_context_roles': [u'_member_', u'admin', u'heat_stack_owner'], '_context_request_id': u'req-bd5ed336-242f-4705-836e-8e8f3d0d1ced', '_context_read_deleted': u'no', 'event_type': u'floatingip.update.start', '_context_user_name': u'admin', '_context_project_name': u'admin', 'timestamp': u'2014-05-3107: 19: 43.463101', '_context_tenant_id': u'9fc714821a3747c8bc4e3a9bfbe82732', '_context_tenant_name': u'admin', '_context_tenant': u'9fc714821a3747c8bc4e3a9bfbe82732', 'message_id': u'0ab6d71f-ba0a-4501-86fe-6cc20521ef5a', 'priority': 'info', '_context_is_admin': True, '_context_project_id': u'9fc714821a3747c8bc4e3a9bfbe82732', '_context_timestamp': u'2014-05-3107: 19: 43.460767', '_context_user': u'6ca7b13b33e4425cae0b85e2cf93d9a1', '_context_user_id': u'6ca7b13b33e4425cae0b85e2cf93d9a1', 'publisher_id': u'network.devstack', 'payload': { u'id': u'64262b2a-8f5d-4ade-9405-0cbdd03c1555', u'floatingip': { u'fixed_ip_address': u'172.24.4.227', u'port_id': u'8ab815c8-03cc-4b45-a673-79bdd0c258f2' } } } NOTIFICATION_L3_METER = { u'_context_roles': [u'admin'], u'_context_read_deleted': u'no', u'event_type': u'l3.meter', u'timestamp': u'2013-08-22 13:14:06.880304', u'_context_tenant_id': None, u'payload': {u'first_update': 1377176476, u'bytes': 0, u'label_id': u'383244a7-e99b-433a-b4a1-d37cf5b17d15', u'last_update': 1377177246, u'host': u'precise64', u'tenant_id': u'admin', u'time': 30, u'pkts': 0}, u'priority': u'INFO', u'_context_is_admin': True, u'_context_timestamp': u'2013-08-22 13:01:06.614635', u'_context_user_id': None, u'publisher_id': u'metering.precise64', u'message_id': u'd7aee6e8-c7eb-4d47-9338-f60920d708e4', u'_unique_id': u'd5a3bdacdcc24644b84e67a4c10e886a', u'_context_project_id': None} NOTIFICATION_POOL_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-10715057-7590-4529-8020-b994295ee6f4", "event_type": "pool.create.end", "timestamp": "2014-09-15 17:20:50.687649", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "ce255443233748ce9cc71b480974df28", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "pool": { "status": "ACTIVE", "lb_method": "ROUND_ROBIN", "protocol": "HTTP", "description": "", "health_monitors": [], "members": [], "status_description": None, "id": "6d726518-f3aa-4dd4-ac34-e156a35c0aff", "vip_id": None, "name": "my_pool", "admin_state_up": True, "subnet_id": "afaf251b-2ec3-42ac-9fa9-82a4195724fa", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "health_monitors_status": [], "provider": "haproxy"}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:20:49.600299", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "0a5ed7a6-e516-4aed-9968-4ee9f1b65cc2"} NOTIFICATION_VIP_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "vip.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "vip": { "status": "ACTIVE", "protocol": "HTTP", "description": "", "address": "10.0.0.2", "protocol_port": 80, "port_id": "2b5dd476-11da-4d46-9f1e-7a75436062f6", "id": "87a5ce35-f278-47f3-8990-7f695f52f9bf", "status_description": None, "name": "my_vip", "admin_state_up": True, "subnet_id": "afaf251b-2ec3-42ac-9fa9-82a4195724fa", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "connection_limit": -1, "pool_id": "6d726518-f3aa-4dd4-ac34-e156a35c0aff", "session_persistence": {"type": "SOURCE_IP"}}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "3895ad11-98a3-4031-92af-f76e96736661"} NOTIFICATION_HEALTH_MONITORS_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "health_monitor.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "health_monitor": { "admin_state_up": True, "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "delay": 10, "max_retries": 10, "timeout": 10, "pools": [], "type": "PING", "id": "6dea2d01-c3af-4696-9192-6c938f391f01"}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "65067e3f-830d-4fbb-87e2-f0e51fda83d2"} NOTIFICATION_MEMBERS_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "member.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "member": {"admin_state_up": True, "status": "ACTIVE", "status_description": None, "weight": 1, "address": "10.0.0.3", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "protocol_port": 80, "id": "5e32f960-63ae-4a93-bfa2-339aa83d82ce", "pool_id": "6b73b9f8-d807-4553-87df-eb34cdd08070"}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "65067e3f-830d-4fbb-87e2-f0e51fda83d2"} NOTIFICATION_FIREWALL_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "firewall.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "firewall": { "status": "ACTIVE", "name": "my_firewall", "admin_state_up": True, "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "firewall_policy_id": "c46a1c15-0496-41c9-beff-9a309a25653e", "id": "e2d1155f-6bc4-4292-9cfa-ea91af4b38c8", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "fdffeca1-2b5a-4dc9-b8ae-87c482a83e0d"} NOTIFICATION_FIREWALL_RULE_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "firewall_rule.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "firewall_rule": { "protocol": "tcp", "description": "", "source_port": 80, "source_ip_address": '192.168.255.10', "destination_ip_address": '10.10.10.1', "firewall_policy_id": '', "position": None, "destination_port": 80, "id": "53b7c0d3-cb87-4069-9e29-1e866583cc8c", "name": "rule_01", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "enabled": True, "action": "allow", "ip_version": 4, "shared": False}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "fdffeca1-2b5a-4dc9-b8ae-87c482a83e0d"} NOTIFICATION_FIREWALL_POLICY_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "firewall_policy.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "firewall_policy": {"name": "my_policy", "firewall_rules": [], "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "audited": False, "shared": False, "id": "c46a1c15-0496-41c9-beff-9a309a25653e", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "fdffeca1-2b5a-4dc9-b8ae-87c482a83e0d"} NOTIFICATION_VPNSERVICE_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "vpnservice.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "vpnservice": {"router_id": "75871c53-e722-4b21-93ed-20cb40b6b672", "status": "ACTIVE", "name": "my_vpn", "admin_state_up": True, "subnet_id": "afaf251b-2ec3-42ac-9fa9-82a4195724fa", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "id": "270c40cc-28d5-4a7e-83da-cc33088ee5d6", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "65067e3f-830d-4fbb-87e2-f0e51fda83d2"} NOTIFICATION_IPSEC_POLICY_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "ipsecpolicy.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "ipsecpolicy": {"encapsulation_mode": "tunnel", "encryption_algorithm": "aes-128", "pfs": "group5", "lifetime": { "units": "seconds", "value": 3600}, "name": "my_ipsec_polixy", "transform_protocol": "esp", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "id": "998d910d-4506-47c9-a160-47ec51ff53fc", "auth_algorithm": "sha1", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "4c0e6ecb-2e40-4975-aee2-d88045c747bf"} NOTIFICATION_IKE_POLICY_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "ikepolicy.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "ikepolicy": {"encryption_algorithm": "aes-128", "pfs": "group5", "name": "my_ike_policy", "phase1_negotiation_mode": "main", "lifetime": {"units": "seconds", "value": 3600}, "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "ike_version": "v1", "id": "11cef94e-3f6a-4b65-8058-7deb1838633a", "auth_algorithm": "sha1", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "4c0e6ecb-2e40-4975-aee2-d88045c747bf"} NOTIFICATION_IPSEC_SITE_CONN_CREATE = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "ipsec_site_connection.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "ipsec_site_connection": { "status": "ACTIVE", "psk": "test", "initiator": "bi-directional", "name": "my_ipsec_connection", "admin_state_up": True, "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "ipsecpolicy_id": "998d910d-4506-47c9-a160-47ec51ff53fc", "auth_mode": "psk", "peer_cidrs": ["192.168.255.0/24"], "mtu": 1500, "ikepolicy_id": "11cef94e-3f6a-4b65-8058-7deb1838633a", "dpd": {"action": "hold", "interval": 30, "timeout": 120}, "route_mode": "static", "vpnservice_id": "270c40cc-28d5-4a7e-83da-cc33088ee5d6", "peer_address": "10.0.0.1", "peer_id": "10.0.0.254", "id": "06f3c1ec-2e01-4ad6-9c98-4252751fc60a", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "4c0e6ecb-2e40-4975-aee2-d88045c747bf"} NOTIFICATION_POOL_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-10715057-7590-4529-8020-b994295ee6f4", "event_type": "pool.update.end", "timestamp": "2014-09-15 17:20:50.687649", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "ce255443233748ce9cc71b480974df28", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "pool": { "status": "ACTIVE", "lb_method": "ROUND_ROBIN", "protocol": "HTTP", "description": "", "health_monitors": [], "members": [], "status_description": None, "id": "6d726518-f3aa-4dd4-ac34-e156a35c0aff", "vip_id": None, "name": "my_pool", "admin_state_up": True, "subnet_id": "afaf251b-2ec3-42ac-9fa9-82a4195724fa", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "health_monitors_status": [], "provider": "haproxy"}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:20:49.600299", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "0a5ed7a6-e516-4aed-9968-4ee9f1b65cc2"} NOTIFICATION_VIP_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "vip.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "vip": { "status": "ACTIVE", "protocol": "HTTP", "description": "", "address": "10.0.0.2", "protocol_port": 80, "port_id": "2b5dd476-11da-4d46-9f1e-7a75436062f6", "id": "87a5ce35-f278-47f3-8990-7f695f52f9bf", "status_description": None, "name": "my_vip", "admin_state_up": True, "subnet_id": "afaf251b-2ec3-42ac-9fa9-82a4195724fa", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "connection_limit": -1, "pool_id": "6d726518-f3aa-4dd4-ac34-e156a35c0aff", "session_persistence": {"type": "SOURCE_IP"}}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "3895ad11-98a3-4031-92af-f76e96736661"} NOTIFICATION_HEALTH_MONITORS_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "health_monitor.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "health_monitor": { "admin_state_up": True, "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "delay": 10, "max_retries": 10, "timeout": 10, "pools": [], "type": "PING", "id": "6dea2d01-c3af-4696-9192-6c938f391f01"}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "65067e3f-830d-4fbb-87e2-f0e51fda83d2"} NOTIFICATION_MEMBERS_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "member.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "member": {"admin_state_up": True, "status": "ACTIVE", "status_description": None, "weight": 1, "address": "10.0.0.3", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "protocol_port": 80, "id": "5e32f960-63ae-4a93-bfa2-339aa83d82ce", "pool_id": "6b73b9f8-d807-4553-87df-eb34cdd08070"}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "65067e3f-830d-4fbb-87e2-f0e51fda83d2"} NOTIFICATION_FIREWALL_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "firewall.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "firewall": { "status": "ACTIVE", "name": "my_firewall", "admin_state_up": True, "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "firewall_policy_id": "c46a1c15-0496-41c9-beff-9a309a25653e", "id": "e2d1155f-6bc4-4292-9cfa-ea91af4b38c8", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "fdffeca1-2b5a-4dc9-b8ae-87c482a83e0d"} NOTIFICATION_FIREWALL_RULE_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "firewall_rule.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "firewall_rule": { "protocol": "tcp", "description": "", "source_port": 80, "source_ip_address": '192.168.255.10', "destination_ip_address": '10.10.10.1', "firewall_policy_id": '', "position": None, "destination_port": 80, "id": "53b7c0d3-cb87-4069-9e29-1e866583cc8c", "name": "rule_01", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "enabled": True, "action": "allow", "ip_version": 4, "shared": False}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "fdffeca1-2b5a-4dc9-b8ae-87c482a83e0d"} NOTIFICATION_FIREWALL_POLICY_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "firewall_policy.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "firewall_policy": {"name": "my_policy", "firewall_rules": [], "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "audited": False, "shared": False, "id": "c46a1c15-0496-41c9-beff-9a309a25653e", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "fdffeca1-2b5a-4dc9-b8ae-87c482a83e0d"} NOTIFICATION_VPNSERVICE_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "vpnservice.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "vpnservice": {"router_id": "75871c53-e722-4b21-93ed-20cb40b6b672", "status": "ACTIVE", "name": "my_vpn", "admin_state_up": True, "subnet_id": "afaf251b-2ec3-42ac-9fa9-82a4195724fa", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "id": "270c40cc-28d5-4a7e-83da-cc33088ee5d6", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "65067e3f-830d-4fbb-87e2-f0e51fda83d2"} NOTIFICATION_IPSEC_POLICY_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "ipsecpolicy.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "ipsecpolicy": {"encapsulation_mode": "tunnel", "encryption_algorithm": "aes-128", "pfs": "group5", "lifetime": { "units": "seconds", "value": 3600}, "name": "my_ipsec_polixy", "transform_protocol": "esp", "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "id": "998d910d-4506-47c9-a160-47ec51ff53fc", "auth_algorithm": "sha1", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "4c0e6ecb-2e40-4975-aee2-d88045c747bf"} NOTIFICATION_IKE_POLICY_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "ikepolicy.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "ikepolicy": {"encryption_algorithm": "aes-128", "pfs": "group5", "name": "my_ike_policy", "phase1_negotiation_mode": "main", "lifetime": {"units": "seconds", "value": 3600}, "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "ike_version": "v1", "id": "11cef94e-3f6a-4b65-8058-7deb1838633a", "auth_algorithm": "sha1", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "4c0e6ecb-2e40-4975-aee2-d88045c747bf"} NOTIFICATION_IPSEC_SITE_CONN_UPDATE = { "_context_roles": ["admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "ipsec_site_connection.update.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "ipsec_site_connection": { "status": "ACTIVE", "psk": "test", "initiator": "bi-directional", "name": "my_ipsec_connection", "admin_state_up": True, "tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "ipsecpolicy_id": "998d910d-4506-47c9-a160-47ec51ff53fc", "auth_mode": "psk", "peer_cidrs": ["192.168.255.0/24"], "mtu": 1500, "ikepolicy_id": "11cef94e-3f6a-4b65-8058-7deb1838633a", "dpd": {"action": "hold", "interval": 30, "timeout": 120}, "route_mode": "static", "vpnservice_id": "270c40cc-28d5-4a7e-83da-cc33088ee5d6", "peer_address": "10.0.0.1", "peer_id": "10.0.0.254", "id": "06f3c1ec-2e01-4ad6-9c98-4252751fc60a", "description": ""}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "4c0e6ecb-2e40-4975-aee2-d88045c747bf"} NOTIFICATION_EMPTY_PAYLOAD = { "_context_roles": ["heat_stack_owner", "admin"], "_context_request_id": "req-e56a8a5e-5d42-43e8-9677-2d36e6e17d5e", "event_type": "health_monitor.create.end", "timestamp": "2014-09-15 17:22:11.323644", "_context_tenant_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_user": "1c1f7c80efc24a16b835ae1c0802d0a1", "_unique_id": "f112a185e1d1424eba3a13df9e0f0277", "_context_tenant_name": "demo", "_context_user_id": "1c1f7c80efc24a16b835ae1c0802d0a1", "payload": { "health_monitor": {}}, "_context_project_name": "demo", "_context_read_deleted": "no", "_context_auth_token": "e6daf56d7d1787e1fbefff0ecf29703f", "_context_tenant": "a820f2d6293b4a7587d1c582767f43fb", "priority": "INFO", "_context_is_admin": True, "_context_project_id": "a820f2d6293b4a7587d1c582767f43fb", "_context_timestamp": "2014-09-15 17:22:11.187163", "_context_user_name": "admin", "publisher_id": "network.ubuntu", "message_id": "65067e3f-830d-4fbb-87e2-f0e51fda83d2"} class TestNotifications(test.BaseTestCase): def test_network_create(self): v = notifications.Network(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_NETWORK_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.create", samples[1].name) def test_bulk_network_create(self): v = notifications.Network(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_BULK_NETWORK_CREATE)) self.assertEqual(4, len(samples)) self.assertEqual("network", samples[0].name) self.assertEqual("network.create", samples[1].name) self.assertEqual("network", samples[2].name) self.assertEqual("network.create", samples[3].name) def test_subnet_create(self): v = notifications.Subnet(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_SUBNET_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("subnet.create", samples[1].name) def test_bulk_subnet_create(self): v = notifications.Subnet(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_BULK_SUBNET_CREATE)) self.assertEqual(4, len(samples)) self.assertEqual("subnet", samples[0].name) self.assertEqual("subnet.create", samples[1].name) self.assertEqual("subnet", samples[2].name) self.assertEqual("subnet.create", samples[3].name) def test_port_create(self): v = notifications.Port(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_PORT_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("port.create", samples[1].name) def test_bulk_port_create(self): v = notifications.Port(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_BULK_PORT_CREATE)) self.assertEqual(4, len(samples)) self.assertEqual("port", samples[0].name) self.assertEqual("port.create", samples[1].name) self.assertEqual("port", samples[2].name) self.assertEqual("port.create", samples[3].name) def test_port_update(self): v = notifications.Port(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_PORT_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("port.update", samples[1].name) def test_network_exists(self): v = notifications.Network(mock.Mock()) samples = v.process_notification(NOTIFICATION_NETWORK_EXISTS) self.assertEqual(1, len(list(samples))) def test_router_exists(self): v = notifications.Router(mock.Mock()) samples = v.process_notification(NOTIFICATION_ROUTER_EXISTS) self.assertEqual(1, len(list(samples))) def test_floatingip_exists(self): v = notifications.FloatingIP(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_FLOATINGIP_EXISTS)) self.assertEqual(1, len(samples)) self.assertEqual("ip.floating", samples[0].name) def test_floatingip_update(self): v = notifications.FloatingIP(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_FLOATINGIP_UPDATE_START)) self.assertEqual(len(samples), 2) self.assertEqual("ip.floating", samples[0].name) def test_metering_report(self): v = notifications.Bandwidth(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_L3_METER)) self.assertEqual(1, len(samples)) self.assertEqual("bandwidth", samples[0].name) def test_pool_create(self): v = notifications.Pool(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_POOL_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.lb.pool", samples[0].name) def test_vip_create(self): v = notifications.Vip(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_VIP_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.lb.vip", samples[0].name) def test_member_create(self): v = notifications.Member(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_MEMBERS_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.lb.member", samples[0].name) def test_health_monitor_create(self): v = notifications.HealthMonitor(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_HEALTH_MONITORS_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.lb.health_monitor", samples[0].name) def test_firewall_create(self): v = notifications.Firewall(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_FIREWALL_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.firewall", samples[0].name) def test_vpnservice_create(self): v = notifications.VPNService(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_VPNSERVICE_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.vpn", samples[0].name) def test_ipsec_connection_create(self): v = notifications.IPSecSiteConnection(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_IPSEC_SITE_CONN_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.vpn.connections", samples[0].name) def test_firewall_policy_create(self): v = notifications.FirewallPolicy(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_FIREWALL_POLICY_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.firewall.policy", samples[0].name) def test_firewall_rule_create(self): v = notifications.FirewallRule(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_FIREWALL_RULE_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.firewall.rule", samples[0].name) def test_ipsec_policy_create(self): v = notifications.IPSecPolicy(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_IPSEC_POLICY_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.vpn.ipsecpolicy", samples[0].name) def test_ike_policy_create(self): v = notifications.IKEPolicy(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_IKE_POLICY_CREATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.vpn.ikepolicy", samples[0].name) def test_pool_update(self): v = notifications.Pool(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_POOL_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.lb.pool", samples[0].name) def test_vip_update(self): v = notifications.Vip(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_VIP_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.lb.vip", samples[0].name) def test_member_update(self): v = notifications.Member(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_MEMBERS_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.lb.member", samples[0].name) def test_health_monitor_update(self): v = notifications.HealthMonitor(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_HEALTH_MONITORS_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.lb.health_monitor", samples[0].name) def test_firewall_update(self): v = notifications.Firewall(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_FIREWALL_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.firewall", samples[0].name) def test_vpnservice_update(self): v = notifications.VPNService(mock.Mock()) samples = list(v.process_notification(NOTIFICATION_VPNSERVICE_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.vpn", samples[0].name) def test_ipsec_connection_update(self): v = notifications.IPSecSiteConnection(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_IPSEC_SITE_CONN_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.vpn.connections", samples[0].name) def test_firewall_policy_update(self): v = notifications.FirewallPolicy(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_FIREWALL_POLICY_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.firewall.policy", samples[0].name) def test_firewall_rule_update(self): v = notifications.FirewallRule(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_FIREWALL_RULE_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.firewall.rule", samples[0].name) def test_ipsec_policy_update(self): v = notifications.IPSecPolicy(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_IPSEC_POLICY_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.vpn.ipsecpolicy", samples[0].name) def test_ike_policy_update(self): v = notifications.IKEPolicy(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_IKE_POLICY_UPDATE)) self.assertEqual(2, len(samples)) self.assertEqual("network.services.vpn.ikepolicy", samples[0].name) def test_empty_event_payload(self): v = notifications.HealthMonitor(mock.Mock()) samples = list(v.process_notification( NOTIFICATION_EMPTY_PAYLOAD)) self.assertEqual(0, len(samples)) class TestEventTypes(test.BaseTestCase): def test_network(self): v = notifications.Network(mock.Mock()) events = v.event_types self.assertIsNotEmpty(events) def test_subnet(self): v = notifications.Subnet(mock.Mock()) events = v.event_types self.assertIsNotEmpty(events) def test_port(self): v = notifications.Port(mock.Mock()) events = v.event_types self.assertIsNotEmpty(events) def test_router(self): self.assertTrue(notifications.Router(mock.Mock()).event_types) def test_floatingip(self): self.assertTrue(notifications.FloatingIP(mock.Mock()).event_types) def test_bandwidth(self): self.assertTrue(notifications.Bandwidth(mock.Mock()).event_types) def test_pool(self): self.assertTrue(notifications.Pool(mock.Mock()).event_types) def test_vip(self): self.assertTrue(notifications.Vip(mock.Mock()).event_types) def test_member(self): self.assertTrue(notifications.Member(mock.Mock()).event_types) def test_health_monitor(self): self.assertTrue(notifications.HealthMonitor(mock.Mock()).event_types) def test_firewall(self): self.assertTrue(notifications.Firewall(mock.Mock()).event_types) def test_vpnservice(self): self.assertTrue(notifications.VPNService(mock.Mock()).event_types) def test_ipsec_connection(self): self.assertTrue(notifications.IPSecSiteConnection( mock.Mock()).event_types) def test_firewall_policy(self): self.assertTrue(notifications.FirewallPolicy(mock.Mock()).event_types) def test_firewall_rule(self): self.assertTrue(notifications.FirewallRule(mock.Mock()).event_types) def test_ipsec_policy(self): self.assertTrue(notifications.IPSecPolicy(mock.Mock()).event_types) def test_ike_policy(self): self.assertTrue(notifications.IKEPolicy(mock.Mock()).event_types)
43.15852
79
0.632411
cf243ca279e7e3c030132451950c5ecae0407d67
1,332
py
Python
api/todo.py
lambda-lambda/todo_list
d8334929ec1407c771aa473e4ee056c5cff6a646
[ "MIT" ]
null
null
null
api/todo.py
lambda-lambda/todo_list
d8334929ec1407c771aa473e4ee056c5cff6a646
[ "MIT" ]
null
null
null
api/todo.py
lambda-lambda/todo_list
d8334929ec1407c771aa473e4ee056c5cff6a646
[ "MIT" ]
null
null
null
from models.todo import Todo from models.session import current_user from response import Response from auth import ( login_required, same_user_required, ) def add(request): user = current_user(request) form = request.data form['user_id'] = user.id todo = Todo.new(**form) response = Response.new_json_response(todo.to_dict()) return response def delete(request): query = request.query id = int(query['id']) todo = Todo.delete(id) response = Response.new_json_response(todo.to_dict()) return response def update(request): form = request.data id = form['id'] content = form['content'] todo = Todo.update(id, content=content) response = Response.new_json_response(todo.to_dict()) return response def all(request): query = request.query user = current_user(request) query['user_id'] = user.id todos = Todo.all(**query) todos = [todo.to_dict() for todo in todos] response = Response.new_json_response(todos) return response def init_routes(): d = { '/api/todo/add': login_required(add), '/api/todo/delete': login_required(same_user_required(delete, Todo)), '/api/todo/update': login_required(same_user_required(update, Todo)), '/api/todo/all': login_required(all), } return d
23.785714
77
0.66967
2ec964d73b93f510eabc2de668684feb6dd470c3
4,529
py
Python
yocto/poky/bitbake/lib/bb/checksum.py
libreswitch/libreswitch
1bb99e4bbc55aff46048453e28a1466b08d338aa
[ "Apache-2.0" ]
16
2017-01-17T15:20:43.000Z
2021-03-19T05:45:14.000Z
yocto/poky/bitbake/lib/bb/checksum.py
libreswitch/libreswitch
1bb99e4bbc55aff46048453e28a1466b08d338aa
[ "Apache-2.0" ]
415
2016-12-20T17:20:45.000Z
2018-09-23T07:59:23.000Z
yocto/poky/bitbake/lib/bb/checksum.py
libreswitch/libreswitch
1bb99e4bbc55aff46048453e28a1466b08d338aa
[ "Apache-2.0" ]
10
2016-12-20T13:24:50.000Z
2021-03-19T05:46:43.000Z
# Local file checksum cache implementation # # Copyright (C) 2012 Intel Corporation # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import glob import operator import os import stat import bb.utils import logging from bb.cache import MultiProcessCache logger = logging.getLogger("BitBake.Cache") try: import cPickle as pickle except ImportError: import pickle logger.info("Importing cPickle failed. " "Falling back to a very slow implementation.") # mtime cache (non-persistent) # based upon the assumption that files do not change during bitbake run class FileMtimeCache(object): cache = {} def cached_mtime(self, f): if f not in self.cache: self.cache[f] = os.stat(f)[stat.ST_MTIME] return self.cache[f] def cached_mtime_noerror(self, f): if f not in self.cache: try: self.cache[f] = os.stat(f)[stat.ST_MTIME] except OSError: return 0 return self.cache[f] def update_mtime(self, f): self.cache[f] = os.stat(f)[stat.ST_MTIME] return self.cache[f] def clear(self): self.cache.clear() # Checksum + mtime cache (persistent) class FileChecksumCache(MultiProcessCache): cache_file_name = "local_file_checksum_cache.dat" CACHE_VERSION = 1 def __init__(self): self.mtime_cache = FileMtimeCache() MultiProcessCache.__init__(self) def get_checksum(self, f): entry = self.cachedata[0].get(f) cmtime = self.mtime_cache.cached_mtime(f) if entry: (mtime, hashval) = entry if cmtime == mtime: return hashval else: bb.debug(2, "file %s changed mtime, recompute checksum" % f) hashval = bb.utils.md5_file(f) self.cachedata_extras[0][f] = (cmtime, hashval) return hashval def merge_data(self, source, dest): for h in source[0]: if h in dest: (smtime, _) = source[0][h] (dmtime, _) = dest[0][h] if smtime > dmtime: dest[0][h] = source[0][h] else: dest[0][h] = source[0][h] def get_checksums(self, filelist, pn): """Get checksums for a list of files""" def checksum_file(f): try: checksum = self.get_checksum(f) except OSError as e: bb.warn("Unable to get checksum for %s SRC_URI entry %s: %s" % (pn, os.path.basename(f), e)) return None return checksum def checksum_dir(pth): # Handle directories recursively dirchecksums = [] for root, dirs, files in os.walk(pth): for name in files: fullpth = os.path.join(root, name) checksum = checksum_file(fullpth) if checksum: dirchecksums.append((fullpth, checksum)) return dirchecksums checksums = [] for pth in filelist.split(): exist = pth.split(":")[1] if exist == "False": continue pth = pth.split(":")[0] if '*' in pth: # Handle globs for f in glob.glob(pth): if os.path.isdir(f): if not os.path.islink(f): checksums.extend(checksum_dir(f)) else: checksum = checksum_file(f) checksums.append((f, checksum)) elif os.path.isdir(pth): if not os.path.islink(pth): checksums.extend(checksum_dir(pth)) else: checksum = checksum_file(pth) checksums.append((pth, checksum)) checksums.sort(key=operator.itemgetter(1)) return checksums
32.35
108
0.57187
cc60806515b3fecb406ebc1589f23a5bd303acb5
3,288
py
Python
yarn/datadog_checks/yarn/config_models/instance.py
codylerum/integrations-core
aee18148cebf5026099abde7bc218d3ba8d2e75c
[ "BSD-3-Clause" ]
null
null
null
yarn/datadog_checks/yarn/config_models/instance.py
codylerum/integrations-core
aee18148cebf5026099abde7bc218d3ba8d2e75c
[ "BSD-3-Clause" ]
null
null
null
yarn/datadog_checks/yarn/config_models/instance.py
codylerum/integrations-core
aee18148cebf5026099abde7bc218d3ba8d2e75c
[ "BSD-3-Clause" ]
null
null
null
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from __future__ import annotations from typing import Any, Mapping, Optional, Sequence from pydantic import BaseModel, root_validator, validator from datadog_checks.base.utils.functions import identity from datadog_checks.base.utils.models import validation from . import defaults, validators class AuthToken(BaseModel): class Config: allow_mutation = False reader: Optional[Mapping[str, Any]] writer: Optional[Mapping[str, Any]] class Proxy(BaseModel): class Config: allow_mutation = False http: Optional[str] https: Optional[str] no_proxy: Optional[Sequence[str]] class InstanceConfig(BaseModel): class Config: allow_mutation = False allow_redirects: Optional[bool] application_status_mapping: Optional[Mapping[str, Any]] application_tags: Optional[Mapping[str, Any]] auth_token: Optional[AuthToken] auth_type: Optional[str] aws_host: Optional[str] aws_region: Optional[str] aws_service: Optional[str] cluster_name: Optional[str] collect_app_metrics: Optional[bool] collect_node_metrics: Optional[bool] connect_timeout: Optional[float] disable_generic_tags: Optional[bool] disable_legacy_cluster_tag: Optional[bool] empty_default_hostname: Optional[bool] extra_headers: Optional[Mapping[str, Any]] headers: Optional[Mapping[str, Any]] kerberos_auth: Optional[str] kerberos_cache: Optional[str] kerberos_delegate: Optional[bool] kerberos_force_initiate: Optional[bool] kerberos_hostname: Optional[str] kerberos_keytab: Optional[str] kerberos_principal: Optional[str] log_requests: Optional[bool] min_collection_interval: Optional[float] ntlm_domain: Optional[str] password: Optional[str] persist_connections: Optional[bool] proxy: Optional[Proxy] queue_blacklist: Optional[Sequence[str]] read_timeout: Optional[float] resourcemanager_uri: Optional[str] service: Optional[str] skip_proxy: Optional[bool] split_yarn_application_tags: Optional[bool] tags: Optional[Sequence[str]] timeout: Optional[float] tls_ca_cert: Optional[str] tls_cert: Optional[str] tls_ignore_warning: Optional[bool] tls_private_key: Optional[str] tls_use_host_header: Optional[bool] tls_verify: Optional[bool] use_legacy_auth_encoding: Optional[bool] username: Optional[str] @root_validator(pre=True) def _initial_validation(cls, values): return validation.core.initialize_config(getattr(validators, 'initialize_instance', identity)(values)) @validator('*', pre=True, always=True) def _ensure_defaults(cls, v, field): if v is not None or field.required: return v return getattr(defaults, f'instance_{field.name}')(field, v) @validator('*') def _run_validations(cls, v, field): if not v: return v return getattr(validators, f'instance_{field.name}', identity)(v, field=field) @root_validator(pre=False) def _final_validation(cls, values): return validation.core.finalize_config(getattr(validators, 'finalize_instance', identity)(values))
31.314286
110
0.725973
f2aef2cc62dc9fb283d78d436c9f7054552da463
18,843
py
Python
demo_project/demo/utils.py
idearun/django-graphos
a096fb76a9759d958fdf6fbb88becab50a7c80f1
[ "BSD-2-Clause" ]
257
2015-01-01T13:59:06.000Z
2022-03-19T12:44:32.000Z
demo_project/demo/utils.py
idearun/django-graphos
a096fb76a9759d958fdf6fbb88becab50a7c80f1
[ "BSD-2-Clause" ]
64
2015-01-13T10:11:24.000Z
2022-01-08T15:26:26.000Z
demo_project/demo/utils.py
idearun/django-graphos
a096fb76a9759d958fdf6fbb88becab50a7c80f1
[ "BSD-2-Clause" ]
98
2015-01-13T17:38:05.000Z
2022-01-20T11:07:18.000Z
from .models import Account DB_HOST = ["localhost"] DB_PORT = 27017 def get_db(db_name): import pymongo DB_HOST = ["localhost"] DB_PORT = 27017 db = pymongo.Connection(DB_HOST, DB_PORT)[db_name] return db def get_mongo_cursor(db_name, collection_name, max_docs=100): import pymongo db = pymongo.Connection(host=DB_HOST, port=DB_PORT)[db_name] collection = db[collection_name] cursor = collection.find() count = cursor.count if callable(count): count = count() if count >= max_docs: cursor = cursor[0:max_docs] return cursor data = [ ['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit'], ['2004', 1000, 400, 100, 600], ['2005', 1170, 460, 120, 710], ['2006', 660, 1120, 50, -460], ['2007', 1030, 540, 100, 490], ] candlestick_data = [['Mon', 20, 28, 38, 45], ['Tue', 31, 38, 55, 66], ['Wed', 50, 55, 77, 80], ['Thu', 77, 77, 66, 50], ['Fri', 68, 66, 22, 15]] # TODO: Come up with a better example scatter_multi_series_data = [ ['state','country','Rainfall', 'Precipitation'], ['Uttar Pradesh','India',1, 2], ['Bihar','India',2, 3], ['Telangana','India',5, 7], ['Lahore','Pakistan',9,8], ['Hyderabad','Pakistan',8,7], ['Lahore','Pakistan',3,11] ] # TODO: Come up with a better example scatter_single_series_data = [ ['Leader', 'Rainfall', 'Precipitation'], ['Trump', 1, 2], ['Clinton', 2, 3], ['Trumps', 5, 7], ['George', 6, 9], ['Alex', 7, 4], ['Donald', 7, 8], ] treemap_data = [ ['Location', 'Parent', 'Market trade volume (size)', 'Market increase/decrease (color)'], ['Global', None, 0, 0], ['America', 'Global', 0, 0], ['Europe', 'Global', 0, 0], ['Asia', 'Global', 0, 0], ['Australia', 'Global', 0, 0], ['Africa', 'Global', 0, 0], ['Brazil', 'America', 11, 10], ['USA', 'America', 52, 31], ['Mexico', 'America', 24, 12], ['Canada', 'America', 16, -23], ['France', 'Europe', 42, -11], ['Germany', 'Europe', 31, -2], ['Sweden', 'Europe', 22, -13], ['Italy', 'Europe', 17, 4], ['UK', 'Europe', 21, -5], ['China', 'Asia', 36, 4], ['Japan', 'Asia', 20, -12], ['India', 'Asia', 40, 63], ['Laos', 'Asia', 4, 34], ['Mongolia', 'Asia', 1, -5], ['Israel', 'Asia', 12, 24], ['Iran', 'Asia', 18, 13], ['Pakistan', 'Asia', 11, -52], ['Egypt', 'Africa', 21, 0], ['S. Africa', 'Africa', 30, 43], ['Sudan', 'Africa', 12, 2], ['Congo', 'Africa', 10, 12], ['Zaire', 'Africa', 8, 10]] # map_data = [ # ['Country', 'Value'], # ['fo', 0], # ['um', 1], # ['us', 2], # ['jp', 3], # ['sc', 4], # ['in', 5], # ['fr', 6], # ['fm', 7], # ['cn', 8], # ['pt', 9], # ['sw', 10], # ['sh', 11], # ['br', 12], # ['ki', 13], # ['ph', 14], # ['mx', 15], # ['es', 16], # ['bu', 17], # ['mv', 18], # ['sp', 19], # ['gb', 20], # ['gr', 21], # ['as', 22], # ['dk', 23], # ['gl', 24], # ['gu', 25], # ['mp', 26], # ['pr', 27], # ['vi', 28], # ['ca', 29], # ['st', 30], # ['cv', 31], # ['dm', 32], # ['nl', 33], # ['jm', 34], # ['ws', 35], # ['om', 36], # ['vc', 37], # ['tr', 38], # ['bd', 39], # ['lc', 40], # ['nr', 41], # ['no', 42], # ['kn', 43], # ['bh', 44], # ['to', 45], # ['fi', 46], # ['id', 47], # ['mu', 48], # ['se', 49], # ['tt', 50], # ['my', 51], # ['pa', 52], # ['pw', 53], # ['tv', 54], # ['mh', 55], # ['cl', 56], # ['th', 57], # ['gd', 58], # ['ee', 59], # ['ad', 60], # ['tw', 61], # ['bb', 62], # ['it', 63], # ['mt', 64], # ['vu', 65], # ['sg', 66], # ['cy', 67], # ['lk', 68], # ['km', 69], # ['fj', 70], # ['ru', 71], # ['va', 72], # ['sm', 73], # ['kz', 74], # ['az', 75], # ['tj', 76], # ['ls', 77], # ['uz', 78], # ['ma', 79], # ['co', 80], # ['tl', 81], # ['tz', 82], # ['ar', 83], # ['sa', 84], # ['pk', 85], # ['ye', 86], # ['ae', 87], # ['ke', 88], # ['pe', 89], # ['do', 90], # ['ht', 91], # ['pg', 92], # ['ao', 93], # ['kh', 94], # ['vn', 95], # ['mz', 96], # ['cr', 97], # ['bj', 98], # ['ng', 99], # ['ir', 100], # ['sv', 101], # ['sl', 102], # ['gw', 103], # ['hr', 104], # ['bz', 105], # ['za', 106], # ['cf', 107], # ['sd', 108], # ['cd', 109], # ['kw', 110], # ['de', 111], # ['be', 112], # ['ie', 113], # ['kp', 114], # ['kr', 115], # ['gy', 116], # ['hn', 117], # ['mm', 118], # ['ga', 119], # ['gq', 120], # ['ni', 121], # ['lv', 122], # ['ug', 123], # ['mw', 124], # ['am', 125], # ['sx', 126], # ['tm', 127], # ['zm', 128], # ['nc', 129], # ['mr', 130], # ['dz', 131], # ['lt', 132], # ['et', 133], # ['er', 134], # ['gh', 135], # ['si', 136], # ['gt', 137], # ['ba', 138], # ['jo', 139], # ['sy', 140], # ['mc', 141], # ['al', 142], # ['uy', 143], # ['cnm', 144], # ['mn', 145], # ['rw', 146], # ['so', 147], # ['bo', 148], # ['cm', 149], # ['cg', 150], # ['eh', 151], # ['rs', 152], # ['me', 153], # ['tg', 154], # ['la', 155], # ['af', 156], # ['ua', 157], # ['sk', 158], # ['jk', 159], # ['bg', 160], # ['qa', 161], # ['li', 162], # ['at', 163], # ['sz', 164], # ['hu', 165], # ['ro', 166], # ['ne', 167], # ['lu', 168], # ['ad', 169], # ['ci', 170], # ['lr', 171], # ['bn', 172], # ['iq', 173], # ['ge', 174], # ['gm', 175], # ['ch', 176], # ['td', 177], # ['kv', 178], # ['lb', 179], # ['dj', 180], # ['bi', 181], # ['sr', 182], # ['il', 183], # ['ml', 184], # ['sn', 185], # ['gn', 186], # ['zw', 187], # ['pl', 188], # ['mk', 189], # ['py', 190], # ['by', 191], # ['ca', 192], # ['bf', 193], # ['na', 194], # ['ly', 195], # ['tn', 196], # ['bt', 197], # ['md', 198], # ['ss', 199], # ['bw', 200], # ['bs', 201], # ['nz', 202], # ['cu', 203], # ['ec', 204], # ['au', 205], # ['ve', 206], # ['sb', 207], # ['mg', 208], # ['is', 209], # ['eg', 210], # ['kg', 211], # ['np', 212] # ] map_data = [ ['Country', 'Value'], ['fo', 0], ['um', 1], ['us', 2], ['jp', 3], ['sc', 4], ['in', 5], ['fr', 6], ['fm', 7], ['cn', 8], ['pt', 9], ['sw', 10], ['sh', 11], ['br', 12], ['ki', 13], ['ph', 14], ['mx', 15], ['es', 16], ['bu', 17], ['mv', 18], ['sp', 19], ['gb', 20], ['gr', 21], ['as', 22], ['dk', 23], ['gl', 24], ['gu', 25], ['mp', 26], ['pr', 27], ['vi', 28], ['ca', 29], ['st', 30], ['cv', 31], ['dm', 32], ['nl', 33], ['jm', 34], ['ws', 35], ['om', 36], ['vc', 37], ['tr', 38], ['bd', 39], ['lc', 40], ['nr', 41], ['no', 42], ['kn', 43], ['bh', 44], ['to', 45], ['fi', 46], ['id', 47], ['mu', 48], ['se', 49], ['tt', 50], ['my', 51], ['pa', 52], ['pw', 53], ['tv', 54], ['mh', 55], ['cl', 56], ['th', 57], ['gd', 58], ['ee', 59], ['ad', 60], ['tw', 61], ['bb', 62], ['it', 63], ['mt', 64], ['vu', 65], ['sg', 66], ['cy', 67], ['lk', 68], ['km', 69], ['fj', 70], ['ru', 71], ['va', 72], ['sm', 73], ['kz', 74], ['az', 75], ['tj', 76], ['ls', 77], ['uz', 78], ['ma', 79], ['co', 80], ['tl', 81], ['tz', 82], ['ar', 83], ['sa', 84], ['pk', 85], ['ye', 86], ['ae', 87], ['ke', 88], ['pe', 89], ['do', 90], ['ht', 91], ['pg', 92], ['ao', 93], ['kh', 94], ['vn', 95], ['mz', 96], ['cr', 97], ['bj', 98], ['ng', 99] ] map_data_us_multi_series_lat_lon = [ ['Latitude', 'Longitude', 'Winner', 'Seats'], [32.380120, -86.300629, 'Trump', 10], [58.299740, -134.406794, 'Trump', 10], [33.448260, -112.075774, 'Trump', 10], [34.748655, -92.274494, 'Clinton', 20], [38.579065, -121.491014, 'Clinton', 20], ] map_data_us_multi_series = [ ['State', 'Winner', 'Seats'], ['us-nj', 'Trump', 10], ['us-ri', 'Trump', 10], ['us-ma', 'Trump', 10], ['us-ct', 'Clinton', 20], ['us-md', 'Clinton', 20], ['us-ny', 'Clinton', 20], ['us-de', 'Trump', 20], ['us-fl', 'Trump', 20], ['us-oh', 'Trump', 20], ['us-pa', 'Trump', 20], ['us-li', 'Trump', 20], ['us-ca', 'Trump', 20], ['us-hi', 'Trump', 20], ['us-va', 'Trump', 31], ['us-mi', 'Trump', 31], ['us-in', 'Trump', 31], ['us-nc', 'Trump', 31], ['us-ga', 'Trump', 31], ['us-tn', 'Trump', 31], ['us-nh', 'Trump', 31], ['us-sc', 'Trump', 31], ['us-la', 'Trump', 31], ['us-ky', 'Trump', 31], ['us-wi', 'Trump', 12], ['us-wa', 'Trump', 12], ['us-al', 'Clinton', 12], ['us-mo', 'Clinton', 12], ['us-tx', 'Clinton', 45], ['us-wv', 'Clinton', 45], ] map_data_us_lat_lon = [ ['Latitude', 'Longitude', 'Population'], [32.380120, -86.300629, 900], [58.299740, -134.406794, 387], [33.448260, -112.075774, 313], ] map_data_india_lat_lon = [ ['Latitude', 'Longitude', 'Population'], [25.4851484, 83.2104426, 900], [27.7126407, 78.7391187, 387], [28.2699017, 79.1604971, 313], ] map_data_us = [ ['State', 'Population'], ['us-nj', 438], ['us-ri', 387], ['us-ma', 313], ['us-ct', 271], ['us-md', 209], ['us-ny', 195], ['us-de', 155], ['us-fl', 114], ['us-oh', 107], ['us-pa', 106], ['us-li', 86], ['us-ca', 84], ['us-hi', 73], ['us-va', 69], ['us-mi', 68], ['us-in', 65], ['us-nc', 64], ['us-ga', 55], ['us-tn', 53], ['us-nh', 53], ['us-sc', 51], ['us-la', 40], ['us-ky', 39], ['us-wi', 38], ['us-wa', 34], ['us-al', 34], ['us-mo', 31], ['us-tx', 31], ['us-wv', 29], ['us-vt', 25], ['us-mn', 24], ['us-ms', 23], ['us-ia', 20], ['us-ar', 20], ['us-ok', 19], ['us-az', 17], ['us-co', 16], ['us-me', 16], ['us-or', 14], ['us-ks', 13], ['us-ut', 11], ['us-ne', 9], ['us-nv', 7], ['us-id', 6], ['us-nm', 6], ['us-sd', 4], ['us-nd', 4], ['us-mt', 2], ['us-wy', 2], ['us-ak', 1], ] map_data_us_point = [ ['Lat', 'Lon', 'Name', 'Date'], [46.8797, -110.3626, 'trump', '25th February'], [41.4925, -99.9018, 'trump', '26th February'], [45.4925, -89.9018, 'trump', '27th February'], [32.1656, -82.9001, 'clinton', '25th February'], [33.1656, -81.9001, 'clinton', '26th February'], ] mongo_series_object_1 = [[440, 39], [488, 29.25], [536, 28], [584, 29], [632, 33.25], [728, 28.5], [776, 33.25], [824, 28.5], [872, 31], [920, 30.75], [968, 26.25]] mongo_series_object_2 = [[400, 4], [488, 0], [536, 20], [584, 8], [632, 2], [680, 36], [728, 0], [776, 0], [824, 0], [872, 4], [920, 1], [968, 0]] mongo_data = [{'data': mongo_series_object_1, 'label': 'hours'}, {'data': mongo_series_object_2, 'label': 'hours'}] def create_demo_accounts(): Account.objects.all().delete() # Create some rows Account.objects.create(year="2004", sales=1000, expenses=400, ceo="Welch") Account.objects.create(year="2005", sales=1170, expenses=460, ceo="Jobs") Account.objects.create(year="2006", sales=660, expenses=1120, ceo="Page") Account.objects.create(year="2007", sales=1030, expenses=540, ceo="Welch") Account.objects.create(year="2008", sales=2030, expenses=1540, ceo="Zuck") Account.objects.create(year="2009", sales=2230, expenses=1840, ceo="Cook") def create_demo_mongo(): accounts = get_db("accounts") docs = accounts.docs docs.drop() docs = accounts.docs header = data[0] data_only = data[1:] for row in data_only: docs.insert(dict(zip(header, row))) heatmap_data = [['Name', 'Yash', 'Akshar', 'Ashok','Shabda'], ['Uttar Pradesh',1000,2000,3000,4000], ['Bihar',2000,5000,8000,9800], ['Hyderabad',10000,9855,6000,2000], ['Banglore',98652,78563,8522,2000], ['Chennai',98745,8563,5236,2000], ['Vizag',9875,7000,966,2300], ['Maharashtra',9000,16789,9087,6789], ['Punjab',3467,8900,5670,9900] ] funnel_data = [['Unique users', 'Counts'], ['Website visits', 654], ['Downloads', 4064], ['Requested price list', 1987], ['Invoice sent', 976], ['Finalized', 846] ] treemap_data_highcharts = [["Continent","Country","Cause","Death Rate"], ["Asia","India","Cardiovascular Disease",10], ["Asia","India","Road Accident",5], ["Asia","India","Cancer",3], ["Asia","China","Cardiovascular Disease",9], ["Asia","China","Road Accident",6], ["Asia","China","Cancer",1], ["South Ameria","Brazil","Cardiovascular Disease",11], ["South Ameria","Brazil","Road Accident",3], ["South Ameria","Brazil","Cancer",2], ["South Ameria","Uruguay","Cardiovascular Disease",12], ["South Ameria","Uruguay","Road Accident",9], ["South Ameria","Uruguay","Cancer",8], ["Europe","France","Cardiovascular Disease",9], ["Europe","France","Road Accident",4], ["Europe","France","Cancer",6] ] piechart_data_highcharts = [["Country","Cause","Death Rate"], ["India","Cardiovascular Disease",10], ["India","Road Accident",5], ["India","Cancer",3], ["China","Cardiovascular Disease",9], ["China","Road Accident",6], ["China","Cancer",1], ["Brazil","Cardiovascular Disease",11], ["Brazil","Road Accident",3], ["Brazil","Cancer",2], ["Uruguay","Cardiovascular Disease",12], ["Uruguay","Road Accident",9], ["Uruguay","Cancer",8], ["France","Cardiovascular Disease",9], ["France","Road Accident",4], ["France","Cancer",6] ] bubble_chart_data_multi = [["Grade","Country","Sugar Consumption","Fat Consumption","GDP"], ["A","India",10,15,90], ["B","India",11,20,19], ["C","India",12,15,70], ["D","India",13,30,39], ["E","India",14,12,9], ["F","India",15,5,98], ["H","Japan",18,60,110], ["I","Japan", 41, 16, 140], ["J","Japan", 47, 36, 150], ["K","Japan", 61, 56, 70], ["L","Japan", 74, 36, 210], ["M","Japan", 10, 46, 90], ["N","Japan", 30, 26, 100], ["O","China",14,18,100], ["A","China", 9, 17, 10], ["B","China", 51, 67, 200], ["C","China", 12, 27, 160], ["D","China", 42, 67, 86], ["E","China", 30, 97, 20], ["F","China", 16, 67, 90], ["L","USA",56,20,120], ["K","USA", 32, 23, 220], ["A","USA", 15, 85, 320], ["S","USA", 48, 10, 20], ["D","USA", 30, 96, 150], ["K","USA", 14, 22, 160], ["P","USA", 39, 21, 100], ["O","USA", 44, 29, 150]] bubble_chart_data_single = [["Country","Sugar Consumption","Fat Consumption","GDP"], ["India",10,15,90], ["USA",11,20,19], ["China",12,15,70], ["Japan",13,30,39], ["Pakistan",14,12,9], ["Srilanka",15,5,98], ["Indonesia",16,35,150]]
27.073276
99
0.345433
57b52ba3fc6514eebfb144a68eb62b62ea05a0ef
6,509
py
Python
astoria/managers/astprocd/process_manager.py
srobo/astoria
7bdefd91254b154aadf63b574c8b767d17a2e5d4
[ "MIT" ]
1
2021-02-03T02:54:54.000Z
2021-02-03T02:54:54.000Z
astoria/managers/astprocd/process_manager.py
srobo/astoria
7bdefd91254b154aadf63b574c8b767d17a2e5d4
[ "MIT" ]
72
2020-12-15T18:29:18.000Z
2022-03-08T09:42:53.000Z
astoria/managers/astprocd/process_manager.py
srobo/astoria
7bdefd91254b154aadf63b574c8b767d17a2e5d4
[ "MIT" ]
2
2022-02-05T23:00:51.000Z
2022-03-09T21:40:49.000Z
"""Process Manager Application.""" import asyncio import logging from typing import Dict, Optional from astoria.common.broadcast_event import UsercodeLogBroadcastEvent from astoria.common.manager import StateManager from astoria.common.manager_requests import ( RequestResponse, UsercodeKillManagerRequest, UsercodeRestartManagerRequest, ) from astoria.common.messages.astdiskd import DiskInfo, DiskType, DiskUUID from astoria.common.messages.astprocd import CodeStatus, ProcessManagerMessage from astoria.common.mqtt import BroadcastHelper from astoria.managers.mixins.disk_handler import DiskHandlerMixin from .usercode_lifecycle import UsercodeLifecycle LOGGER = logging.getLogger(__name__) loop = asyncio.get_event_loop() class ProcessManager(DiskHandlerMixin, StateManager[ProcessManagerMessage]): """Astoria Process State Manager.""" name = "astprocd" dependencies = ["astdiskd", "astmetad"] def _init(self) -> None: self._lifecycle: Optional[UsercodeLifecycle] = None self._cur_disks: Dict[DiskUUID, DiskInfo] = {} self._mqtt.subscribe("astdiskd", self.handle_astdiskd_disk_info_message) self._register_request( "restart", UsercodeRestartManagerRequest, self.handle_restart_request, ) self._register_request( "kill", UsercodeKillManagerRequest, self.handle_kill_request, ) self._log_helper = BroadcastHelper.get_helper( self._mqtt, UsercodeLogBroadcastEvent, ) @property def offline_status(self) -> ProcessManagerMessage: """ Status to publish when the manager goes offline. This status should ensure that any other components relying on this data go into a safe state. """ return ProcessManagerMessage( status=ProcessManagerMessage.Status.STOPPED, ) async def main(self) -> None: """Main routine for astprocd.""" # Wait whilst the program is running. self.update_status() await self.wait_loop() for uuid, info in self._cur_disks.items(): asyncio.ensure_future(self.handle_disk_removal(uuid, info)) async def handle_disk_insertion(self, uuid: DiskUUID, disk_info: DiskInfo) -> None: """Handle a disk insertion.""" LOGGER.debug(f"Disk inserted: {uuid} ({disk_info.disk_type})") if disk_info.disk_type is DiskType.USERCODE: LOGGER.info(f"Usercode disk {uuid} is mounted at {disk_info.mount_path}") if self._lifecycle is None: LOGGER.debug(f"Starting usercode lifecycle for {uuid}") self._lifecycle = UsercodeLifecycle( uuid, disk_info, self.update_status, self._log_helper, self.config, ) asyncio.ensure_future(self._lifecycle.run_process()) else: LOGGER.warn("Cannot run usercode, there is already a lifecycle present.") with disk_info.mount_path.joinpath("log.txt").open("w") as fh: fh.write("Unable to start code.\n") fh.write("It is not safe to run multiple code disks at once.\n") async def handle_disk_removal(self, uuid: DiskUUID, disk_info: DiskInfo) -> None: """Handle a disk removal.""" LOGGER.debug(f"Disk removed: {uuid} ({disk_info.disk_type})") if disk_info.disk_type is DiskType.USERCODE: LOGGER.info(f"Usercode disk {uuid} removed ({disk_info.mount_path})") if self._lifecycle is not None and self._lifecycle._uuid == disk_info.uuid: await self._lifecycle.kill_process() self._lifecycle = None self.update_status() else: LOGGER.warning("Disk removed, but no code lifecycle available") async def handle_kill_request( self, request: UsercodeKillManagerRequest, ) -> RequestResponse: """Handle a request to kill running usercode.""" if self._lifecycle is None: return RequestResponse( uuid=request.uuid, success=False, reason="No active usercode lifecycle", ) else: LOGGER.info("Kill request received.") await self._lifecycle.kill_process() return RequestResponse( uuid=request.uuid, success=True, ) async def handle_restart_request( self, request: UsercodeRestartManagerRequest, ) -> RequestResponse: """Handle a request to restart usercode.""" LOGGER.info("Restart request received.") if self._lifecycle is None: return RequestResponse( uuid=request.uuid, success=False, reason="No active usercode lifecycle", ) else: if self._lifecycle.status is CodeStatus.RUNNING: return RequestResponse( uuid=request.uuid, success=False, reason="Code is already running.", ) else: asyncio.ensure_future(self._lifecycle.run_process()) return RequestResponse( uuid=request.uuid, success=True, ) def update_status(self, code_status: Optional[CodeStatus] = None) -> None: """ Calculate and update the status of this manager. Called by the usercode lifecycle to inform us of changes. """ if self._lifecycle is None: # When the status is updated in the lifecycle constructor, we # are left with a situation where there is no lifecycle object, # but the code is starting. Thus we want to inform anyway. # # This section also updates the status when the lifecycle is cleaned up. self.status = ProcessManagerMessage( status=ProcessManagerMessage.Status.RUNNING, code_status=code_status, ) else: self.status = ProcessManagerMessage( status=ProcessManagerMessage.Status.RUNNING, code_status=self._lifecycle.status, disk_info=self._lifecycle.disk_info, )
36.982955
89
0.608696
545be62f44ed6217e3e2a77b3b5c50bb6e7f5b94
2,015
py
Python
migrations/versions/14b840151c2f_character_table.py
jimmybutton/moviedb
61028ac4db7f58a671ab3a1c2afd3bfb53372773
[ "MIT" ]
null
null
null
migrations/versions/14b840151c2f_character_table.py
jimmybutton/moviedb
61028ac4db7f58a671ab3a1c2afd3bfb53372773
[ "MIT" ]
null
null
null
migrations/versions/14b840151c2f_character_table.py
jimmybutton/moviedb
61028ac4db7f58a671ab3a1c2afd3bfb53372773
[ "MIT" ]
null
null
null
"""character table Revision ID: 14b840151c2f Revises: 5f1654c61a38 Create Date: 2020-06-16 18:07:44.967078 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '14b840151c2f' down_revision = '5f1654c61a38' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('character', sa.Column('id', sa.Integer(), nullable=False), sa.Column('created_timestamp', sa.DateTime(), nullable=True), sa.Column('created_id', sa.Integer(), nullable=True), sa.Column('modified_timestamp', sa.DateTime(), nullable=True), sa.Column('modified_id', sa.Integer(), nullable=True), sa.Column('movie_id', sa.Integer(), nullable=True), sa.Column('actor_id', sa.Integer(), nullable=True), sa.Column('character_name', sa.String(length=128), nullable=True), sa.Column('character_url', sa.String(length=128), nullable=True), sa.Column('movie_title', sa.String(length=128), nullable=True), sa.Column('movie_year', sa.Integer(), nullable=True), sa.Column('actor_name', sa.String(length=128), nullable=True), sa.ForeignKeyConstraint(['actor_id'], ['people.id'], ), sa.ForeignKeyConstraint(['created_id'], ['user.id'], ), sa.ForeignKeyConstraint(['modified_id'], ['user.id'], ), sa.ForeignKeyConstraint(['movie_id'], ['movie.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_character_created_timestamp'), 'character', ['created_timestamp'], unique=False) op.create_index(op.f('ix_character_modified_timestamp'), 'character', ['modified_timestamp'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_character_modified_timestamp'), table_name='character') op.drop_index(op.f('ix_character_created_timestamp'), table_name='character') op.drop_table('character') # ### end Alembic commands ###
39.509804
111
0.698759
0dc38fa59b31a2e9fbee37dec7b69be947dacf38
5,957
py
Python
numpy/_pytesttester.py
bdvd/numpy
cea994fac86dbc5af7bee3f15fc5b475a99163fa
[ "BSD-3-Clause" ]
1
2020-12-07T17:25:19.000Z
2020-12-07T17:25:19.000Z
numpy/_pytesttester.py
sahanabalappa/numpy
cea994fac86dbc5af7bee3f15fc5b475a99163fa
[ "BSD-3-Clause" ]
20
2020-02-14T11:37:52.000Z
2020-02-18T21:18:45.000Z
numpy/_pytesttester.py
sahanabalappa/numpy
cea994fac86dbc5af7bee3f15fc5b475a99163fa
[ "BSD-3-Clause" ]
1
2020-03-20T00:22:37.000Z
2020-03-20T00:22:37.000Z
""" Pytest test running. This module implements the ``test()`` function for NumPy modules. The usual boiler plate for doing that is to put the following in the module ``__init__.py`` file:: from numpy._pytesttester import PytestTester test = PytestTester(__name__).test del PytestTester Warnings filtering and other runtime settings should be dealt with in the ``pytest.ini`` file in the numpy repo root. The behavior of the test depends on whether or not that file is found as follows: * ``pytest.ini`` is present (develop mode) All warnings except those explicitly filtered out are raised as error. * ``pytest.ini`` is absent (release mode) DeprecationWarnings and PendingDeprecationWarnings are ignored, other warnings are passed through. In practice, tests run from the numpy repo are run in develop mode. That includes the standard ``python runtests.py`` invocation. This module is imported by every numpy subpackage, so lies at the top level to simplify circular import issues. For the same reason, it contains no numpy imports at module scope, instead importing numpy within function calls. """ import sys import os __all__ = ['PytestTester'] def _show_numpy_info(): import numpy as np print("NumPy version %s" % np.__version__) relaxed_strides = np.ones((10, 1), order="C").flags.f_contiguous print("NumPy relaxed strides checking option:", relaxed_strides) class PytestTester: """ Pytest test runner. A test function is typically added to a package's __init__.py like so:: from numpy._pytesttester import PytestTester test = PytestTester(__name__).test del PytestTester Calling this test function finds and runs all tests associated with the module and all its sub-modules. Attributes ---------- module_name : str Full path to the package to test. Parameters ---------- module_name : module name The name of the module to test. Notes ----- Unlike the previous ``nose``-based implementation, this class is not publicly exposed as it performs some ``numpy``-specific warning suppression. """ def __init__(self, module_name): self.module_name = module_name def __call__(self, label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, durations=-1, tests=None): """ Run tests for module using pytest. Parameters ---------- label : {'fast', 'full'}, optional Identifies the tests to run. When set to 'fast', tests decorated with `pytest.mark.slow` are skipped, when 'full', the slow marker is ignored. verbose : int, optional Verbosity value for test outputs, in the range 1-3. Default is 1. extra_argv : list, optional List with any extra arguments to pass to pytests. doctests : bool, optional .. note:: Not supported coverage : bool, optional If True, report coverage of NumPy code. Default is False. Requires installation of (pip) pytest-cov. durations : int, optional If < 0, do nothing, If 0, report time of all tests, if > 0, report the time of the slowest `timer` tests. Default is -1. tests : test or list of tests Tests to be executed with pytest '--pyargs' Returns ------- result : bool Return True on success, false otherwise. Notes ----- Each NumPy module exposes `test` in its namespace to run all tests for it. For example, to run all tests for numpy.lib: >>> np.lib.test() #doctest: +SKIP Examples -------- >>> result = np.lib.test() #doctest: +SKIP ... 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds >>> result True """ import pytest import warnings module = sys.modules[self.module_name] module_path = os.path.abspath(module.__path__[0]) # setup the pytest arguments pytest_args = ["-l"] # offset verbosity. The "-q" cancels a "-v". pytest_args += ["-q"] # Filter out distutils cpu warnings (could be localized to # distutils tests). ASV has problems with top level import, # so fetch module for suppression here. with warnings.catch_warnings(): warnings.simplefilter("always") from numpy.distutils import cpuinfo # Filter out annoying import messages. Want these in both develop and # release mode. pytest_args += [ "-W ignore:Not importing directory", "-W ignore:numpy.dtype size changed", "-W ignore:numpy.ufunc size changed", "-W ignore::UserWarning:cpuinfo", ] # When testing matrices, ignore their PendingDeprecationWarnings pytest_args += [ "-W ignore:the matrix subclass is not", "-W ignore:Importing from numpy.matlib is", ] if doctests: raise ValueError("Doctests not supported") if extra_argv: pytest_args += list(extra_argv) if verbose > 1: pytest_args += ["-" + "v"*(verbose - 1)] if coverage: pytest_args += ["--cov=" + module_path] if label == "fast": pytest_args += ["-m", "not slow"] elif label != "full": pytest_args += ["-m", label] if durations >= 0: pytest_args += ["--durations=%s" % durations] if tests is None: tests = [self.module_name] pytest_args += ["--pyargs"] + list(tests) # run tests. _show_numpy_info() try: code = pytest.main(pytest_args) except SystemExit as exc: code = exc.code return code == 0
30.706186
79
0.612221
0fc9bcb527d5fe44323aef0ac7bfc93b4daf6ca8
3,476
py
Python
config/settings/base.py
TeamORIT/WhatsUpAddis-BE
702d14eff969673ce88dbd6f4cad690cbb580c30
[ "MIT" ]
null
null
null
config/settings/base.py
TeamORIT/WhatsUpAddis-BE
702d14eff969673ce88dbd6f4cad690cbb580c30
[ "MIT" ]
3
2018-11-30T22:18:39.000Z
2018-11-30T23:46:03.000Z
config/settings/base.py
TeamORIT/WhatsUpAddis-BE
702d14eff969673ce88dbd6f4cad690cbb580c30
[ "MIT" ]
null
null
null
""" Django settings for config project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] # Third Party apps INSTALLED_APPS += [ 'authtools', ] # Project apps INSTALLED_APPS += [ 'accounts', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': '', } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Africa/Addis_Ababa' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Custom Auth User Model AUTH_USER_MODEL = 'accounts.User'
24.652482
91
0.686709
f76988636febcc33fb36775812da45e5abffae6b
214
py
Python
benchmark/overhead.py
keithyipkw/InSync
3744b45f31f713de2dfc8c30507e67db96915e07
[ "MIT" ]
null
null
null
benchmark/overhead.py
keithyipkw/InSync
3744b45f31f713de2dfc8c30507e67db96915e07
[ "MIT" ]
null
null
null
benchmark/overhead.py
keithyipkw/InSync
3744b45f31f713de2dfc8c30507e67db96915e07
[ "MIT" ]
null
null
null
import sys import numpy as np import pandas as pd def main(): df = pd.read_csv(sys.argv[1], names=["Method", "Time"]) print(df.groupby("Method").describe().to_csv()) if __name__ == "__main__": main()
19.454545
59
0.64486
56c3f29d7d2fd08275474e893db5a4e895d61469
1,073
py
Python
bin/sa_haveibeenpwned/aob_py3/future/moves/urllib/parse.py
hRun/SA-haveibeenpwned
2a8ae3dedc405dc3c8dac1cb6a705a70f574afdb
[ "Apache-2.0" ]
2
2020-08-17T07:52:48.000Z
2020-12-18T16:39:32.000Z
bin/sa_haveibeenpwned/aob_py3/future/moves/urllib/parse.py
hRun/SA-haveibeenpwned
2a8ae3dedc405dc3c8dac1cb6a705a70f574afdb
[ "Apache-2.0" ]
5
2020-12-15T23:40:14.000Z
2022-02-23T15:43:18.000Z
bin/sa_haveibeenpwned/aob_py3/future/moves/urllib/parse.py
hRun/SA-haveibeenpwned
2a8ae3dedc405dc3c8dac1cb6a705a70f574afdb
[ "Apache-2.0" ]
4
2019-05-16T09:57:33.000Z
2021-07-14T12:31:21.000Z
from __future__ import absolute_import from future.standard_library import suspend_hooks from future.utils import PY3 if PY3: from urllib.parse import * else: __future_module__ = True from urlparse import (ParseResult, SplitResult, parse_qs, parse_qsl, urldefrag, urljoin, urlparse, urlsplit, urlunparse, urlunsplit) # we use this method to get at the original py2 urllib before any renaming # quote = sys.py2_modules['urllib'].quote # quote_plus = sys.py2_modules['urllib'].quote_plus # unquote = sys.py2_modules['urllib'].unquote # unquote_plus = sys.py2_modules['urllib'].unquote_plus # urlencode = sys.py2_modules['urllib'].urlencode # splitquery = sys.py2_modules['urllib'].splitquery with suspend_hooks(): from urllib import (quote, quote_plus, unquote, unquote_plus, urlencode, splitquery)
37
79
0.591799
5080baf08d27bd22d35addc82db0281b4c3a17f2
7,879
py
Python
napari/utils/misc.py
hectormz/napari
c53051ed3e3693ae74c86a5c4611f057293bd21d
[ "BSD-3-Clause" ]
null
null
null
napari/utils/misc.py
hectormz/napari
c53051ed3e3693ae74c86a5c4611f057293bd21d
[ "BSD-3-Clause" ]
null
null
null
napari/utils/misc.py
hectormz/napari
c53051ed3e3693ae74c86a5c4611f057293bd21d
[ "BSD-3-Clause" ]
null
null
null
"""Miscellaneous utility functions. """ import collections.abc import inspect import itertools import re from enum import Enum, EnumMeta from os import PathLike, fspath, path from typing import Optional, Sequence, Type, TypeVar import numpy as np ROOT_DIR = path.dirname(path.dirname(__file__)) def str_to_rgb(arg): """Convert an rgb string 'rgb(x,y,z)' to a list of ints [x,y,z]. """ return list( map(int, re.match(r'rgb\((\d+),\s*(\d+),\s*(\d+)\)', arg).groups()) ) def ensure_iterable(arg, color=False): """Ensure an argument is an iterable. Useful when an input argument can either be a single value or a list. If a color is passed then it will be treated specially to determine if it is iterable. """ if is_iterable(arg, color=color): return arg else: return itertools.repeat(arg) def is_iterable(arg, color=False): """Determine if a single argument is an iterable. If a color is being provided and the argument is a 1-D array of length 3 or 4 then the input is taken to not be iterable. """ if arg is None: return False elif type(arg) is str: return False elif np.isscalar(arg): return False elif color and isinstance(arg, (list, np.ndarray)): if np.array(arg).ndim == 1 and (len(arg) == 3 or len(arg) == 4): return False else: return True else: return True def is_sequence(arg): """Check if ``arg`` is a sequence like a list or tuple. return True: list tuple return False string numbers dict set """ if isinstance(arg, collections.abc.Sequence) and not isinstance(arg, str): return True return False def ensure_sequence_of_iterables(obj, length: Optional[int] = None): """Ensure that ``obj`` behaves like a (nested) sequence of iterables. If length is provided and the object is already a sequence of iterables, a ValueError will be raised if ``len(obj) != length``. Parameters ---------- obj : Any the object to check length : int, optional If provided, assert that obj has len ``length``, by default None Returns ------- iterable nested sequence of iterables, or an itertools.repeat instance Examples -------- In [1]: ensure_sequence_of_iterables([1, 2]) Out[1]: repeat([1, 2]) In [2]: ensure_sequence_of_iterables([(1, 2), (3, 4)]) Out[2]: [(1, 2), (3, 4)] In [3]: ensure_sequence_of_iterables({'a':1}) Out[3]: repeat({'a': 1}) In [4]: ensure_sequence_of_iterables(None) Out[4]: repeat(None) """ if obj and is_sequence(obj) and is_iterable(obj[0]): if length is not None and len(obj) != length: raise ValueError(f"length of {obj} must equal {length}") return obj return itertools.repeat(obj) def formatdoc(obj): """Substitute globals and locals into an object's docstring.""" frame = inspect.currentframe().f_back try: obj.__doc__ = obj.__doc__.format( **{**frame.f_globals, **frame.f_locals} ) return obj finally: del frame class StringEnumMeta(EnumMeta): def __getitem__(self, item): """ set the item name case to uppercase for name lookup """ if isinstance(item, str): item = item.upper() return super().__getitem__(item) def __call__( cls, value, names=None, *, module=None, qualname=None, type=None, start=1, ): """ set the item value case to lowercase for value lookup """ # simple value lookup if names is None: if isinstance(value, str): return super().__call__(value.lower()) elif isinstance(value, cls): return value else: raise ValueError( f'{cls} may only be called with a `str`' f' or an instance of {cls}' ) # otherwise create new Enum class return cls._create_( value, names, module=module, qualname=qualname, type=type, start=start, ) def keys(self): return list(map(str, self)) class StringEnum(Enum, metaclass=StringEnumMeta): def _generate_next_value_(name, start, count, last_values): """ autonaming function assigns each value its own name as a value """ return name.lower() def __str__(self): """String representation: The string method returns the lowercase string of the Enum name """ return self.value camel_to_snake_pattern = re.compile(r'(.)([A-Z][a-z]+)') camel_to_spaces_pattern = re.compile( r"((?<=[a-z])[A-Z]|(?<!\A)[A-R,T-Z](?=[a-z]))" ) def camel_to_snake(name): # https://gist.github.com/jaytaylor/3660565 return camel_to_snake_pattern.sub(r'\1_\2', name).lower() def camel_to_spaces(val): return camel_to_spaces_pattern.sub(r" \1", val) T = TypeVar('T', str, Sequence[str]) def abspath_or_url(relpath: T) -> T: """Utility function that normalizes paths or a sequence thereof. Expands user directory and converts relpaths to abspaths... but ignores URLS that begin with "http", "ftp", or "file". Parameters ---------- relpath : str or list or tuple A path, or list or tuple of paths. Returns ------- abspath : str or list or tuple An absolute path, or list or tuple of absolute paths (same type as input). """ if isinstance(relpath, (tuple, list)): return type(relpath)(abspath_or_url(p) for p in relpath) if isinstance(relpath, (str, PathLike)): relpath = fspath(relpath) if relpath.startswith(('http:', 'https:', 'ftp:', 'file:')): return relpath return path.abspath(path.expanduser(relpath)) raise TypeError("Argument must be a string, PathLike, or sequence thereof") class CallDefault(inspect.Parameter): def __str__(self): """wrap defaults""" kind = self.kind formatted = self._name # Fill in defaults if ( self._default is not inspect._empty or kind == inspect._KEYWORD_ONLY ): formatted = '{}={}'.format(formatted, formatted) if kind == inspect._VAR_POSITIONAL: formatted = '*' + formatted elif kind == inspect._VAR_KEYWORD: formatted = '**' + formatted return formatted class CallSignature(inspect.Signature): _parameter_cls = CallDefault def __str__(self): """do not render separators commented code is what was taken out from the copy/pasted inspect module code :) """ result = [] # render_pos_only_separator = False # render_kw_only_separator = True for param in self.parameters.values(): formatted = str(param) result.append(formatted) rendered = '({})'.format(', '.join(result)) if self.return_annotation is not inspect._empty: anno = inspect.formatannotation(self.return_annotation) rendered += ' -> {}'.format(anno) return rendered callsignature = CallSignature.from_callable def all_subclasses(cls: Type) -> set: """Recursively find all subclasses of class ``cls``. Parameters ---------- cls : class A python class (or anything that implements a __subclasses__ method). Returns ------- set the set of all classes that are subclassed from ``cls`` """ return set(cls.__subclasses__()).union( [s for c in cls.__subclasses__() for s in all_subclasses(c)] )
26.618243
79
0.595634
278f542169ee3982e74f11451af4f09a61b7a2e2
1,302
py
Python
examples/plot_implied_timescales.py
smsaladi/msmexplorer
7880545c239c8f33ababdd111f58fd553b8bbdde
[ "MIT" ]
6
2018-03-02T21:02:32.000Z
2020-05-26T08:23:24.000Z
examples/plot_implied_timescales.py
smsaladi/msmexplorer
7880545c239c8f33ababdd111f58fd553b8bbdde
[ "MIT" ]
9
2018-03-02T21:19:26.000Z
2021-07-26T13:54:30.000Z
examples/plot_implied_timescales.py
smsaladi/msmexplorer
7880545c239c8f33ababdd111f58fd553b8bbdde
[ "MIT" ]
5
2018-02-07T18:42:23.000Z
2021-04-29T07:01:50.000Z
""" Implied Timescales Plot =============== """ from msmbuilder.example_datasets import FsPeptide from msmbuilder.featurizer import DihedralFeaturizer from msmbuilder.decomposition import tICA from msmbuilder.cluster import MiniBatchKMeans from msmbuilder.msm import MarkovStateModel import numpy as np import msmexplorer as msme rs = np.random.RandomState(42) # Load Fs Peptide Data trajs = FsPeptide().get().trajectories # Extract Backbone Dihedrals featurizer = DihedralFeaturizer(types=['phi', 'psi']) diheds = featurizer.fit_transform(trajs) # Perform Dimensionality Reduction tica_model = tICA(lag_time=2, n_components=2) tica_trajs = tica_model.fit_transform(diheds) # Perform Clustering clusterer = MiniBatchKMeans(n_clusters=100, random_state=rs) clustered_trajs = clusterer.fit_transform(tica_trajs) lag_times = [1, 50, 100, 250, 500, 1000, 5000] msm_objs = [] for lag in lag_times: # Construct MSM msm = MarkovStateModel(lag_time=lag, n_timescales=5) msm.fit(clustered_trajs) msm_objs.append(msm) # Plot Timescales colors = ['pomegranate', 'beryl', 'tarragon', 'rawdenim', 'carbon'] msme.plot_implied_timescales(msm_objs, color_palette=colors, xlabel='Lag time (frames)', ylabel='Implied Timescales ($ns$)')
28.933333
67
0.736559
b88f412abd7df462d6b3c8b747a9272747cf0d18
1,304
py
Python
geopandas/io/sql.py
dimitri-justeau/geopandas
1731e44b2df88d08adfbc09260dda86d3d35e91d
[ "BSD-3-Clause" ]
3
2015-03-03T21:08:39.000Z
2015-12-14T23:22:47.000Z
geopandas/io/sql.py
dimitri-justeau/geopandas
1731e44b2df88d08adfbc09260dda86d3d35e91d
[ "BSD-3-Clause" ]
1
2021-06-02T00:37:10.000Z
2021-06-02T00:37:10.000Z
geopandas/io/sql.py
dimitri-justeau/geopandas
1731e44b2df88d08adfbc09260dda86d3d35e91d
[ "BSD-3-Clause" ]
2
2021-01-02T02:25:31.000Z
2021-01-10T16:41:32.000Z
import binascii from pandas import read_sql import shapely.wkb from geopandas import GeoSeries, GeoDataFrame def read_postgis(sql, con, geom_col='geom', crs=None, index_col=None, coerce_float=True, params=None): """ Returns a GeoDataFrame corresponding to the result of the query string, which must contain a geometry column. Examples: sql = "SELECT geom, kind FROM polygons;" df = geopandas.read_postgis(sql, con) Parameters ---------- sql: string con: DB connection object or SQLAlchemy engine geom_col: string, default 'geom' column name to convert to shapely geometries crs: optional CRS to use for the returned GeoDataFrame See the documentation for pandas.read_sql for further explanation of the following parameters: index_col, coerce_float, params """ df = read_sql(sql, con, index_col=index_col, coerce_float=coerce_float, params=params) if geom_col not in df: raise ValueError("Query missing geometry column '{0}'".format( geom_col)) wkb_geoms = df[geom_col] s = wkb_geoms.apply(lambda x: shapely.wkb.loads(binascii.unhexlify(x.encode()))) df[geom_col] = GeoSeries(s) return GeoDataFrame(df, crs=crs, geometry=geom_col)
27.744681
84
0.681748
445d18e9455c1203ec5db6e43b8ac9fd1f2dd4b7
4,595
py
Python
GAN/coupled_gan/cogan_pytorch.py
eastonhou/generative-models
02f19ff8f8980afea44ed0a8834bc5e1c4322b4d
[ "Unlicense" ]
7,386
2016-12-15T06:54:40.000Z
2022-03-31T16:21:47.000Z
GAN/coupled_gan/cogan_pytorch.py
milanhzj/generative-models
b930d5fa9e2f69adfd4ea8ec759f38f6ce6da4c2
[ "Unlicense" ]
150
2017-08-28T14:59:36.000Z
2022-03-11T23:21:35.000Z
GAN/coupled_gan/cogan_pytorch.py
milanhzj/generative-models
b930d5fa9e2f69adfd4ea8ec759f38f6ce6da4c2
[ "Unlicense" ]
2,247
2017-01-12T04:20:12.000Z
2022-03-27T00:42:14.000Z
import torch import torch.nn import torch.nn.functional as nn import torch.autograd as autograd import torch.optim as optim import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import os from torch.autograd import Variable from tensorflow.examples.tutorials.mnist import input_data import copy import scipy.ndimage.interpolation mnist = input_data.read_data_sets('../../MNIST_data', one_hot=True) mb_size = 32 z_dim = 100 X_dim = mnist.train.images.shape[1] y_dim = mnist.train.labels.shape[1] h_dim = 128 cnt = 0 lr = 1e-3 """ Shared Generator weights """ G_shared = torch.nn.Sequential( torch.nn.Linear(z_dim, h_dim), torch.nn.ReLU(), ) """ Generator 1 """ G1_ = torch.nn.Sequential( torch.nn.Linear(h_dim, X_dim), torch.nn.Sigmoid() ) """ Generator 2 """ G2_ = torch.nn.Sequential( torch.nn.Linear(h_dim, X_dim), torch.nn.Sigmoid() ) def G1(z): h = G_shared(z) X = G1_(h) return X def G2(z): h = G_shared(z) X = G2_(h) return X """ Shared Discriminator weights """ D_shared = torch.nn.Sequential( torch.nn.Linear(h_dim, 1), torch.nn.Sigmoid() ) """ Discriminator 1 """ D1_ = torch.nn.Sequential( torch.nn.Linear(X_dim, h_dim), torch.nn.ReLU() ) """ Discriminator 2 """ D2_ = torch.nn.Sequential( torch.nn.Linear(X_dim, h_dim), torch.nn.ReLU() ) def D1(X): h = D1_(X) y = D_shared(h) return y def D2(X): h = D2_(X) y = D_shared(h) return y D_params = (list(D1_.parameters()) + list(D2_.parameters()) + list(D_shared.parameters())) G_params = (list(G1_.parameters()) + list(G2_.parameters()) + list(G_shared.parameters())) nets = [G_shared, G1_, G2_, D_shared, D1_, D2_] def reset_grad(): for net in nets: net.zero_grad() G_solver = optim.Adam(G_params, lr=lr) D_solver = optim.Adam(D_params, lr=lr) X_train = mnist.train.images half = int(X_train.shape[0] / 2) # Real image X_train1 = X_train[:half] # Rotated image X_train2 = X_train[half:].reshape(-1, 28, 28) X_train2 = scipy.ndimage.interpolation.rotate(X_train2, 90, axes=(1, 2)) X_train2 = X_train2.reshape(-1, 28*28) # Cleanup del X_train def sample_x(X, size): start_idx = np.random.randint(0, X.shape[0]-size) return Variable(torch.from_numpy(X[start_idx:start_idx+size])) for it in range(100000): X1 = sample_x(X_train1, mb_size) X2 = sample_x(X_train2, mb_size) z = Variable(torch.randn(mb_size, z_dim)) # Dicriminator G1_sample = G1(z) D1_real = D1(X1) D1_fake = D1(G1_sample) G2_sample = G2(z) D2_real = D2(X2) D2_fake = D2(G2_sample) D1_loss = torch.mean(-torch.log(D1_real + 1e-8) - torch.log(1. - D1_fake + 1e-8)) D2_loss = torch.mean(-torch.log(D2_real + 1e-8) - torch.log(1. - D2_fake + 1e-8)) D_loss = D1_loss + D2_loss D_loss.backward() # Average the gradients for p in D_shared.parameters(): p.grad.data = 0.5 * p.grad.data D_solver.step() reset_grad() # Generator G1_sample = G1(z) D1_fake = D1(G1_sample) G2_sample = G2(z) D2_fake = D2(G2_sample) G1_loss = torch.mean(-torch.log(D1_fake + 1e-8)) G2_loss = torch.mean(-torch.log(D2_fake + 1e-8)) G_loss = G1_loss + G2_loss G_loss.backward() # Average the gradients for p in G_shared.parameters(): p.grad.data = 0.5 * p.grad.data G_solver.step() reset_grad() # Print and plot every now and then if it % 1000 == 0: print('Iter-{}; D1_loss: {:.4}; G1_loss: {:.4}; ' 'D2_loss: {:.4}; G2_loss: {:.4}' .format( it, D1_loss.data[0], G1_loss.data[0], D2_loss.data[0], G2_loss.data[0]) ) z = Variable(torch.randn(8, z_dim)) samples1 = G1(z).data.numpy() samples2 = G2(z).data.numpy() samples = np.vstack([samples1, samples2]) fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis('off') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect('equal') plt.imshow(sample.reshape(28, 28), cmap='Greys_r') if not os.path.exists('out/'): os.makedirs('out/') plt.savefig('out/{}.png' .format(str(cnt).zfill(3)), bbox_inches='tight') cnt += 1 plt.close(fig)
22.52451
72
0.604788
9412d7df98fae6e7e783eee6e49ebc07dbbbcf4b
6,752
py
Python
mycroft/audio/speech.py
damorosodaragona/mycroft-core
367542b5504c4ab3c9e5c46e3c8e3b150c01d3d0
[ "Apache-2.0" ]
2
2021-04-05T22:28:37.000Z
2021-06-16T00:24:41.000Z
mycroft/audio/speech.py
damorosodaragona/mycroft-core
367542b5504c4ab3c9e5c46e3c8e3b150c01d3d0
[ "Apache-2.0" ]
4
2021-06-08T22:45:08.000Z
2022-03-12T00:51:26.000Z
mycroft/audio/speech.py
mjkaye/mycroft-core-deb
f3ae5327a4d45a7e2e1d5511850097472b755c53
[ "Apache-2.0" ]
2
2020-09-28T01:38:34.000Z
2020-12-03T03:14:32.000Z
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import re import time from threading import Lock from mycroft.configuration import Configuration from mycroft.metrics import report_timing, Stopwatch from mycroft.tts import TTSFactory from mycroft.util import check_for_signal from mycroft.util.log import LOG from mycroft.messagebus.message import Message from mycroft.tts.remote_tts import RemoteTTSException from mycroft.tts.mimic_tts import Mimic bus = None # Mycroft messagebus connection config = None tts = None tts_hash = None lock = Lock() mimic_fallback_obj = None _last_stop_signal = 0 def handle_speak(event): """Handle "speak" message Parse sentences and invoke text to speech service. """ config = Configuration.get() Configuration.set_config_update_handlers(bus) global _last_stop_signal # if the message is targeted and audio is not the target don't # don't synthezise speech event.context = event.context or {} if event.context.get('destination') and not \ ('debug_cli' in event.context['destination'] or 'audio' in event.context['destination']): return # Get conversation ID if event.context and 'ident' in event.context: ident = event.context['ident'] else: ident = 'unknown' start = time.time() # Time of speech request with lock: stopwatch = Stopwatch() stopwatch.start() utterance = event.data['utterance'] listen = event.data.get('expect_response', False) # This is a bit of a hack for Picroft. The analog audio on a Pi blocks # for 30 seconds fairly often, so we don't want to break on periods # (decreasing the chance of encountering the block). But we will # keep the split for non-Picroft installs since it give user feedback # faster on longer phrases. # # TODO: Remove or make an option? This is really a hack, anyway, # so we likely will want to get rid of this when not running on Mimic if (config.get('enclosure', {}).get('platform') != "picroft" and len(re.findall('<[^>]*>', utterance)) == 0): # Remove any whitespace present after the period, # if a character (only alpha) ends with a period # ex: A. Lincoln -> A.Lincoln # so that we don't split at the period utterance = re.sub(r'\b([A-za-z][\.])(\s+)', r'\g<1>', utterance) chunks = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\;|\?)\s', utterance) # Apply the listen flag to the last chunk, set the rest to False chunks = [(chunks[i], listen if i == len(chunks) - 1 else False) for i in range(len(chunks))] for chunk, listen in chunks: # Check if somthing has aborted the speech if (_last_stop_signal > start or check_for_signal('buttonPress')): # Clear any newly queued speech tts.playback.clear() break try: mute_and_speak(chunk, ident, listen) except KeyboardInterrupt: raise except Exception: LOG.error('Error in mute_and_speak', exc_info=True) else: mute_and_speak(utterance, ident, listen) stopwatch.stop() report_timing(ident, 'speech', stopwatch, {'utterance': utterance, 'tts': tts.__class__.__name__}) def mute_and_speak(utterance, ident, listen=False): """Mute mic and start speaking the utterance using selected tts backend. Arguments: utterance: The sentence to be spoken ident: Ident tying the utterance to the source query """ global tts_hash # update TTS object if configuration has changed if tts_hash != hash(str(config.get('tts', ''))): global tts # Stop tts playback thread tts.playback.stop() tts.playback.join() # Create new tts instance tts = TTSFactory.create() tts.init(bus) tts_hash = hash(str(config.get('tts', ''))) LOG.info("Speak: " + utterance) try: tts.execute(utterance, ident, listen) except RemoteTTSException as e: LOG.error(e) mimic_fallback_tts(utterance, ident, listen) except Exception as e: LOG.error('TTS execution failed ({})'.format(repr(e))) def mimic_fallback_tts(utterance, ident, listen): global mimic_fallback_obj # fallback if connection is lost config = Configuration.get() tts_config = config.get('tts', {}).get("mimic", {}) lang = config.get("lang", "en-us") if not mimic_fallback_obj: mimic_fallback_obj = Mimic(lang, tts_config) tts = mimic_fallback_obj LOG.debug("Mimic fallback, utterance : " + str(utterance)) tts.init(bus) tts.execute(utterance, ident, listen) def handle_stop(event): """Handle stop message. Shutdown any speech. """ global _last_stop_signal if check_for_signal("isSpeaking", -1): _last_stop_signal = time.time() tts.playback.clear() # Clear here to get instant stop bus.emit(Message("mycroft.stop.handled", {"by": "TTS"})) def init(messagebus): """Start speech related handlers. Arguments: messagebus: Connection to the Mycroft messagebus """ global bus global tts global tts_hash global config bus = messagebus Configuration.set_config_update_handlers(bus) config = Configuration.get() bus.on('mycroft.stop', handle_stop) bus.on('mycroft.audio.speech.stop', handle_stop) bus.on('speak', handle_speak) tts = TTSFactory.create() tts.init(bus) tts_hash = hash(str(config.get('tts', ''))) def shutdown(): """Shutdown the audio service cleanly. Stop any playing audio and make sure threads are joined correctly. """ if tts: tts.playback.stop() tts.playback.join() if mimic_fallback_obj: mimic_fallback_obj.playback.stop() mimic_fallback_obj.playback.join()
34.10101
79
0.631961
3ec693d78e4b5e0a1f18ad421790ac2ef6c8b94c
3,682
py
Python
example/utils.py
maresb/keras-transformer
e7374b43625dc6e8997a1882ad94c886377bee74
[ "MIT" ]
null
null
null
example/utils.py
maresb/keras-transformer
e7374b43625dc6e8997a1882ad94c886377bee74
[ "MIT" ]
null
null
null
example/utils.py
maresb/keras-transformer
e7374b43625dc6e8997a1882ad94c886377bee74
[ "MIT" ]
null
null
null
import math import warnings import h5py from keras import Model def load_optimizer_weights(model: Model, model_save_path: str): """ Loads optimizer's weights for the model from an HDF5 file. """ with h5py.File(model_save_path, mode='r') as f: if 'optimizer_weights' in f: # Build train function (to get weight updates). # noinspection PyProtectedMember model._make_train_function() optimizer_weights_group = f['optimizer_weights'] optimizer_weight_names = [ n.decode('utf8') for n in optimizer_weights_group.attrs['weight_names']] optimizer_weight_values = [ optimizer_weights_group[n] for n in optimizer_weight_names] try: model.optimizer.set_weights(optimizer_weight_values) except ValueError: warnings.warn('Error in loading the saved optimizer ' 'state. As a result, your model is ' 'starting with a freshly initialized ' 'optimizer.') def contain_tf_gpu_mem_usage(): """ By default TensorFlow may try to reserve all available GPU memory making it impossible to train multiple networks at once. This function will disable such behaviour in TensorFlow. """ from keras import backend if backend.backend() != 'tensorflow': return try: # noinspection PyPackageRequirements import tensorflow as tf except ImportError: pass else: from keras.backend.tensorflow_backend import set_session config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True # dynamically grow the memory sess = tf.compat.v1.Session(config=config) set_session(sess) class CosineLRSchedule: """ Cosine annealing with warm restarts, described in paper "SGDR: stochastic gradient descent with warm restarts" https://arxiv.org/abs/1608.03983 Changes the learning rate, oscillating it between `lr_high` and `lr_low`. It takes `period` epochs for the learning rate to drop to its very minimum, after which it quickly returns back to `lr_high` (resets) and everything starts over again. With every reset: * the period grows, multiplied by factor `period_mult` * the maximum learning rate drops proportionally to `high_lr_mult` This class is supposed to be used with `keras.callbacks.LearningRateScheduler`. """ def __init__(self, lr_high: float, lr_low: float, initial_period: int = 50, period_mult: float = 2, high_lr_mult: float = 0.97): self._lr_high = lr_high self._lr_low = lr_low self._initial_period = initial_period self._period_mult = period_mult self._high_lr_mult = high_lr_mult def __call__(self, epoch, lr): return self.get_lr_for_epoch(epoch) def get_lr_for_epoch(self, epoch): assert epoch >= 0 t_cur = 0 lr_max = self._lr_high period = self._initial_period result = lr_max for i in range(epoch + 1): if i == epoch: # last iteration result = (self._lr_low + 0.5 * (lr_max - self._lr_low) * (1 + math.cos(math.pi * t_cur / period))) else: if t_cur == period: period *= self._period_mult lr_max *= self._high_lr_mult t_cur = 0 else: t_cur += 1 return result
35.747573
79
0.606735
a1b86159bccf26403c849c48e529828e7aef1a84
407
py
Python
myInsta_project/asgi.py
inziani/myInsta
3f564f8a0240fc02665b06b4032214046771d3ef
[ "Unlicense" ]
null
null
null
myInsta_project/asgi.py
inziani/myInsta
3f564f8a0240fc02665b06b4032214046771d3ef
[ "Unlicense" ]
null
null
null
myInsta_project/asgi.py
inziani/myInsta
3f564f8a0240fc02665b06b4032214046771d3ef
[ "Unlicense" ]
null
null
null
""" ASGI config for myInsta_project project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myInsta_project.settings') application = get_asgi_application()
23.941176
78
0.793612
ecc94a99f9d592417cb092b2ab4e0969a234edaa
6,114
py
Python
fabfile.py
Sibyx/dbs2019-project-assignment-nightgaunt
6c65364ef04b413a734dd495fba85569e2648d73
[ "Apache-2.0" ]
1
2020-03-21T16:44:48.000Z
2020-03-21T16:44:48.000Z
fabfile.py
Sibyx/dbs2019-project-assignment-nightgaunt
6c65364ef04b413a734dd495fba85569e2648d73
[ "Apache-2.0" ]
9
2019-05-17T09:26:59.000Z
2022-03-11T23:46:51.000Z
fabfile.py
Sibyx/mdns
6c65364ef04b413a734dd495fba85569e2648d73
[ "Apache-2.0" ]
null
null
null
import datetime import json import os import warnings from fabric import Connection, task from invoke import Context warnings.filterwarnings(action='ignore', module='.*paramiko.*') PROJECT_NAME = "mdns" BASE_DIR = os.path.dirname(os.path.abspath(__file__)) REPO_URL = "https://github.com/Sibyx/mdns.git" KEEP_RELEASES = 5 def _get_connection(ctx: Context, config: dict) -> Connection: ctx.host = config['host'] ctx.user = config['user'] ctx.connect_kwargs.key_filename = config['private_key'] ctx.port = config['port'] ctx = Connection( host=ctx.host, user=ctx.user, port=ctx.port, connect_kwargs=ctx.connect_kwargs, ) ctx.config['run']['echo'] = True return ctx def _parse_config(destination: str) -> dict: with open(f"{BASE_DIR}/.deploy/{destination}.json") as conf_file: return json.load(conf_file) @task def check(ctx, destination): config = _parse_config(destination) ctx = _get_connection(ctx, config['ssh']) ctx.run(f'{config["interpreter"]} --version') @task def setup(ctx, destination): config = _parse_config(destination) ctx = _get_connection(ctx, config['ssh']) shared_env = f"{config['deploy_to']}/shared/env" ctx.run(f"mkdir {config['deploy_to']}") with ctx.cd(config['deploy_to']): # Create directory structure ctx.run(f"mkdir shared") ctx.run(f"mkdir shared/logs") ctx.run(f"mkdir shared/media") ctx.run(f"mkdir releases") # Create Python virtualenv ctx.run(f"{config['interpreter']} -m venv shared/env") # Install deployment tools ctx.run(f"{shared_env}/bin/pip install pipfile-requirements --no-cache-dir") @task def deploy(ctx, destination): config = _parse_config(destination) ctx = _get_connection(ctx, config['ssh']) release = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") shared_env = f"{config['deploy_to']}/shared/env" # Set deploy to as current directory with ctx.cd(f"{config['deploy_to']}/releases"): # Clone repository ctx.run(f"git clone {REPO_URL} {release}") # Set current release directory as working directory with ctx.cd(f"{config['deploy_to']}/releases/{release}"): # Checkout correct revision ctx.run(f"git checkout {config['revision']}") # Just to be sure, run git pull ctx.run("git pull") # Install & update dependencies ctx.run(f"{shared_env}/bin/pip install --upgrade --no-cache-dir pip") ctx.run(f"{shared_env}/bin/pip install --upgrade --no-cache-dir pipfile-requirements") ctx.run(f"{shared_env}/bin/pipfile2req Pipfile.lock > requirements.txt") ctx.run(f"{shared_env}/bin/pip install -r requirements.txt --no-cache-dir") # Create .env file ctx.run("touch .env") for key, value in config['env'].items(): ctx.run(f'echo "{key}=\'{value}\'" >> .env') # Create symlinks for logs ctx.run(f"ln -s {config['deploy_to']}/shared/logs logs") ctx.run("touch logs/error.log") ctx.run("touch logs/request.log") ctx.run("touch logs/sql.log") # Create symlink for media ctx.run(f"rm -rf media") ctx.run(f"ln -s {config['deploy_to']}/shared/media media") # Migrate ctx.run( f"DJANGO_SETTINGS_MODULE={config['env']['DJANGO_SETTINGS_MODULE']} " f"{shared_env}/bin/python manage.py migrate --no-input" ) # Static files ctx.put("static/bundle.js", f"{config['deploy_to']}/releases/{release}/static/") ctx.put("static/bundle.js.map", f"{config['deploy_to']}/releases/{release}/static/") # Removing sensitive data ctx.run(f"rm -rf .deploy Pipfile Pipfile.lock requirements.txt") # Publish release with ctx.cd(config['deploy_to']): # Remove old symlink ctx.run("rm -f current") # Create symlink to the latest release ctx.run(f"ln -s {config['deploy_to']}/releases/{release} current") # Restart Gunicorn service # ctx.run("sudo systemctl restart mdns-web") # Clean old releases with ctx.cd(f"{config['deploy_to']}/releases"): ctx.run(f"ls -t . | sort -r | tail -n +{KEEP_RELEASES + 1} | xargs rm -rf --") @task def clean(ctx, destination): config = _parse_config(destination) ctx = _get_connection(ctx, config['ssh']) ctx.run(f"rm -rf {config['deploy_to']}") @task def user(ctx, destination): config = _parse_config(destination) ctx = _get_connection(ctx, config['ssh']) shared_env = f"{config['deploy_to']}/shared/env" # Move to project folder with ctx.cd(f"{config['deploy_to']}/current"): ctx.run( f"DJANGO_SETTINGS_MODULE={config['env']['DJANGO_SETTINGS_MODULE']} " f"{shared_env}/bin/python manage.py createsuperuser", pty=True ) @task def fake(ctx, destination): config = _parse_config(destination) ctx = _get_connection(ctx, config['ssh']) shared_env = f"{config['deploy_to']}/shared/env" # Move to project folder with ctx.cd(f"{config['deploy_to']}/current"): ctx.run( f"DJANGO_SETTINGS_MODULE={config['env']['DJANGO_SETTINGS_MODULE']} " f"{shared_env}/bin/python manage.py fake --clear", pty=True ) @task def organisms(ctx, destination): config = _parse_config(destination) ctx = _get_connection(ctx, config['ssh']) shared_env = f"{config['deploy_to']}/shared/env" # Move to project folder with ctx.cd(f"{config['deploy_to']}/current"): ctx.put("tmp/data.csv", f"{config['deploy_to']}/current/tmp") ctx.run( f"DJANGO_SETTINGS_MODULE={config['env']['DJANGO_SETTINGS_MODULE']} " f"{shared_env}/bin/python manage.py import_organisms --file tmp/data.csv", pty=True ) @task def restart(ctx, destination): config = _parse_config(destination) ctx = _get_connection(ctx, config['ssh']) # Restart Gunicorn service ctx.run("sudo systemctl restart mdns-web", pty=True)
30.878788
95
0.636572
5a9599d08a335223ff4a239fa9350dd7894a2917
41,614
py
Python
pychron/graph/graph.py
WiscAr/pychron
8d335d53ba7a5fc70760d9a7cb60540ad169ae84
[ "Apache-2.0" ]
null
null
null
pychron/graph/graph.py
WiscAr/pychron
8d335d53ba7a5fc70760d9a7cb60540ad169ae84
[ "Apache-2.0" ]
80
2018-07-17T20:10:20.000Z
2021-08-17T15:38:24.000Z
pychron/graph/graph.py
UManPychron/pychron
b84c9fd70072f9cbda30abe2c471e64fe3dd75d8
[ "Apache-2.0" ]
null
null
null
# =============================================================================== # Copyright 2011 Jake Ross # # 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. # =============================================================================== # =============enthought library imports======================= import csv import math import os import six from chaco.api import OverlayPlotContainer, \ VPlotContainer, HPlotContainer, GridPlotContainer, \ BasePlotContainer, Plot, ArrayPlotData from chaco.array_data_source import ArrayDataSource from chaco.axis import PlotAxis from enable.component_editor import ComponentEditor from numpy import array, hstack, Inf, column_stack from pyface.timer.api import do_after as do_after_timer from traits.api import Instance, List, Str, Property, Dict, Event, Bool from traitsui.api import View, Item, UItem from pychron.core.helpers.color_generators import colorname_generator as color_generator from pychron.core.helpers.filetools import add_extension from pychron.graph.context_menu_mixin import ContextMenuMixin from pychron.graph.ml_label import MPlotAxis from pychron.graph.offset_plot_label import OffsetPlotLabel from pychron.graph.tools.axis_tool import AxisTool from .tools.contextual_menu_tool import ContextualMenuTool VALID_FONTS = ['Arial', 'Lucida Grande', 'Geneva', 'Courier'] # 'Helvetica', # 'Times New Roman' CONTAINERS = {'v': VPlotContainer, 'h': HPlotContainer, 'g': GridPlotContainer, 'o': OverlayPlotContainer} IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.tiff', '.tif', '.gif'] DEFAULT_IMAGE_EXT = IMAGE_EXTENSIONS[0] def name_generator(base): i = 0 while 1: n = base + str(i) yield n i += 1 def fmt(data): return ['%0.8f' % d for d in data] def get_file_path(action='save as', **kw): from pyface.api import FileDialog, OK dlg = FileDialog(action=action, **kw) if dlg.open() == OK: return dlg.path def add_aux_axis(po, p, title='', color='black'): """ """ from chaco.axis import PlotAxis axis = PlotAxis(p, orientation='right', title=title, axis_line_visible=False, tick_color=color, tick_label_color=color, title_color=color) p.underlays.append(axis) po.add(p) po.x_grid.visible = False po.y_grid.visible = False def plot_axis_factory(p, key, normal, **kw): if key == 'x': m = p.index_mapper if normal: o = 'bottom' else: o = 'top' kw['tick_label_formatter'] = lambda x: '' else: if normal: o = 'left' else: o = 'right' kw['tick_label_formatter'] = lambda x: '' m = p.value_mapper from chaco.axis import PlotAxis ax = PlotAxis(component=p, mapper=m, orientation=o, axis_line_visible=False, **kw) return ax def plot_factory(legend_kw=None, **kw): """ """ p = Plot(data=ArrayPlotData(), **kw) vis = kw['show_legend'] if 'show_legend' in kw else False if not isinstance(vis, bool): align = vis vis = True else: align = 'lr' p.legend.visible = vis p.legend.align = align if legend_kw: p.legend.trait_set(**legend_kw) return p def container_factory(**kw): """ """ if 'kind' in kw: kind = kw['kind'] else: kind = 'v' cklass = CONTAINERS.get(kind, VPlotContainer) options = dict(bgcolor='white', padding=5, fill_padding=True) for k in options: if k not in list(kw.keys()): kw[k] = options[k] container = cklass(**kw) return container class Graph(ContextMenuMixin): """ """ name = Str plotcontainer = Instance(BasePlotContainer) container_dict = Dict plots = List(Plot) selected_plotid = Property(depends_on='selected_plot') selected_plot = Instance(Plot) window_title = '' window_width = 600 window_height = 500 window_x = 500 window_y = 250 width = 300 height = 300 resizable = True line_inspectors_write_metadata = False autoupdate = Bool(False) _convert_index = None status_text = Str x_limits_changed = Event xdataname_generators = List ydataname_generators = List yerdataname_generators = List color_generators = List series = List data_len = List data_limits = List def __init__(self, *args, **kw): """ """ super(Graph, self).__init__(*args, **kw) self.clear() pc = self.plotcontainer if self.use_context_menu: menu = ContextualMenuTool(parent=self, component=pc) pc.tools.append(menu) def update_group_attribute(self, plot, attr, value, dataid=0): pass def get_plotid_by_ytitle(self, *args, **kw): plot = self.get_plot_by_ytitle(*args, **kw) if plot is not None: return self.plots.index(plot) def get_plot_by_ytitle(self, txt, startswith=False): """ iso: str return None or Plot with y_axis.title equal to iso if startswith is True title only has to start with iso """ txt = str(txt) if startswith: is_equal = lambda x: x.startswith(txt) else: is_equal = lambda x: x.__eq__(txt) for po in self.plots: if is_equal(po.y_axis.title): return po else: print('plot titles txt={} {}'.format(txt, [po.y_axis.title for po in self.plots])) def get_num_plots(self): """ """ return len(self.plots) def get_num_series(self, plotid): """ """ return len(self.series[plotid]) def get_data(self, plotid=0, series=0, axis=0): """ """ if isinstance(series, (str, six.text_type)): s = series else: s = self.series[plotid][series][axis] p = self.plots[plotid] return p.data.get_data(s) def get_aux_data(self, plotid=0, series=1): plot = self.plots[plotid] si = plot.plots['aux{:03d}'.format(series)][0] oi = si.index.get_data() ov = si.value.get_data() return oi, ov def save_png(self, path=None): """ """ self._save(type_='pic', path=path) def save_pdf(self, path=None): """ """ from pychron.core.pdf.save_pdf_dialog import save_pdf save_pdf(self.plotcontainer) # self._save(type_='pdf', path=path) def save(self, path=None): """ """ self._save(path=path) def rescale_x_axis(self): # l, h = self.selected_plot.default_index.get_bounds() # self.set_x_limits(l, h, plotid=self.selected_plotid) r = self.selected_plot.index_range r.reset() def rescale_y_axis(self): r = self.selected_plot.value_range r.reset() def rescale_both(self): self.rescale_x_axis() self.rescale_y_axis() def export_data(self, path=None, plotid=None): """ """ if path is None: path = get_file_path() if path is not None: path = add_extension(path, '.csv') self._export_data(path, plotid) def read_xy(self, p, header=False, series=0, plotid=0): """ """ x = [] y = [] with open(p, 'r') as f: reader = csv.reader(f) if header: next(reader) for line in reader: if line[0].startswith('#'): continue if len(line) == 2: x.append(float(line[0])) y.append(float(line[1])) self.set_data(x, plotid, series) self.set_data(y, plotid, series, axis=1) def remove_rulers(self, plotid=0): from pychron.graph.guide_overlay import GuideOverlay plot = self.plots[plotid] for o in plot.overlays: if isinstance(o, GuideOverlay): plot.overlays.remove(o) def clear_plots(self): x = list(range(len(self.plots))) self.xdataname_generators = [name_generator('x') for _ in x] self.ydataname_generators = [name_generator('y') for _ in x] self.yerdataname_generators = [name_generator('yer') for _ in x] self.color_generators = [color_generator() for _ in x] self.series = [[] for _ in x] self.data_len = [[] for _ in x] self.data_limits = [[] for _ in x] for pi in self.plots: for k, pp in list(pi.plots.items()): for renderer in pp: try: pi.remove(renderer) except RuntimeError: print('failed removing {}'.format(renderer)) pi.plots.pop(k) self.clear_data() def clear(self, clear_container=True): """ """ self.clear_plots() self.plots = [] self.xdataname_generators = [name_generator('x')] self.ydataname_generators = [name_generator('y')] self.yerdataname_generators = [name_generator('yer')] self.color_generators = [color_generator()] self.series = [] self.data_len = [] self.data_limits = [] if clear_container: self.plotcontainer = pc = self.container_factory() if self.use_context_menu: menu = ContextualMenuTool(parent=self, component=pc) pc.tools.append(menu) self.selected_plot = None def set_axis_label_color(self, *args, **kw): """ """ kw['attr'] = 'title' self._set_axis_color(*args, **kw) def set_axis_tick_color(self, *args, **kw): """ """ attrs = ['tick_label', 'tick'] if 'attrs' in kw: attrs = kw['attrs'] for a in attrs: kw['attr'] = a self._set_axis_color(*args, **kw) def set_aux_data(self, x, y, plotid=0, series=1): p = self.plots[plotid].plots['aux{:03d}'.format(series)][0] p.index.set_data(x) p.value.set_data(y) def clear_data(self, plotid=None, **kw): if plotid is None: for i, p in enumerate(self.plots): for s in self.series[i]: for k in s: p.data.set_data(k, []) else: self.set_data([], **kw) def set_data(self, d, plotid=0, series=0, axis=0): """ """ if isinstance(series, int): n = self.series[plotid][series] series = n[axis] self.plots[plotid].data.set_data(series, d) def set_axis_traits(self, plotid=0, axis='x', **kw): """ """ plot = self.plots[plotid] attr = getattr(plot, '{}_axis'.format(axis)) attr.trait_set(**kw) def set_grid_traits(self, plotid=0, grid='x', **kw): """ """ plot = self.plots[plotid] attr = getattr(plot, '{}_grid'.format(grid)) attr.trait_set(**kw) def set_series_traits(self, d, plotid=0, series=0): """ """ plot = self.plots[plotid].plots['plot%i' % series][0] plot.trait_set(**d) self.plotcontainer.request_redraw() def get_series_color(self, plotid=0, series=0): if isinstance(series, int): series = 'plot{:03d}'.format(series) p = self.plots[plotid].plots[series][0] return p.color def get_series_label(self, plotid=0, series=0): """ """ r = '' legend = self.plots[plotid].legend if isinstance(series, str): if series in legend.labels: return series return try: r = legend.labels[series] except IndexError: pass return r def set_series_label(self, label, plotid=0, series=None): """ A chaco update requires that the legends labels match the keys in the plot dict save the plots from the dict resave them with label as the key """ legend = self.plots[plotid].legend if series is None: n = len(list(self.plots[plotid].plots.keys())) series = n - 1 if isinstance(series, int): series = 'plot{}'.format(series) try: legend.labels[series] = label except Exception as e: legend.labels.append(label) try: plots = self.plots[plotid].plots[series] except KeyError: print('set series label plotid={} {}'.format(plotid, list(self.plots[plotid].plots.keys()))) raise self.plots[plotid].plots[label] = plots self.plots[plotid].plots.pop(series) def clear_legend(self, keys, plotid=0): """ """ legend = self.plots[plotid].legend for key in keys: legend.plots.pop(key) def set_series_visibility(self, v, plotid=0, series=0): """ """ p = self.plots[plotid] if isinstance(series, int): series = 'plot%i' % series try: p.showplot(series) if v else p.hideplot(series) self.plotcontainer.invalidate_and_redraw() except KeyError as e: print('set series visibility', e, p.series) def get_x_limits(self, plotid=0): """ """ return self._get_limits('index', plotid=plotid) def get_y_limits(self, plotid=0): """ """ return self._get_limits('value', plotid=plotid) def set_y_limits(self, min_=None, max_=None, pad=0, plotid=0, **kw): """ """ mmin, mmax = self.get_y_limits(plotid) if min_ is None: min_ = mmin if max_ is None: max_ = mmax self._set_limits(min_, max_, 'value', plotid, pad, **kw) def set_x_limits(self, min_=None, max_=None, pad=0, plotid=0, **kw): """ """ if self._set_limits(min_, max_, 'index', plotid, pad, **kw): self.x_limits_changed = True def set_x_tracking(self, track, plotid=0): """ """ plot = self.plots[plotid] if track: plot.index_range.tracking_amount = track plot.index_range.high_setting = 'track' plot.index_range.low_setting = 'auto' else: plot.index_range.high_setting = 'auto' plot.index_range.low_setting = 'auto' def set_y_tracking(self, track, plotid=0): """ """ plot = self.plots[plotid] if track: plot.value_range.tracking_amount = track plot.value_range.high_setting = 'track' plot.value_range.low_setting = 'auto' else: plot.value_range.high_setting = 'auto' plot.value_range.low_setting = 'auto' def set_plot_title(self, t, font='modern', size=None, plotid=0): p = self.plots[plotid] p.title = t def set_title(self, t, font='modern', size=None): """ """ self._title = t pc = self.plotcontainer if pc.overlays: pc.overlays.pop() if font not in VALID_FONTS: font = 'modern' if size is None: size = 12 # self._title_font = font # self._title_size = size font = '{} {}'.format(font, size) from chaco.plot_label import PlotLabel pl = PlotLabel(t, component=pc, font=font) pc.overlays.append(pl) self.redraw() def get_x_title(self, plotid=0): """ """ return self._get_title('y_axis', plotid) def get_y_title(self, plotid=0): """ """ return self._get_title('x_axis', plotid) def set_x_title(self, title, plotid=None, **font): """ """ self._set_title('x_axis', title, plotid, **font) def set_y_title(self, title, plotid=None, **font): """ """ self._set_title('y_axis', title, plotid, **font) def add_axis_tool(self, plot, axis): t = AxisTool(component=axis) plot.tools.append(t) def add_limit_tool(self, plot, orientation, handler=None): from pychron.graph.tools.limits_tool import LimitsTool from pychron.graph.tools.limits_tool import LimitOverlay t = LimitsTool(component=plot, orientation=orientation) o = LimitOverlay(component=plot, tool=t) plot.tools.insert(0, t) plot.overlays.append(o) if handler: t.on_trait_change(handler, 'limits_updated') def add_plot_label(self, txt, plotid=0, overlay_position='inside top', hjustify='left', **kw): """ """ c = self.plots[plotid] pl = OffsetPlotLabel(txt, component=c, overlay_position=overlay_position, hjustify=hjustify, **kw) c.overlays.append(pl) return pl def add_data_label(self, x, y, plotid=0): """ """ from chaco.data_label import DataLabel plot = self.plots[plotid] label = DataLabel(component=plot, data_point=(x, y), label_position="top left", padding=40, bgcolor="lightgray", border_visible=False) plot.overlays.append(label) def delplot(self, plotid=0, series=0): plot = self.plots[plotid] if isinstance(series, int): series = 'plot{}'.format(series) plot.delplot(series) def new_plot(self, add=True, **kw): """ """ p = plot_factory(**kw) self.plots.append(p) self.color_generators.append(color_generator()) self.xdataname_generators.append(name_generator('x')) self.ydataname_generators.append(name_generator('y')) self.yerdataname_generators.append(name_generator('yer')) self.series.append([]) pc = self.plotcontainer if add: if not isinstance(add, bool): pc.insert(add, p) else: pc.add(p) zoom = kw['zoom'] if 'zoom' in kw else False pan = kw['pan'] if 'pan' in kw else False tools = [] if zoom: nkw = dict(tool_mode='box', always_on=False) if 'zoom_dict' in kw: zoomargs = kw['zoom_dict'] for k in zoomargs: nkw[k] = zoomargs[k] from chaco.tools.api import ZoomTool zt = ZoomTool(component=p, **nkw) p.overlays.append(zt) tools.append(zt) if pan: from .tools.pan_tool import MyPanTool as PanTool kwargs = dict(always_on=False) if isinstance(pan, str): kwargs['constrain'] = True kwargs['constrain_direction'] = pan kwargs['constrain_key'] = None pt = PanTool(p, container=pc, **kwargs) tools.append(pt) plotid = len(self.plots) - 1 for t in ['x', 'y']: title = '{}title'.format(t) if title in kw: self._set_title('{}_axis'.format(t), kw[title], plotid) p.tools = tools return p def new_graph(self, *args, **kw): """ """ raise NotImplementedError def new_series(self, x=None, y=None, yer=None, plotid=None, colors=None, color_map_name='hot', marker_size=2, **kw): """ """ if plotid is None: plotid = len(self.plots) - 1 kw['plotid'] = plotid kw['marker_size'] = marker_size plotobj, names, rd = self._series_factory(x, y, yer=yer, **kw) if 'type' in rd: ptype = rd['type'] if ptype == 'line_scatter': plotobj.plot(names, type='scatter', marker_size=2, marker='circle', color=rd['color'], outline_color=rd['color']) rd['type'] = 'line' elif ptype == 'scatter': if 'outline_color' not in rd: rd['outline_color'] = rd['color'] if 'selection_outline_color' not in rd: rd['selection_outline_color'] = rd['color'] if ptype == 'cmap_scatter': from chaco.default_colormaps import color_map_name_dict rd['selection_color'] = rd['color'] rd['selection_outline_color'] = rd['color'] rd['color_mapper'] = color_map_name_dict[color_map_name] c = self.series[plotid][-1][0].replace('x', 'c') self.plots[plotid].data.set_data(c, array(colors)) names += (c,) renderer = plotobj.plot(names, **rd) return renderer[0], plotobj def auto_update(self, *args, **kw): """ """ pass def add_aux_axis(self, po, p, title='', color='black'): """ """ axis = PlotAxis(p, orientation='right', title=title, axis_line_visible=False, tick_color=color, tick_label_color=color, title_color=color) p.underlays.append(axis) po.add(p) po.x_grid.visible = False po.y_grid.visible = False def add_aux_datum(self, datum, plotid=0, series=1, do_after=False): """ """ # def add(): plot = self.plots[plotid] si = plot.plots['aux{:03d}'.format(series)][0] oi = si.index.get_data() ov = si.value.get_data() si.index.set_data(hstack((oi, [datum[0]]))) si.value.set_data(hstack((ov, [datum[1]]))) # if do_after: # do_after_timer(do_after, add) # else: # add() def add_data(self, data, plotlist=None, **kw): """ """ if plotlist is None: plotlist = range(len(data)) for pi, d in zip(plotlist, data): self.add_datum(d, plotid=pi, **kw) def add_bulk_data(self, xs, ys, plotid=0, series=0, ypadding='0.1', update_y_limits=False): try: names = self.series[plotid][series] except IndexError: print('adding data', plotid, series, self.series[plotid]) plot = self.plots[plotid] data = plot.data for n, ds in ((names[0], xs), (names[1], ys)): xx = data.get_data(n) xx = hstack((xx, ds)) data.set_data(n, xx) if update_y_limits: ys = data[names[1]] mi = ys.min() ma = ys.max() if isinstance(ypadding, str): ypad = max(0.1, abs(mi - ma)) * float(ypadding) else: ypad = ypadding mi -= ypad ma += ypad # # if ymin_anchor is not None: # # mi = max(ymin_anchor, mi) # self.set_y_limits(min_=mi, max_=ma, plotid=plotid) def add_datum(self, datum, plotid=0, series=0, update_y_limits=False, ypadding=10, ymin_anchor=None, **kw): try: names = self.series[plotid][series] except (IndexError, TypeError): print('adding datum', plotid, series, self.series[plotid]) return plot = self.plots[plotid] if not hasattr(datum, '__iter__'): datum = (datum,) data = plot.data mi, ma = -Inf, Inf for i, (name, di) in enumerate(zip(names, datum)): d = data.get_data(name) nd = hstack((d, di)) data.set_data(name, nd) if i == 1: # y values mi = min(nd) ma = max(nd) if update_y_limits: if isinstance(ypadding, str): ypad = abs(ma - mi) * float(ypadding) else: ypad = ypadding mi -= ypad if ymin_anchor is not None: mi = max(ymin_anchor, mi) self.set_y_limits(min_=mi, max_=ma + ypad, plotid=plotid) def add_range_selector(self, plotid=0, series=0): from chaco.tools.range_selection import RangeSelection from chaco.tools.range_selection_overlay import RangeSelectionOverlay plot = self.plots[plotid].plots['plot{}'.format(series)][0] plot.active_tool = RangeSelection(plot, left_button_selects=True) plot.overlays.append(RangeSelectionOverlay(component=plot)) def add_guide(self, value, orientation='h', plotid=0, color=(0, 0, 0)): """ """ plot = self.plots[plotid] from pychron.graph.guide_overlay import GuideOverlay guide_overlay = GuideOverlay(component=plot, value=value, color=color) plot.overlays.append(guide_overlay) def add_vertical_rule(self, v, **kw): return self._add_rule(v, 'v', **kw) def add_horizontal_rule(self, v, **kw): return self._add_rule(v, 'h', **kw) def add_opposite_ticks(self, plotid=0, key=None): """ """ p = self.plots[plotid] if key is None: for key in ['x', 'y']: ax = plot_axis_factory(p, key, False) p.underlays.append(ax) else: ax = plot_axis_factory(p, key, False) p.underlays.append(ax) def add_minor_xticks(self, plotid=0, **kw): """ """ p = self.plots[plotid] from pychron.graph.minor_tick_overlay import MinorTicksOverlay m = MinorTicksOverlay(component=p, orientation='v', **kw) p.underlays.append(m) def add_minor_yticks(self, plotid=0, **kw): """ """ p = self.plots[plotid] from pychron.graph.minor_tick_overlay import MinorTicksOverlay m = MinorTicksOverlay(component=p, orientation='h', **kw) p.underlays.append(m) def set_time_xaxis(self, plotid=None): from chaco.scales_tick_generator import ScalesTickGenerator from chaco.scales.time_scale import CalendarScaleSystem if plotid is None: plotid = len(self.plots) - 1 p = self.plots[plotid] p.x_axis.tick_generator = ScalesTickGenerator(scale=CalendarScaleSystem()) def refresh(self): pass def invalidate_and_redraw(self): self.plotcontainer._layout_needed = True self.plotcontainer.invalidate_and_redraw() def redraw(self, force=True): """ """ if force: self.invalidate_and_redraw() else: self.plotcontainer.request_redraw() def get_next_color(self, exclude=None, plotid=0): cg = self.color_generators[plotid] nc = next(cg) if exclude is not None: if not isinstance(exclude, (list, tuple)): exclude = [exclude] while nc in exclude: nc = next(cg) return nc def container_factory(self, **kw): """ """ self.container_dict.update(kw) return container_factory(**self.container_dict) # private def _add_rule(self, v, orientation, plotid=0, add_move_tool=False, **kw): if v is None: return if 'plot' in kw: plot = kw['plot'] else: plot = self.plots[plotid] from pychron.graph.guide_overlay import GuideOverlay, GuideOverlayMoveTool l = GuideOverlay(plot, value=v, orientation=orientation, **kw) plot.underlays.append(l) if add_move_tool: plot.tools.append(GuideOverlayMoveTool(overlay=l)) return l def _export_data(self, path, plotid): # names = [] # a = None with open(path, 'w') as wfile: def write(l): wfile.write('{}\n'.format(l)) for plot in self.plots: line = plot.y_axis.title write(line) for k, pp in plot.plots.items(): pp = pp[0] a = column_stack((pp.index.get_data(), pp.value.get_data())) e = getattr(pp, 'yerror', None) header = 'x,y' if e is not None: try: a = column_stack((a, e.get_data())) header = 'x,y,e' except ValueError: pass write(k) write(header) for row in a: write(','.join(['{:0.8f}'.format(r) for r in row])) def _series_factory(self, x, y, yer=None, plotid=0, add=True, **kw): """ """ if x is None: x = array([]) if y is None: y = array([]) if 'yerror' in kw: if not isinstance(kw['yerror'], ArrayDataSource): kw['yerror'] = ArrayDataSource(kw['yerror']) yername = None plot = self.plots[plotid] if add: if 'xname' in kw: xname = kw['xname'] else: xname = next(self.xdataname_generators[plotid]) if 'yname' in kw: yname = kw['yname'] else: yname = next(self.ydataname_generators[plotid]) names = (xname, yname) # self.raw_x[plotid].append(x) # self.raw_y[plotid].append(y) if yer is not None: # self.raw_yer[plotid].append(yer) yername = next(self.yerdataname_generators[plotid]) names += (yername,) self.series[plotid].append(names) else: # try: xname = self.series[plotid][0][0] yname = self.series[plotid][0][1] if yer is not None: yername = self.series[plotid][0][2] # except IndexError: # pass plot.data.set_data(xname, x) plot.data.set_data(yname, y) if yer is not None: plot.data.set_data(yername, yer) colorkey = 'color' if 'color' not in list(kw.keys()): color_gen = self.color_generators[plotid] c = next(color_gen) else: c = kw['color'] if isinstance(c, str): c = c.replace(' ', '') if 'type' in kw: if kw['type'] == 'bar': colorkey = 'fill_color' elif kw['type'] == 'polygon': colorkey = 'face_color' kw['edge_color'] = c elif kw['type'] == 'scatter': if 'outline_color' not in kw: kw['outline_color'] = c for k, v in [ ('render_style', 'connectedpoints'), (colorkey, c), ('selection_color', 'white')]: if k not in list(kw.keys()): kw[k] = v return plot, (xname, yname), kw def _save(self, type_='pic', path=None): """ """ if path is None: path = get_file_path(default_directory=os.path.expanduser('~')) # from pyface.api import FileDialog, OK # dlg = FileDialog(action='save as', default_directory=os.path.expanduser('~')) # if dlg.open() == OK: # path = dlg.path # self.status_text = 'Image Saved: %s' % path if path is not None: if type_ == 'pdf' or path.endswith('.pdf'): self._render_to_pdf(filename=path) else: # auto add an extension to the filename if not present # extension is necessary for PIL compression # set default save type_ DEFAULT_IMAGE_EXT='.png' # see http://infohost.nmt.edu/tcc/help/pubs/pil/formats.html for ei in IMAGE_EXTENSIONS: if path.endswith(ei): self._render_to_pic(path) break else: path = add_extension(path, DEFAULT_IMAGE_EXT) self._render_to_pic(path) # base, ext = os.path.splitext(path) # # if not ext in IMAGE_EXTENSIONS: # path = ''.join((base, DEFAULT_IMAGE_EXT)) def _render_to_pdf(self, save=True, canvas=None, filename=None, dest_box=None): """ """ # save_pdf() # from chaco.pdf_graphics_context import PdfPlotGraphicsContext # # if filename: # # if not filename.endswith('.pdf'): # # filename += '.pdf' # filename = add_extension(filename, ext='.pdf') # # gc = PdfPlotGraphicsContext(filename=filename, # pdf_canvas=canvas, # dest_box=dest_box) # pc = self.plotcontainer # # # pc.do_layout(force=True) # # pc.use_backbuffer=False # gc.render_component(pc, valign='center') # if save: # gc.save() # # pc.use_backbuffer=True # # return gc def _render_to_pic(self, filename): """ """ from chaco.plot_graphics_context import PlotGraphicsContext p = self.plotcontainer gc = PlotGraphicsContext((int(p.outer_width), int(p.outer_height))) # p.use_backbuffer = False gc.render_component(p) # p.use_backbuffer = True gc.save(filename) def _render_to_clipboard(self): ''' on mac osx the bitmap gets copied to the clipboard the contents of clipboard are available to Preview and NeoOffice but not Excel More success may be had on windows Copying to clipboard is used to get a Graph into another program such as Excel or Illustrator Save the image as png then Insert Image is probably equivalent but not as convenient not working ''' def _get_title(self, axis, plotid): """ """ axis = getattr(self.plots[plotid], axis) return axis.title def _set_title(self, axistag, title, plotid, font=None, size=None): """ """ if plotid is None: plotid = len(self.plots) - 1 axis = getattr(self.plots[plotid], axistag) params = dict(title=title) if font not in VALID_FONTS: font = 'arial' if font is not None or size is not None: if size is None: size = 12 tfont = '{} {}'.format(font, size) params.update(title_font=tfont) axis.trait_set(**params) if '<sup>' in title or '<sub>' in title: plot = self.plots[plotid] for t in plot.tools: if t.component == axis: plot.tools.remove(t) break nxa = MPlotAxis() nxa.title = title nxa.clone(axis) t = AxisTool(component=nxa) plot.tools.append(t) setattr(self.plots[plotid], axistag, nxa) # axis = nxa self.plotcontainer.request_redraw() def _get_limits(self, axis, plotid): """ """ plot = self.plots[plotid] try: ra = getattr(plot, '%s_range' % axis) return ra.low, ra.high except AttributeError as e: print('get_limits', e) def _set_limits(self, mi, ma, axis, plotid, pad, pad_style='symmetric', force=False): if not plotid < len(self.plots): return plot = self.plots[plotid] ra = getattr(plot, '{}_range'.format(axis)) scale = getattr(plot, '{}_scale'.format(axis)) if isinstance(pad, str): # interpret pad as a percentage of the range # ie '0.1' => 0.1*(ma-mi) if ma is None: ma = ra.high if mi is None: mi = ra.low if mi == -Inf: mi = 0 if ma == Inf: ma = 100 if ma is not None and mi is not None: dev = ma - mi def convert(p): p = float(p) * dev if abs(p) < 1e-10: p = 1 return p if ',' in pad: pad = [convert(p) for p in pad.split(',')] else: pad = convert(pad) if not pad: pad = 0 # print(type(mi), isinstance(mi, (int, float)), pad_style) # if isinstance(mi, (int, float)): try: if isinstance(pad, list): mi -= pad[0] elif pad_style in ('symmetric', 'lower'): mi -= pad except TypeError: pass # if isinstance(ma, (int, float)): try: if isinstance(pad, list): ma += pad[1] elif pad_style in ('symmetric', 'upper'): ma += pad except TypeError: pass if scale == 'log': try: if mi <= 0: mi = Inf data = plot.data for di in data.list_data(): if 'y' in di: ya = sorted(data.get_data(di)) i = 0 try: while ya[i] <= 0: i += 1 if ya[i] < mi: mi = ya[i] except IndexError: mi = 0.01 mi = 10 ** math.floor(math.log(mi, 10)) ma = 10 ** math.ceil(math.log(ma, 10)) except ValueError: return change = False if mi == ma: if not pad: pad = 1 ra.high = ma + pad ra.low = ma - pad else: if mi is not None: change = ra.low != mi if isinstance(mi, (int, float)): if mi < ra.high: ra.low = mi else: ra.low = mi if ma is not None: change = change or ra.high != ma if isinstance(ma, (int, float)): if ma > ra.low: ra.high = ma else: ra.high = ma if change: self.redraw(force=force) return change def _get_selected_plotid(self): r = 0 if self.selected_plot is not None: r = self.plots.index(self.selected_plot) return r def show(self): do_after_timer(1, self.edit_traits) def panel_view(self): plot = Item('plotcontainer', style='custom', show_label=False, editor=ComponentEditor()) v = View(plot) return v def traits_view(self): v = View(UItem('plotcontainer', style='custom', editor=ComponentEditor()), title=self.window_title, width=self.window_width, height=self.window_height, x=self.window_x, y=self.window_y, resizable=self.resizable) return v if __name__ == '__main__': m = Graph() m.new_plot(zoom=True) m.new_series([1, 2, 3], [1, 41, 14]) m.configure_traits() # ============= EOF ====================================
28.878557
106
0.507113
22960c92547dae1db378ae82742536316ed9fab4
2,837
py
Python
pylearn2/sandbox/cuda_convnet/tests/test_stochastic_pool.py
ikervazquezlopez/Pylearn2
2971e8f64374ffde572d4cf967aad5342beaf5e0
[ "BSD-3-Clause" ]
3
2018-04-05T21:24:54.000Z
2021-09-14T01:48:36.000Z
pylearn2/sandbox/cuda_convnet/tests/test_stochastic_pool.py
ikervazquezlopez/Pylearn2
2971e8f64374ffde572d4cf967aad5342beaf5e0
[ "BSD-3-Clause" ]
null
null
null
pylearn2/sandbox/cuda_convnet/tests/test_stochastic_pool.py
ikervazquezlopez/Pylearn2
2971e8f64374ffde572d4cf967aad5342beaf5e0
[ "BSD-3-Clause" ]
2
2018-02-18T14:46:57.000Z
2019-05-03T11:51:45.000Z
import copy import numpy from theano.compat.six.moves import xrange import theano from theano.compat.python2x import Counter from pylearn2.sandbox.cuda_convnet.stochastic_pool import (stochastic_max_pool_c01b, weighted_max_pool_c01b) from pylearn2.testing.skip import skip_if_no_gpu from pylearn2.utils import float32_floatX skip_if_no_gpu() if theano.config.mode == 'FAST_COMPILE': mode_with_gpu = theano.compile.mode.get_mode('FAST_RUN').including('gpu') mode_without_gpu = theano.compile.mode.get_mode( 'FAST_RUN').excluding('gpu') else: mode_with_gpu = theano.compile.mode.get_default_mode().including('gpu') mode_without_gpu = theano.compile.mode.get_default_mode().excluding('gpu') #The CPU tests already compare C/Py, so we only check C/GPU mode_with_gpu = copy.copy(mode_with_gpu) mode_without_gpu = copy.copy(mode_without_gpu) mode_with_gpu.check_py_code = False mode_without_gpu.check_py_code = False # TODO add unit tests for: seed, differnt shape, stide, batch and channel size @float32_floatX def test_stochasatic_pool_samples(): """ check if the order of frequency of samples from stochastic max pool are same as the order of input values. """ ds = 3 stride = 3 rng = numpy.random.RandomState(220) data = rng.uniform(0, 10, size=(1, ds, ds, 1)).astype('float32') x = theano.tensor.tensor4() s_max = stochastic_max_pool_c01b(x, (ds, ds), (stride, stride)) f = theano.function([x], s_max, mode=mode_with_gpu) samples = [] for i in xrange(300): samples.append(numpy.asarray(f(data))[0, 0, 0, 0]) counts = Counter(samples) data = data.reshape(ds*ds) data.sort() data = data[::-1] for i in range(len(data) - 1): assert counts[data[i]] >= counts[data[i+1]] @float32_floatX def test_weighted_pool(): # TODO: test with different stride values rng = numpy.random.RandomState(220) for ds in [9, 2]: for batch in [1, 10]: for ch in [1, 16]: stride = ds data = rng.uniform(size=(batch, ds, ds, ch)).astype('float32') # op x = theano.tensor.tensor4() w_max = weighted_max_pool_c01b(x, (ds, ds), (stride, stride)) f = theano.function([x], w_max, mode=mode_with_gpu) op_val = numpy.asarray(f(data)) # python norm = data / data.sum(2).sum(1)[:, numpy.newaxis, numpy.newaxis, :] py_val = (data * norm).sum(2).sum(1)[:, numpy.newaxis, numpy.newaxis, :] assert numpy.allclose(op_val, py_val)
32.609195
84
0.606274
e8aeef3d4079afcf76860e114b402c6388ca3ea7
1,838
py
Python
monai/deploy/utils/fileutil.py
jlvahldiek/monai-deploy-app-sdk
050aeabec581067a11566f59a2970b075d36ae7c
[ "Apache-2.0" ]
28
2021-09-17T18:16:42.000Z
2022-03-31T16:32:36.000Z
monai/deploy/utils/fileutil.py
jlvahldiek/monai-deploy-app-sdk
050aeabec581067a11566f59a2970b075d36ae7c
[ "Apache-2.0" ]
109
2021-09-17T18:34:31.000Z
2022-03-31T21:04:35.000Z
monai/deploy/utils/fileutil.py
jlvahldiek/monai-deploy-app-sdk
050aeabec581067a11566f59a2970b075d36ae7c
[ "Apache-2.0" ]
11
2021-09-17T20:23:31.000Z
2022-03-29T08:55:19.000Z
# Copyright 2021 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import hashlib from pathlib import Path from typing import Callable, Union def checksum(path: Union[str, Path], hash_fn: str = "sha256", chunk_num_blocks=8192, **kwargs) -> str: """Return checksum of file or directory. Args: path (Union[str, Path]): A path to file or directory. hash_fn (str): A hash function to use. Defaults to 'sha256'. chunk_num_blocks (int): A number of blocks to read at once. Defaults to 8192. **kwargs: Additional arguments to pass to hash function. Returns: str: checksum of file or directory """ if hasattr(hashlib, hash_fn): hash_func: Callable = getattr(hashlib, hash_fn) else: raise ValueError("Unknown hash function") hashlib.blake2b h: hashlib._Hash = hash_func(**kwargs) path = Path(path) if path.is_file(): path_list = [path] else: path_list = sorted(path.glob("**/*")) for path in path_list: if not path.is_file(): continue with path.open("rb") as f: for chunk in iter(lambda: f.read(chunk_num_blocks * h.block_size), b""): h.update(chunk) return h.hexdigest() if __name__ == "__main__": import sys print(checksum(sys.argv[1]))
31.689655
102
0.669206
81101f98a4398945ef106d7b3646bcf59e88573e
9,810
py
Python
src/sklearn_evaluation/training/selector.py
abcnishant007/sklearn-evaluation
77ff2da43097b0451d8cf6f95c534409f612bf6a
[ "MIT" ]
351
2016-01-27T19:15:27.000Z
2022-03-09T15:40:56.000Z
src/sklearn_evaluation/training/selector.py
abcnishant007/sklearn-evaluation
77ff2da43097b0451d8cf6f95c534409f612bf6a
[ "MIT" ]
37
2016-03-16T03:57:59.000Z
2021-06-26T14:02:33.000Z
src/sklearn_evaluation/training/selector.py
abcnishant007/sklearn-evaluation
77ff2da43097b0451d8cf6f95c534409f612bf6a
[ "MIT" ]
30
2016-01-27T19:27:08.000Z
2022-03-31T06:09:59.000Z
""" When training models, it is common to try out different subsets of features or subpopulations. ``DataSelector`` allows you to define a series of transformations on your data so you can succinctly define a subsetting pipeline as a series of dictionaries. """ from copy import copy, deepcopy import abc import inspect import importlib import itertools from collections.abc import Mapping import pandas as pd from decorator import decorator from sklearn_evaluation.exceptions import DataSelectorError from sklearn_evaluation.util import map_parameters_in_fn_call from sklearn_evaluation.table import Table def import_from_dotted_path(dotted_path): parts = dotted_path.split('.') mod_name, callable_ = '.'.join(parts[:-1]), parts[-1] mod = importlib.import_module(mod_name) fn = getattr(mod, callable_) return fn def expand_value(value): """ If value is a str with at least one dot ("."), try to import it and call it, if anything fails, return the value """ if isinstance(value, str) and '.' in value: parts = value.split('.') mod_name, callable = '.'.join(parts[:-1]), parts[-1] try: mod = importlib.import_module(mod_name) except ModuleNotFoundError: return value try: fn = getattr(mod, callable) except AttributeError: return value return fn() else: return value # NOTE: consider deleting @decorator def expand_arguments(func, *args, **kwargs): """ Fnctions decorated with expand_argument call "expand_value" on each passed argument, which will interpred as a "dotted path" any string with dots on it and replace the value by the value returned by a function imported from that location (no arguments passed), if no function is found in such location, the original value is returned """ return func(*[expand_value(arg) for arg in args], **{k: expand_value(v) for k, v in kwargs.items()}) def concatenate_over(argname): """Decorator to "vectorize" functions and concatenate outputs """ def _prepare_args(arg_map, value): params = copy(arg_map) params[argname] = value return params @decorator def _concatenate_over(func, *args, **kwargs): """Validate that an agument is a proportion [0, 1.0] """ arg_map = map_parameters_in_fn_call(args, kwargs, func) value = arg_map.get(argname) if isinstance(value, list): return list( itertools.chain.from_iterable( func(**_prepare_args(arg_map, v)) for v in value)) else: return func(**arg_map) return _concatenate_over class Step(abc.ABC): @abc.abstractmethod def transform(self, df): pass def get_args(self): args = inspect.getfullargspec(self.__init__).args args.remove('self') return {arg: getattr(self, arg) for arg in args} # NOTE: consider deleting this, just show if in the transform summary def get_params(self): return {k: v for k, v in self.__dict__.items() if k.endswith('_')} @concatenate_over('prefix') def _with_prefix(df, prefix): return [] if not prefix else [ c for c in df.columns if c.startswith(prefix) ] @concatenate_over('suffix') def _with_suffix(df, suffix): return [] if not suffix else [c for c in df.columns if c.endswith(suffix)] @concatenate_over('substr') def _contains(df, substr): return [] if not substr else [c for c in df.columns if substr in c] def _with_max_na_prop(df, max_prop): if max_prop is not None: na_prop = df.isna().sum(axis='index') / len(df) return na_prop[na_prop > max_prop].index.tolist() else: return [] class ColumnDrop(Step): """Drop columns Parameters ---------- names List of columns to drop prefix Drop columns with this prefix (or list of) suffix Drop columns with this suffix (or list of) contains Drop columns if they contains this substring max_na_prop Drop columns whose proportion of NAs [0, 1] is larger than this """ @expand_arguments def __init__(self, names: list = None, prefix: str = None, suffix: str = None, contains: str = None, max_na_prop: float = None): self.names = names or [] self.prefix = prefix self.suffix = suffix self.contains = contains self.max_na_prop = max_na_prop self.to_delete_ = None def transform(self, df, return_summary=False): self.to_delete_ = set(self.names + _with_prefix(df, self.prefix) + _with_suffix(df, self.suffix) + _with_max_na_prop(df, self.max_na_prop) + _contains(df, self.contains)) out = df.drop(self.to_delete_, axis='columns') return out if not return_summary else (out, self.transform_summary(df)) def transform_summary(self, df): return 'Deleted {:,} columns: {}'.format(len(self.to_delete_), self.to_delete_) def _incomplete_cases(df): nas = df.isna().sum(axis='columns') return nas[nas > 0].index def _query(df, query): return df.query(query).index class RowDrop(Step): """Drop rows Parameters ---------- if_nas If True, deletes all rows where there is at leat one NA query Drops all rows matching the query (passed via pandas.query) """ @expand_arguments def __init__(self, if_nas: bool = False, query: str = None): self.if_nas = if_nas self.query = query def transform(self, df, return_summary=False): to_delete = pd.Index([]) if self.if_nas: to_delete = to_delete.union(_incomplete_cases(df)) if self.query: to_delete = to_delete.union(_query(df, self.query)) out = df[~df.index.isin(to_delete)] return out if not return_summary else (out, self.transform_summary( df, to_delete)) def transform_summary(self, df, to_delete): n = len(to_delete) return 'Deleted {:,} rows ({:.1%})'.format(n, n / len(df)) class ColumnKeep(Step): """Subset columns Parameters ---------- names List of columns to keep """ def __init__(self, names: list = None, dotted_path: str = None): self.names = names or [] self.dotted_path = dotted_path def transform(self, df, return_summary=False): to_keep = copy(self.names) if self.dotted_path: fn = import_from_dotted_path(self.dotted_path) to_keep.extend(fn(df)) # remove duplicates to_keep = list(set(to_keep)) return df[to_keep], self.transform_summary(to_keep) def transform_summary(self, to_keep): return 'Keeping {:,} column(s)'.format(len(to_keep)) class DataSelector: """Subset a pandas.DataFrame by passing a series of steps Parameters ---------- *steps Steps to apply to the data sequentially (order matters). Each step must be a dictionary with a key "kind" whose value must be one of "column_drop", "row_drop" or "column_keep". The rest of the key-value pairs must match the signature for the corresponding Step objects """ def __init__(self, *steps): steps = deepcopy(steps) self.steps = [_instantiate_step(step) for step in steps] def transform(self, df, return_summary: bool = False): """Apply steps Parameters ---------- df Data frame to transform return_summary If False, the function only returns the output data frame, if True, it also returns a summary table """ result = df summaries = [] for i, step in enumerate(self.steps): try: result = step.transform(result, return_summary=return_summary) except Exception as e: raise DataSelectorError('Error executing step {} ({})'.format( i, type(step).__name__)) from e if return_summary: result, summary = result summaries.append(summary) if not return_summary: return result else: table = Table([(type(step).__name__, summary) for step, summary in zip(self.steps, summaries)], header=['Step', 'Summary']) return result, table def _get_table(self): return Table([(type(step).__name__, step.get_args(), step.get_params()) for step in self.steps], header=['Step', 'Args', 'Params']) def __repr__(self): table = str(self._get_table()) table = '{} with steps:\n'.format(type(self).__name__) + table return table def _repr_html_(self): return self._get_table().to_html() def _instantiate_step(step): if not isinstance(step, Mapping): raise TypeError('step must be a mapping, got {}'.format( type(step).__name__)) kind = step.pop('kind', None) if kind not in _mapping: raise ValueError('Each step must have a kind key with one of ' 'the valid values: {}'.format(set(_mapping))) return _mapping[kind](**step) _mapping = { 'column_drop': ColumnDrop, 'row_drop': RowDrop, 'column_keep': ColumnKeep, }
29.459459
79
0.601427
76a6db428459ea5739eacde9f14bdbe015b4b3bf
1,779
py
Python
test/unit/devices/test_default.py
mikiec84/ncclient
7662666aac957fcf6aeb50c05f6b9816179cfd23
[ "Apache-2.0" ]
3
2015-11-03T17:11:42.000Z
2016-12-09T14:47:44.000Z
test/unit/devices/test_default.py
mikiec84/ncclient
7662666aac957fcf6aeb50c05f6b9816179cfd23
[ "Apache-2.0" ]
null
null
null
test/unit/devices/test_default.py
mikiec84/ncclient
7662666aac957fcf6aeb50c05f6b9816179cfd23
[ "Apache-2.0" ]
null
null
null
import unittest from ncclient.devices.default import DefaultDeviceHandler capabilities = ['urn:ietf:params:netconf:base:1.0', 'urn:ietf:params:netconf:base:1.1', 'urn:ietf:params:netconf:capability:writable-running:1.0', 'urn:ietf:params:netconf:capability:candidate:1.0', 'urn:ietf:params:netconf:capability:confirmed-commit:1.0', 'urn:ietf:params:netconf:capability:rollback-on-error:1.0', 'urn:ietf:params:netconf:capability:startup:1.0', 'urn:ietf:params:netconf:capability:url:1.0?scheme=http,ftp,file,https,sftp', 'urn:ietf:params:netconf:capability:validate:1.0', 'urn:ietf:params:netconf:capability:xpath:1.0', 'urn:ietf:params:netconf:capability:notification:1.0', 'urn:liberouter:params:netconf:capability:power-control:1.0', 'urn:ietf:params:netconf:capability:interleave:1.0', 'urn:ietf:params:netconf:capability:with-defaults:1.0'] class TestDefaultDevice(unittest.TestCase): def setUp(self): self.obj = DefaultDeviceHandler() def test_get_capabilties(self): self.assertEqual(self.obj.get_capabilities(), capabilities) def test_get_ssh_subsystem_names(self): self.assertEqual(self.obj.get_ssh_subsystem_names(), ["netconf"]) def test_perform_qualify_check(self): self.assertTrue(self.obj.perform_qualify_check()) def test_handle_raw_dispatch(self): self.assertFalse(self.obj.handle_raw_dispatch(None)) def test_handle_connection_exceptions(self): self.assertFalse(self.obj.handle_connection_exceptions(None)) suite = unittest.TestSuite() unittest.TextTestRunner().run(suite)
41.372093
93
0.678471
74f3f72d9087f66a6b3e425e04bb69e0c815a9bb
2,535
py
Python
hear_me_django_app/accounts/api/views.py
kamil1marczak/hear_me_django_app
2a567c15acddbf6bf183c6c637a3785c2a9c9c5c
[ "MIT" ]
null
null
null
hear_me_django_app/accounts/api/views.py
kamil1marczak/hear_me_django_app
2a567c15acddbf6bf183c6c637a3785c2a9c9c5c
[ "MIT" ]
null
null
null
hear_me_django_app/accounts/api/views.py
kamil1marczak/hear_me_django_app
2a567c15acddbf6bf183c6c637a3785c2a9c9c5c
[ "MIT" ]
null
null
null
from rest_framework.generics import ListAPIView from hear_me_django_app.accounts.models import Account, Card, Transaction, AccountOwner, Company from hear_me_django_app.accounts.api.serializers import AccountSerializer, TransactionSerializer, \ TransactionReadSerializer from hear_me_django_app.accounts.api.filters import AccountFilterSet, TransactionFilterSet # from .mixins import ReadWriteSerializerMixin # from hear_me_django_app.accounts.api.filters import AccountFilterSet # from hear_me_django_app.accounts.actions import TransactionManager # class AccountView(ListAPIView): # queryset = Account.objects.all() # serializer_class = AccountSerializer # filterset_class = AccountFilterSet # # def filter_queryset(self, request): # return super().filter_queryset(request)[:100] # class WineSearchWordsView(ListAPIView): # queryset = AccountSearchWord.objects.all() # serializer_class = WineSearchWordSerializer # filterset_class = WineSearchWordFilterSet # from django.contrib.auth import get_user_model # from rest_framework import status # from rest_framework.decorators import action from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin, CreateModelMixin # from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet class AccountViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet): serializer_class = AccountSerializer queryset = Account.objects.all() filterset_class = AccountFilterSet class TransactionViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, CreateModelMixin, GenericViewSet,): serializer_class = TransactionReadSerializer # read_serializer_class = TransactionReadSerializer # write_serializer_class = TransactionSerializer queryset = Transaction.objects.all() filterset_class = TransactionFilterSet def get_serializer_class(self): if self.action in ["create", "update", "partial_update", "destroy"]: return TransactionSerializer return TransactionReadSerializer # def retrieve( self): # def create(self, request): # # t = # def get_queryset(self, *args, **kwargs): # return self.queryset.filter(id=self.request.user.id) # # @action(detail=False, methods=["GET"]) # def me(self, request): # serializer = UserSerializer(request.user, context={"request": request}) # return Response(status=status.HTTP_200_OK, data=serializer.data)
39.609375
114
0.774359
5afe4624ca380858eaf23d69d883bced8526a76f
1,393
py
Python
server.py
JuveriyaFarheen/video-record
580869ffebd41dcf253c0a8c50862e2be0de91ad
[ "MIT" ]
null
null
null
server.py
JuveriyaFarheen/video-record
580869ffebd41dcf253c0a8c50862e2be0de91ad
[ "MIT" ]
null
null
null
server.py
JuveriyaFarheen/video-record
580869ffebd41dcf253c0a8c50862e2be0de91ad
[ "MIT" ]
null
null
null
from flask import Flask, render_template, Response, jsonify, request from camera import VideoCamera app = Flask(__name__) video_camera = None global_frame = None @app.route('/') def index(): return render_template('index.html') @app.route('/record_status', methods=['POST']) def record_status(): global video_camera if video_camera == None: video_camera = VideoCamera() json = request.get_json() status = json['status'] if status == "true": video_camera.start_record() return jsonify(result="started") else: video_camera.stop_record() return jsonify(result="stopped") def video_stream(): global video_camera global global_frame if video_camera == None: video_camera = VideoCamera() while True: frame = video_camera.get_frame() if frame != None: global_frame = frame yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') else: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n') @app.route('/video_viewer') def video_viewer(): return Response(video_stream(), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='127.0.0.1', threaded=True)
25.796296
93
0.60804
50cf8881a23805180243ba4df2efdd115dee375f
356
py
Python
0-run-with-images.py
GunarakulanGunaretnam/face-detection-in-python
76cb91559a88cb32448ee3f6cca942dbef554089
[ "Apache-2.0" ]
null
null
null
0-run-with-images.py
GunarakulanGunaretnam/face-detection-in-python
76cb91559a88cb32448ee3f6cca942dbef554089
[ "Apache-2.0" ]
null
null
null
0-run-with-images.py
GunarakulanGunaretnam/face-detection-in-python
76cb91559a88cb32448ee3f6cca942dbef554089
[ "Apache-2.0" ]
null
null
null
import cv2 import numpy as np faceModel = cv2.CascadeClassifier("haarcascade-frontalface-default.xml") img = cv2.imread("image-3.jpg") gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = faceModel.detectMultiScale(gray,1.3,5) #rgb #BGR for(x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow("Display",img) cv2.waitKey(0)
17.8
72
0.716292
c8b091025f0b178462f0a2081b0c70fc65ee6438
344
py
Python
bilal/app/__init__.py
ibrahimediz/flaskrest
e0d52d35dc5b3aff8a7a15832c84e1c3882c4f36
[ "MIT" ]
null
null
null
bilal/app/__init__.py
ibrahimediz/flaskrest
e0d52d35dc5b3aff8a7a15832c84e1c3882c4f36
[ "MIT" ]
null
null
null
bilal/app/__init__.py
ibrahimediz/flaskrest
e0d52d35dc5b3aff8a7a15832c84e1c3882c4f36
[ "MIT" ]
null
null
null
from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app,db) from app.api import bp as api_bp app.register_blueprint(api_bp, url_prefix='/api') from app import routes, models
19.111111
49
0.799419
8000c447737e0a95f1850e04e56fa2c5394166d1
44
py
Python
lennybot/__main__.py
Squaar/LennyBot
184113535e1fbbf1a507ddda7a878f72db4114b8
[ "MIT" ]
1
2019-11-09T12:48:56.000Z
2019-11-09T12:48:56.000Z
lennybot/__main__.py
Squaar/LennyBot
184113535e1fbbf1a507ddda7a878f72db4114b8
[ "MIT" ]
5
2018-04-22T20:29:28.000Z
2020-07-25T19:20:30.000Z
lennybot/__main__.py
Squaar/LennyBot
184113535e1fbbf1a507ddda7a878f72db4114b8
[ "MIT" ]
null
null
null
from . import lennyrunner lennyrunner.main()
22
25
0.818182
48f52fa34d45050ff8fdea499e886cace69ae691
463
py
Python
astute-dashboard/astutedashboard/dashboards/billing/image_report/panel.py
sreenathmmenon/astttproject
464fe20c8acf14afdfe03d1e4758e3df2b06196e
[ "Apache-2.0" ]
null
null
null
astute-dashboard/astutedashboard/dashboards/billing/image_report/panel.py
sreenathmmenon/astttproject
464fe20c8acf14afdfe03d1e4758e3df2b06196e
[ "Apache-2.0" ]
null
null
null
astute-dashboard/astutedashboard/dashboards/billing/image_report/panel.py
sreenathmmenon/astttproject
464fe20c8acf14afdfe03d1e4758e3df2b06196e
[ "Apache-2.0" ]
1
2018-02-24T10:32:41.000Z
2018-02-24T10:32:41.000Z
# # Copyright 2017 NephoScale # from django.utils.translation import ugettext_lazy as _ import horizon from astutedashboard.dashboards.billing import dashboard class WindowsInstanceReport(horizon.Panel): name = _("Windows/SQL Instance Report") slug = "windows_instance_report" #Only the following roles are allowed to access this dashboard permissions = (('openstack.roles.admin',),) dashboard.M1AstutePanels.register(WindowsInstanceReport)
24.368421
66
0.784017
900875c1d95ba466bd3d3f4989af63cfad17917e
964
py
Python
models/universal_sentence_encoder_multilingual_large/v1/utils.py
rhangelxs/russian_embeddings
64821cdff03ff97752b6c80621bedf9e2227a0ba
[ "MIT" ]
null
null
null
models/universal_sentence_encoder_multilingual_large/v1/utils.py
rhangelxs/russian_embeddings
64821cdff03ff97752b6c80621bedf9e2227a0ba
[ "MIT" ]
5
2020-09-26T00:18:44.000Z
2022-02-10T00:22:42.000Z
models/universal_sentence_encoder_multilingual_large/v1/utils.py
rhangelxs/russian_embeddings
64821cdff03ff97752b6c80621bedf9e2227a0ba
[ "MIT" ]
null
null
null
import numpy import tensorflow as tf import tensorflow_hub as hub import tf_sentencepiece class EmbeddingWrapper: def __init__(self): module_url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual-large/1" # Set up graph. g = tf.Graph() with g.as_default(): self.module = hub.Module(module_url) # load tfhub module self.question = tf.placeholder(dtype=tf.string, shape=[None]) # question self.question_embedding = self.module(self.question) init_op = tf.group( [tf.global_variables_initializer(), tf.tables_initializer()]) g.finalize() # Initialize session. session = tf.Session(graph=g) session.run(init_op) self.session = session def str2vec(self, string): result = self.session.run(self.question_embedding, feed_dict={self.question: [string]})[0] return result
32.133333
98
0.63278
f1bbb1bf5bba46022785f624cfacb33204de940d
1,874
py
Python
addons/l10n_ch/models/account_journal.py
SHIVJITH/Odoo_Machine_Test
310497a9872db7844b521e6dab5f7a9f61d365a4
[ "Apache-2.0" ]
null
null
null
addons/l10n_ch/models/account_journal.py
SHIVJITH/Odoo_Machine_Test
310497a9872db7844b521e6dab5f7a9f61d365a4
[ "Apache-2.0" ]
null
null
null
addons/l10n_ch/models/account_journal.py
SHIVJITH/Odoo_Machine_Test
310497a9872db7844b521e6dab5f7a9f61d365a4
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api from odoo.exceptions import ValidationError from odoo.addons.base_iban.models.res_partner_bank import validate_iban from odoo.addons.base.models.res_bank import sanitize_account_number class AccountJournal(models.Model): _inherit = 'account.journal' # creation of bank journals by giving the account number, allow craetion of the l10n_ch_postal = fields.Char('Client Number', related='bank_account_id.l10n_ch_postal', readonly=False) invoice_reference_model = fields.Selection(selection_add=[ ('ch', 'Switzerland') ], ondelete={'ch': lambda recs: recs.write({'invoice_reference_model': 'odoo'})}) @api.model def create(self, vals): rslt = super(AccountJournal, self).create(vals) # The call to super() creates the related bank_account_id field if 'l10n_ch_postal' in vals: rslt.l10n_ch_postal = vals['l10n_ch_postal'] return rslt def write(self, vals): rslt = super(AccountJournal, self).write(vals) # The call to super() creates the related bank_account_id field if necessary if 'l10n_ch_postal' in vals: for record in self.filtered('bank_account_id'): record.bank_account_id.l10n_ch_postal = vals['l10n_ch_postal'] return rslt @api.onchange('bank_acc_number') def _onchange_set_l10n_ch_postal(self): try: validate_iban(self.bank_acc_number) is_iban = True except ValidationError: is_iban = False if is_iban: self.l10n_ch_postal = self.env['res.partner.bank']._retrieve_l10n_ch_postal(sanitize_account_number(self.bank_acc_number)) else: self.l10n_ch_postal = self.bank_acc_number
36.745098
134
0.691569
82ec93fd6697b169d9054a8445289d161a88901c
8,293
py
Python
gpio/rpi_gpio.py
jamesgoodhouse/sensorReporter
925868982cb0571f2d2204f0474d8f8d714f3087
[ "Apache-2.0" ]
99
2016-02-24T00:17:59.000Z
2022-02-19T08:07:26.000Z
gpio/rpi_gpio.py
jamesgoodhouse/sensorReporter
925868982cb0571f2d2204f0474d8f8d714f3087
[ "Apache-2.0" ]
68
2016-05-06T18:28:34.000Z
2022-03-31T16:40:32.000Z
gpio/rpi_gpio.py
jamesgoodhouse/sensorReporter
925868982cb0571f2d2204f0474d8f8d714f3087
[ "Apache-2.0" ]
43
2016-05-28T13:22:45.000Z
2021-12-12T02:17:08.000Z
# Copyright 2020 Richard Koshak # # 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. """Contains RPI GPIO sensors, actuators, and connections. Classes: - RpiGpioSensor: Reports on the state of a GPIO Pin. - RpiGpioActuator: Sets a pin to HIGH or LOW on command. """ from time import sleep from configparser import NoOptionError import RPi.GPIO as GPIO from core.sensor import Sensor from core.actuator import Actuator from core.utils import parse_values from distutils.util import strtobool # Set to use BCM numbering. GPIO.setmode(GPIO.BCM) class RpiGpioSensor(Sensor): """Publishes the current state of a configured GPIO pin.""" def __init__(self, publishers, params): """Initializes the connection to the GPIO pin and if "EventDetection" if defined and valid, will subscibe fo events. If missing, than it requires the "Poll" parameter be defined and > 0. By default it will publish CLOSED/OPEN for 0/1 which can be overridden by the "Values" which should be a comma separated list of two paameters, the first one is CLOSED and second one is OPEN. Parameters: - "Pin": the GPIO pin in BCM numbering - "Values": Alternative values to publish for 0 and 1, defaults to CLOSED and OPEN for 0 and 1 respectively. - "PUD": Pull up or down setting, if "UP" uses PULL_UP, all other values result in PULL_DOWN. - "EventDetection": when set instead of depending on sensor_reporter to poll it will reliy on the event detection built into the GPIO library. Valid values are "RISING", "FALLING" and "BOTH". When not defined "Poll" must be set to a positive value. """ super().__init__(publishers, params) self.pin = int(params("Pin")) # Allow users to override the 0/1 pin values. self.values = parse_values(params, ["CLOSED", "OPEN"]) self.log.debug("Configured %s for CLOSED and %s for OPEN", self.values[0], self.values[1]) pud = GPIO.PUD_UP if params("PUD") == "UP" else GPIO.PUD_DOWN GPIO.setup(self.pin, GPIO.IN, pull_up_down=pud) # Set up event detection. try: event_detection = params("EventDetection") event_map = {"RISING": GPIO.RISING, "FALLING": GPIO.FALLING, "BOTH": GPIO.BOTH} if event_detection not in event_map: self.log.error("Invalid event detection specified: %s, one of RISING," " FALLING, BOTH or NONE are the only allowed values. " "Defaulting to NONE", event_detection) event_detection = "NONE" except NoOptionError: self.log.info("No event detection specified, falling back to polling") event_detection = "NONE" if event_detection != "NONE": GPIO.add_event_detect(self.pin, event_map[event_detection], callback=lambda channel: self.check_state()) self.state = GPIO.input(self.pin) self.destination = params("Destination") if self.poll < 0 and event_detection == "NONE": raise ValueError("Event detection is NONE but polling is OFF") if self.poll > 0 and event_detection != "NONE": raise ValueError("Event detection is {} but polling is {}" .format(event_detection, self.poll)) self.log.info("Configured RpiGpioSensor: pin %d on destination %s with PUD %s" " and event detection %s", self.pin, self.destination, pud, event_detection) # We've a first reading so publish it. self.publish_state() def check_state(self): """Checks the current state of the pin and if it's different from the last state publishes it. With event detection this method gets called when the GPIO pin changed states. When polling this method gets called on each poll. """ value = GPIO.input(self.pin) if value != self.state: self.log.info("Pin %s changed from %s to %s", self.pin, self.state, value) self.state = value self.publish_state() def publish_state(self): """Publishes the current state of the pin.""" msg = self.values[0] if self.state == GPIO.LOW else self.values[1] self._send(msg, self.destination) def cleanup(self): """Disconnects from the GPIO subsystem.""" GPIO.cleanup() class RpiGpioActuator(Actuator): """Allows for setting a GPIO pin to high or low on command. Also supports toggling. """ def __init__(self, connections, params): """Initializes the GPIO subsystem and sets the pin to the InitialState. If InitialState is not povided in paams it defaults to GPIO.HIGH. If "Toggle" is defined on any message will result in the pin being set to HIGH for half a second and then back to LOW. Parameters: - "Pin": The GPIO pin in BCM numbering - "InitialState": The pin state to set when coming online, defaults to "OFF". - "Toggle": Optional parameter that when set to "True" causes any message received to result in setting the pin to HIGH, sleep for half a second, then back to LOW. """ super().__init__(connections, params) self.pin = int(params("Pin")) GPIO.setup(self.pin, GPIO.OUT) out = GPIO.LOW try: self.init_state = GPIO.HIGH if params("InitialState") == "ON" else GPIO.LOW except NoOptionError: pass GPIO.output(self.pin, self.init_state) try: self.toggle = bool(strtobool(params("Toggle"))) except NoOptionError: self.toggle = False self.log.info("Configued RpoGpuiActuator: pin %d on destination %s with " "toggle %s", self.pin, self.cmd_src, self.toggle) def on_message(self, msg): """Called when the actuator receives a message. If Toggle is not enabled sets the pin to HIGH if the message is ON and LOW if the message is OFF. """ self.log.info("Received command on %s: %s Toggle = %s Pin = %d", self.cmd_src, msg, self.toggle, self.pin) # Toggle on then off. if self.toggle: self.log.info("Toggling pin %s %s to %s", self.pin, self.highlow_to_str(self.init_state), self.highlow_to_str(not self.init_state)) GPIO.output(self.pin, int(not self.init_state)) sleep(.5) self.log.info("Toggling pin %s %s to %s", self.pin, self.highlow_to_str(not self.init_state), self.highlow_to_str(self.init_state)) GPIO.output(self.pin, self.init_state) # Turn ON/OFF based on the message. else: out = None if msg == "ON": out = GPIO.HIGH elif msg == "OFF": out = GPIO.LOW if out == None: self.log.error("Bad command %s", msg) else: self.log.info("Setting pin %d to %s", self.pin, "HIGH" if out == GPIO.HIGH else "LOW") GPIO.output(self.pin, out) @staticmethod def highlow_to_str(output): """Converts (GPIO.)HIGH (=1) and LOW (=0) to the corresponding string Parameter: - "output": the GPIO constant (HIGH or LOW) Returns string HIGH/LOW """ if output: return "HIGH" else: return "LOW"
41.054455
115
0.604365
e8fb7005a2d2a061e7ae0a8a1df9004504412ed2
4,325
py
Python
python/detectionAlgorithm/offlineVideo/icub/main.py
NunoDuarte/openCVdevelop
43204a903a3c96758332a86c7d6b10c285d6ed37
[ "MIT" ]
null
null
null
python/detectionAlgorithm/offlineVideo/icub/main.py
NunoDuarte/openCVdevelop
43204a903a3c96758332a86c7d6b10c285d6ed37
[ "MIT" ]
null
null
null
python/detectionAlgorithm/offlineVideo/icub/main.py
NunoDuarte/openCVdevelop
43204a903a3c96758332a86c7d6b10c285d6ed37
[ "MIT" ]
null
null
null
# import files from findNearest import findNearest from balltracking import Ball from faceDetector import FaceDetector from gazeBehaviour import GazeBehaviour # import necessary libraries from collections import deque import numpy as np import cv2 import csv import os import argparse import imutils import logging as log dir = 'input' directory = os.fsencode(dir) for file in os.listdir(directory): filename = os.fsdecode(file) cap = cv2.VideoCapture(dir+'/'+filename+'/world_viz.mp4') length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the (optional) video file") ap.add_argument("-b", "--buffer", type=int, default=64, help="max buffer size") args = vars(ap.parse_args()) pts = deque(maxlen=args["buffer"]) ballTracking = Ball() cascPath = "cascade-icub-60v60.xml" faceCascade = cv2.CascadeClassifier(cascPath) log.basicConfig(filename='faceDetected.log', level=log.INFO) anterior = 0 face = FaceDetector() print("Preparing Data...") knownFaces, knownLabels = face.prepare_training_data("training-data", faceCascade) print("Data prepared") # create our LBPH face recognizer face_recognizer = cv2.face.LBPHFaceRecognizer_create() face_recognizer.train(knownFaces, np.array(knownLabels)) timestamps_gaze = list() norm_pos_x = list() norm_pos_y = list() gaze = GazeBehaviour() f = gaze.open(filename) with open(dir+'/'+filename+'/gaze_positions.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: timestamps_gaze.append(float(row['timestamp'])) norm_pos_x.append(row['norm_pos_x']) norm_pos_y.append(row['norm_pos_y']) print(len(timestamps_gaze)) timestamps = np.load(dir+'/'+filename+'/world_viz_timestamps.npy') print(len(timestamps)) cv2.waitKey(0) i = 0 ball = [] time0 = timestamps[i] while i < length: ret, frame = cap.read() # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if frame is not None: frame = imutils.resize(frame, width=750) height, width, channels = frame.shape frame, pts, ballG = ballTracking.trackingGreen(frame, pts) if ballG is not [] and len(ballG) != 0: ball.append([ballG, 5]) frame, pts, ballR = ballTracking.trackingRed(frame, pts) if ballR is not [] and len(ballR) != 0: ball.append([ballR, 4]) frame, pts, ballB = ballTracking.trackingBlue(frame, pts) if ballB is not [] and len(ballB) != 0: ball.append([ballB, 0]) frame, pts, ballY = ballTracking.trackingYellow(frame, pts) if ballY is not [] and len(ballY) != 0: ball.append([ballY, 3]) frame, pts, ballC = ballTracking.trackingCyan(frame, pts) if ballC is not [] and len(ballC) != 0: ball.append([ballC, 2]) anterior, faces, facesTrained = face.detecting(frame, anterior, faceCascade) labels = face.predict(frame, face_recognizer, faces, facesTrained) # calculate the nearest timestamp for the current frame time = timestamps[i] time_close, ind = findNearest(timestamps_gaze, float(time)) # use the x, y position of the closest timestamp norm_pos_* pos_x = norm_pos_x[ind] pos_y = norm_pos_y[ind] cv2.circle(frame, (int(float(pos_x)*width), int(height - int(float(pos_y)*height))), 10, (0, 255, 1), thickness=5, lineType=8, shift=0) # draw circle fixation = [(int(float(pos_x)*width)), int(height - int(float(pos_y)*height))] # check the gaze behaviour if len(ball) is not 0: gaze.record(time_close-time0, ball, faces, fixation, labels, f) cv2.imshow('frame', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break i = i + 1 # clear the lists ball = [] faces = [] # wait for key pressed cv2.waitKey(0) gaze.close(f) cap.release() cv2.destroyAllWindows()
33.789063
113
0.619422
36284889381f8cc328ad0ed9990cd406d1c3442b
1,432
py
Python
stix_shifter_modules/qradar/stix_transmission/results_connector.py
pyromaneact/stix-shifter
431c6f66513cd0db8e338a4e2952a40666bc294b
[ "Apache-2.0" ]
1
2021-10-05T19:26:04.000Z
2021-10-05T19:26:04.000Z
stix_shifter_modules/qradar/stix_transmission/results_connector.py
pyromaneact/stix-shifter
431c6f66513cd0db8e338a4e2952a40666bc294b
[ "Apache-2.0" ]
1
2020-09-08T17:26:43.000Z
2020-09-08T17:26:43.000Z
stix_shifter_modules/qradar/stix_transmission/results_connector.py
pyromaneact/stix-shifter
431c6f66513cd0db8e338a4e2952a40666bc294b
[ "Apache-2.0" ]
1
2020-11-25T13:24:25.000Z
2020-11-25T13:24:25.000Z
from stix_shifter_utils.modules.base.stix_transmission.base_results_connector import BaseResultsConnector from stix_shifter_utils.utils.error_response import ErrorResponder from stix_shifter_utils.utils import logger import json class ResultsConnector(BaseResultsConnector): def __init__(self, api_client): self.api_client = api_client self.logger = logger.set_logger(__name__) def create_results_connection(self, search_id, offset, length): min_range = offset max_range = offset + length # Grab the response, extract the response code, and convert it to readable json response = self.api_client.get_search_results(search_id, 'application/json', min_range, max_range) response_code = response.code # Construct a response object return_obj = dict() error = None response_text = response.read() try: response_dict = json.loads(response_text) except ValueError as ex: self.logger.debug(response_text) error = Exception(f'Can not parse response: {ex} : {response_text}') if 200 <= response_code <= 299: return_obj['success'] = True return_obj['data'] = response_dict.get('events', response_dict.get('flows')) else: ErrorResponder.fill_error(return_obj, response_dict, ['message'], error=error) return return_obj
37.684211
106
0.685056
dc7797baeb9b58b5b5906c389616798747d5dd43
2,587
py
Python
lib/connectivity_lib/webtest.py
seunomosowon/TA-connectivity
40244c5fb2ba7f8f32fd250fb1abf85fbfcb9114
[ "CC-BY-3.0" ]
4
2016-06-19T11:49:50.000Z
2019-10-28T09:18:42.000Z
lib/connectivity_lib/webtest.py
seunomosowon/TA-connectivity
40244c5fb2ba7f8f32fd250fb1abf85fbfcb9114
[ "CC-BY-3.0" ]
8
2016-10-21T00:22:29.000Z
2021-01-26T13:04:57.000Z
lib/connectivity_lib/webtest.py
seunomosowon/TA-connectivity
40244c5fb2ba7f8f32fd250fb1abf85fbfcb9114
[ "CC-BY-3.0" ]
4
2016-06-19T11:49:52.000Z
2019-11-14T10:10:49.000Z
""" This includes functions to be used for web connectivity tests to a given URL. Functions here support the 'webping://' modular input """ from future.standard_library import install_aliases install_aliases() import re from urllib.request import urlopen from urllib.parse import urlparse from http.client import HTTPException import urllib.error from time import strftime from string import Template """ Still need to capture traceback and log to debug? import traceback """ logmessage = Template( '$timenow,action=$action,status=$status_code,src=splunk,dst=$dsthost,url=\"$dsturl\",description=$description') def webtest(url, webtimeout): """ This tests connectivity to a webservice running at a given URL. :param url: Application URL to be tested. :type url: basestring :param webtimeout: application web timeout to be used for the test. :type webtimeout: int :return: Raises an exception or returns a status message about the connection tested :rtype: basestring """ timenow = strftime("%m/%d/%Y %H:%M:%S %Z") dst = urlparse(url).netloc.split(':')[0] # raise exception if url is not in format required or return as unsuccessful action = '' description = '' try: openurl = urlopen(url, timeout=webtimeout) status_code = openurl.getcode() if re.match('(2\d\d)', repr(status_code)): if re.match('(2\d\d)', repr(status_code)): action = 'successful' description = 'online' elif re.match('(3\d\d)', repr(status_code)): action = 'redirected' # These falls under urllib2.HTTPError description = 'redirected' elif re.match('(4\d\d)', repr(status_code)): action = 'unsuccessful' description = 'Malformed URL' elif re.match('(5\d\d)', repr(status_code)): action = 'unsuccessful' description = 'Server Error' else: action = 'unknown' description = 'unknown' except urllib.error.HTTPError as e: action = 'HTTPERROR' description = 'HTTPError - ' + repr(e. code) status_code = e.code except urllib.error.URLError as e: action = 'URLERROR' description = 'URLError - ' + str(e.reason) status_code = 999 except HTTPException: action = 'PROGRAM_ERROR' description = 'HTTPException' status_code = 999 return logmessage.substitute( timenow=timenow, action=action, status_code=status_code, dsthost=dst, dsturl=url, description=description)
34.959459
115
0.649787
bcbfecc2340425dec4314675c221abe592f227d4
416
py
Python
climatetalk/node_types/heat_pump.py
kdschlosser/ClimateTalk
3b09a45c295cf5228283d7095834e8f133ed7de3
[ "MIT" ]
3
2021-04-30T20:12:16.000Z
2022-03-09T11:53:12.000Z
climatetalk/node_types/heat_pump.py
kdschlosser/ClimateTalk
3b09a45c295cf5228283d7095834e8f133ed7de3
[ "MIT" ]
null
null
null
climatetalk/node_types/heat_pump.py
kdschlosser/ClimateTalk
3b09a45c295cf5228283d7095834e8f133ed7de3
[ "MIT" ]
2
2021-04-08T18:29:39.000Z
2021-04-30T20:13:55.000Z
# -*- coding: utf-8 -*- # Copyright 2020 Kevin Schlosser from . import NodeType, Node from ..mdi import heat_pump, sensors NODE_TYPE_HEAT_PUMP = NodeType(0x05).set_desc('Heat Pump') class HeatPump(Node, heat_pump.HeatPumpMDI): node_type = NODE_TYPE_HEAT_PUMP @property def outdoor_temperature(self): return sensors.HeatPumpOutdoorTempSensorMDI(self.address, self.subnet, self.network).value
26
98
0.75
b7b3f9bfa55dc232277365cb410826e8324ace9f
1,679
py
Python
practice/practice_1.2/linked_list.py
Electro98/aads
89607910856600b38349c31665f43fbb33df71c5
[ "MIT" ]
7
2021-07-24T05:37:07.000Z
2022-03-15T05:17:25.000Z
practice/practice_1.2/linked_list.py
Electro98/aads
89607910856600b38349c31665f43fbb33df71c5
[ "MIT" ]
2
2021-08-05T14:09:46.000Z
2021-08-21T14:12:03.000Z
practice/practice_1.2/linked_list.py
Electro98/aads
89607910856600b38349c31665f43fbb33df71c5
[ "MIT" ]
8
2021-08-20T17:17:02.000Z
2022-03-15T05:17:27.000Z
"""Модуль "заглушка" для тестов""" class LinkedListItem: """Узел связного списка""" def __init__(self, data=None): raise NotImplementedError() @property def next_item(self): """Следующий элемент""" raise NotImplementedError() @next_item.setter def next_item(self, value): raise NotImplementedError() @property def previous_item(self): """Предыдущий элемент""" raise NotImplementedError() @previous_item.setter def previous_item(self, value): raise NotImplementedError() def __repr__(self): raise NotImplementedError() class LinkedList: """Связный список""" def __init__(self, first_item=None): raise NotImplementedError() @property def last(self): """Последний элемент""" raise NotImplementedError() def append_left(self, item): """Добавление слева""" raise NotImplementedError() def append_right(self, item): """Добавление справа""" raise NotImplementedError() def append(self, item): """Добавление справа""" raise NotImplementedError() def remove(self, item): """Удаление""" raise NotImplementedError() def insert(self, previous, item): """Вставка справа""" raise NotImplementedError() def __len__(self): raise NotImplementedError() def __iter__(self): raise NotImplementedError() def __getitem__(self, index): raise NotImplementedError() def __contains__(self, item): raise NotImplementedError() def __reversed__(self): raise NotImplementedError()
22.386667
40
0.627159
59f759770b4107eae796f4c5bd72a5a4e517dcd0
22,644
py
Python
knowledge_repo/app/models.py
dmaljovec/knowledge-repo
09e1e9e63fa86817db00341bb589a27bd35c5199
[ "Apache-2.0" ]
null
null
null
knowledge_repo/app/models.py
dmaljovec/knowledge-repo
09e1e9e63fa86817db00341bb589a27bd35c5199
[ "Apache-2.0" ]
1
2020-10-26T22:38:18.000Z
2020-10-26T22:38:18.000Z
knowledge_repo/app/models.py
recursionpharma/knowledge-repo-package
09e1e9e63fa86817db00341bb589a27bd35c5199
[ "Apache-2.0" ]
null
null
null
import os import sys import datetime import logging import traceback from flask import current_app, request from flask_login import UserMixin from flask_sqlalchemy import SQLAlchemy from collections import defaultdict from sqlalchemy import func, distinct, and_, select, Index, UniqueConstraint from knowledge_repo._version import __version__ from knowledge_repo.repository import KnowledgeRepository from knowledge_repo.utils.types import MediumText from .proxies import current_user, current_repo, db_session from .utils.models import unique_constructor from .utils.search import get_keywords from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.ext.orderinglist import ordering_list from sqlalchemy.ext.associationproxy import association_proxy logger = logging.getLogger(__name__) db = SQLAlchemy() class IndexMetadata(db.Model): __tablename__ = 'index_metadata' id = db.Column(db.Integer, nullable=False, primary_key=True) type = db.Column(db.String(255), nullable=False) name = db.Column(db.String(512), nullable=False) value = db.Column(db.String(512), nullable=True) updated_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow) @classmethod def get(cls, type, name, default=None): m = db_session.query(IndexMetadata).filter(IndexMetadata.type == type).filter(IndexMetadata.name == name).first() if m is not None: return m.value return default @classmethod def set(cls, type, name, value): m = db_session.query(IndexMetadata).filter(IndexMetadata.type == type).filter(IndexMetadata.name == name).first() if m is not None: m.value = value m.updated_at = datetime.datetime.utcnow() else: m = IndexMetadata(type=type, name=name, value=value, updated_at=datetime.datetime.utcnow()) db_session.add(m) @classmethod def get_last_update(cls, type, name): m = db_session.query(IndexMetadata).filter(IndexMetadata.type == type).filter(IndexMetadata.name == name).first() if m is not None: return m.updated_at return None class PostAuthorAssoc(db.Model): __tablename__ = 'assoc_post_author' post_id = db.Column(db.Integer, db.ForeignKey("posts.id"), nullable=False, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, primary_key=True) order = db.Column(db.Integer) post = db.relationship('Post', lazy='joined') author = db.relationship('User', lazy='joined') assoc_post_tag = db.Table( 'assoc_post_tag', db.Model.metadata, db.Column('post_id', db.Integer, db.ForeignKey('posts.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tags.id')) ) assoc_post_group = db.Table( 'assoc_post_group', db.Model.metadata, db.Column('post_id', db.Integer, db.ForeignKey('posts.id')), db.Column('group_id', db.Integer, db.ForeignKey('groups.id')) ) assoc_group_user = db.Table( 'assoc_group_user', db.Model.metadata, db.Column('group_id', db.Integer, db.ForeignKey('groups.id')), db.Column('user_id', db.Integer, db.ForeignKey('users.id')) ) class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) post_id = db.Column(db.Integer) text = db.Column(db.Text) type = db.Column(db.String(100), default='post') created_at = db.Column(db.DateTime, default=func.now()) updated_at = db.Column(db.DateTime, default=func.now(), onupdate=func.now()) class ErrorLog(db.Model): __tablename__ = 'errorlog' id = db.Column(db.Integer, primary_key=True) function = db.Column(db.String(100)) location = db.Column(db.String(255)) message = db.Column(db.Text()) traceback = db.Column(db.Text()) version = db.Column(db.String(100), default=__version__) created_at = db.Column(db.DateTime, default=func.now()) @classmethod def from_exception(cls, e): tb = sys.exc_info()[-1] filename, linenumber, function, code = traceback.extract_tb(sys.exc_info()[-1])[-1] filename = os.path.relpath(filename, os.path.join(os.path.dirname(__file__), '..')) return ErrorLog( function=function, location='{}:{}'.format(filename, linenumber), message='{}: {}'.format(e.__class__.__name__, "; ".join(str(a) for a in e.args)), traceback="\n".join(traceback.format_tb(tb)) ) @classmethod def logged(cls, function): def wrapped(*args, **kwargs): try: return function(*args, **kwargs) except Exception as e: db_session.rollback() db_session.add(ErrorLog.from_exception(e)) db_session.commit() tb = sys.exc_info()[-1] raise e.with_traceback(tb) return wrapped class PageView(db.Model): __tablename__ = 'pageviews' id = db.Column(db.Integer, primary_key=True) id_errorlog = db.Column(db.Integer) page = db.Column(db.String(512)) endpoint = db.Column(db.String(255)) user_id = db.Column(db.Integer) object_id = db.Column(db.Integer) object_type = db.Column(db.String(100)) object_action = db.Column(db.String(100)) ip_address = db.Column(db.String(64)) created_at = db.Column(db.DateTime, default=func.now()) version = db.Column(db.String(100), default=__version__) __table_args__ = (Index("object_id_type_action_index", object_id, object_type, object_action),) class logged(object): def __init__(self, route, object_extractor=None): self._route = route self._object_extractor = object_extractor def __getattr__(self, attr): return getattr(self._route, attr) def __call__(self, *args, **kwargs): if not current_app.config.get('INDEXING_ENABLED', True): return self._route(*args, **kwargs) log = PageView( page=request.full_path, endpoint=request.endpoint, user_id=current_user.id, ip_address=request.remote_addr, version=__version__ ) errorlog = None log.object_id, log.object_type, log.object_action, reextract_after_request = self.extract_objects(*args, **kwargs) db_session.add(log) # Add log here to ensure pageviews are accurate try: return self._route(*args, **kwargs) except Exception as e: db_session.rollback() # Ensure no lingering database changes remain after crashed route db_session.add(log) errorlog = ErrorLog.from_exception(e) db_session.add(errorlog) db_session.commit() tb = sys.exc_info()[-1] raise e.with_traceback(tb) finally: # Extract object id and type after response generated (if requested) to ensure # most recent data is collected if reextract_after_request: log.object_id, log.object_type, log.object_action, _ = self.extract_objects(*args, **kwargs) if errorlog is not None: log.id_errorlog = errorlog.id db_session.add(log) db_session.commit() def object_extractor(self, extractor): self._object_extractor = extractor return self def extract_objects(self, *args, **kwargs): if self._object_extractor is None: return None, None, None, False try: object_info = self._object_extractor(*args, **kwargs) except Exception as e: logger.warning("Error using object extractor: " + str(e)) object_info = {'id': (-1), 'type': None} assert isinstance(object_info, dict), "Object extractors must return a dictionary." assert len(set(['id', 'type']).difference(object_info.keys())) == 0 and len(set(object_info.keys()).difference(['id', 'type', 'action', 'may_change'])) == 0, "Object extractors must at least include the keys 'id' and 'type', and optionally 'action' and 'may_change'. Was provided with: {}".format(str(list(object_info.keys()))) object_info = defaultdict(lambda: None, object_info) return object_info['id'], object_info['type'], object_info['action'], object_info['may_change'] or False class Vote(db.Model): __tablename__ = 'votes' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) object_id = db.Column(db.Integer) object_type = db.Column(db.String(100), default='post') created_at = db.Column(db.DateTime, default=func.now()) updated_at = db.Column(db.DateTime, default=func.now(), onupdate=func.now()) @unique_constructor( lambda identifier: identifier, lambda query, identifier: query.filter(User.identifier == identifier) ) class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=func.now()) identifier = db.Column(db.String(500)) # Unique identifier across all login methods username = db.Column(db.String(500)) # Username used to log in (may differ from identifier) password = db.Column(db.String(500)) # Password for local logins name = db.Column(db.String(500)) # Name as determined by auth method preferred_name = db.Column(db.String(500)) # Name as determined by user preferences email = db.Column(db.String(500)) # Email address avatar_uri = db.Column(db.Text()) # Either external url or data uri active = db.Column(db.Boolean, default=True) last_login_at = db.Column(db.DateTime) # Date of last login _posts_assoc = db.relationship("PostAuthorAssoc") posts = association_proxy('_posts_assoc', 'post') # This property should not directly modified # Method overrides for the UserMixin class for flask_login @property def is_active(self): return self.active @property def is_authenticated(self): return True @property def is_anonymous(self): return False def get_id(self): return self.identifier can_logout = True # Other useful methods @property def format_name(self): return self.preferred_name or self.name or self.identifier @property def subscriptions(self): # TODO: make attribute style naming """Get the subscriptions associated with a user. Return an array of strings of tag_names """ subscriptions = (db.session.query(Subscription) .filter(Subscription.user_id == self.id) .all()) out_subscriptions = [] for s in subscriptions: if s.object_type == 'tag': tag_obj = (db.session.query(Tag) .filter(Tag.id == s.object_id) .first()) if tag_obj: full_name = tag_obj.name out_subscriptions.append(full_name) else: db.session.delete(s) return out_subscriptions @property def liked_posts(self): """ :return: Posts that a user has liked :rtype: list """ votes = (db.session.query(Vote) .filter(Vote.user_id == self.id) .all()) post_ids = [vote.object_id for vote in votes] if len(post_ids) == 0: return [] excluded_tags = current_app.config.get('EXCLUDED_TAGS', []) posts = (db.session.query(Post) .filter(Post.id.in_(post_ids)) .filter(~Post.tags.any(Tag.name.in_(excluded_tags))) .all()) return posts @unique_constructor( lambda name: name, lambda query, name: query.filter(Tag.name == name) ) class Tag(db.Model): __tablename__ = 'tags' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(500)) _description = db.Column('description', db.Text()) created_at = db.Column(db.DateTime, default=func.now()) @hybrid_property def description(self): if self._description: return self._description return "All posts with tag '{}'.".format(self.name) @description.expression def description(self): raise NotImplementedError class Subscription(db.Model): __tablename__ = 'subscriptions' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) object_id = db.Column(db.Integer) object_type = db.Column(db.String(100)) # Currently just tag created_at = db.Column(db.DateTime, default=func.now()) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.String(100), unique=True) path = db.Column(db.String(512)) project = db.Column(db.String(512), nullable=True) # DEPRECATED repository = db.Column(db.String(512)) revision = db.Column(db.Integer()) title = db.Column(db.Text()) subtitle = db.Column(db.Text()) tldr = db.Column(db.Text) keywords = db.Column(db.Text) thumbnail = db.Column(db.Text()) private = db.Column(db.Integer()) created_at = db.Column(db.DateTime, default=func.now()) updated_at = db.Column(db.DateTime, default=func.now()) _authors_assoc = db.relationship("PostAuthorAssoc", order_by='PostAuthorAssoc.order', collection_class=ordering_list('order'), cascade="all, delete-orphan") _authors = association_proxy('_authors_assoc', 'author', creator=lambda author: PostAuthorAssoc(author=author),) @hybrid_property def authors(self): return self._authors @authors.setter def authors(self, authors): """ Sets the tags of the post to the tags given in comma delimited string form in tags_string """ user_objs = [] for author in authors: if not isinstance(author, User): author = author.strip() author = User(identifier=author) user_objs.append(author) self._authors = user_objs @hybrid_property def authors_string(self): return ', '.join([author.format_name for author in self.authors]) @authors_string.expression def authors_string(self): raise NotImplementedError _tags = db.relationship("Tag", secondary=assoc_post_tag, backref='posts', lazy='subquery') @hybrid_property def tags(self): return self._tags @tags.setter def tags(self, tags): """ Sets the tags of the post to the tags given in comma delimited string form in tags_string """ tag_objs = [] for tag in tags: if not isinstance(tag, Tag): tag = tag.strip() if tag[0] == "#": tag = tag[1:] tag = Tag(name=tag) tag_objs.append(tag) self._tags = tag_objs @property def contains_excluded_tag(self): excluded_tags = current_app.config.get('EXCLUDED_TAGS', []) return any([tag.name in excluded_tags for tag in self.tags]) _groups = db.relationship("Group", secondary=assoc_post_group, backref='posts', lazy='subquery') @hybrid_property def groups(self): return self._groups @groups.setter def groups(self, groups): # given a list of group_names, we add it. group_objs = [] for group in groups: if not isinstance(group, Group): group = Group(name=group.strip()) group_objs.append(group) # create an implicit group, group_post.id, to add # single users to group = Group(name=":post_group_" + str(self.id)) # this created group should have the author associated with it # so they can add people to the post group.users = self.authors group_objs.append(group) self._groups = group_objs _status = db.Column('status', db.Integer(), default=0) @hybrid_property def status(self): return current_repo.PostStatus(self._status or 0) @status.expression def status(self): return func.coalesce(self._status, 0) @status.setter def status(self, status): if status is None: self._status = None else: assert isinstance(status, KnowledgeRepository.PostStatus), "Status must be an instance of KnowledgeRepository.PostStatus.Status or None" self._status = status.value @hybrid_property def is_published(self): return self.status == current_repo.PostStatus.PUBLISHED @is_published.expression def is_published(self): return func.coalesce(self._status, 0) == current_repo.PostStatus.PUBLISHED.value _views = db.relationship("PageView", lazy='dynamic', primaryjoin="and_(foreign(PageView.object_id)==Post.id, " "PageView.object_type=='post'," "PageView.object_action=='view')") @hybrid_property def views(self): return self._views.all() @hybrid_property def view_count(self): return self._views.count() @view_count.expression def view_count(self): return (select([func.count(PageView.id)]) .where(PageView.object_id == self.id) .where(PageView.object_type == 'post') .label("view_count")) @hybrid_property def view_user_count(self): return (db.session.query(func.count(distinct(PageView.user_id))) .filter(PageView.object_id == self.id) .filter(PageView.object_type == 'post') .scalar()) @view_user_count.expression def view_user_count(self): return (select([func.count(distinct(PageView.user_id))]) .where(PageView.object_id == self.id) .where(PageView.object_type == 'post') .label("view_user_count")) _votes = db.relationship("Vote", lazy='dynamic', primaryjoin="and_(foreign(Vote.object_id)==Post.id, " "Vote.object_type=='post')") @hybrid_property def votes(self): return self._votes.all() @hybrid_property def vote_count(self): """ Given the path of a post, return the total likes """ return self._votes.count() @vote_count.expression def vote_count(self): return (select([func.count(Vote.id)]) .where(Vote.object_id == self.id) .where(Vote.object_type == 'post') .label("vote_count")) def vote_counted_for_user(self, user_id): return (db_session.query(Vote) .filter(and_(Vote.object_id == self.id, Vote.object_type == 'post', Vote.user_id == user_id)) .first()) is not None _comments = db.relationship("Comment", lazy="dynamic", primaryjoin="and_(foreign(Comment.post_id)==Post.id, " "Comment.type=='post')") @hybrid_property def comments(self): return self._comments.all() @hybrid_property def comment_count(self): """ Given the path of the a post, return the total comments """ return self._comments.count() @comment_count.expression def comment_count(self): return (select([func.count(Comment.id)]) .where(Comment.post_id == self.id) .where(Comment.object_type == 'post') .label("comments_count")) @property def kp(self): return current_repo.post(self.path) @property def text(self): return self.kp.read() def update_metadata_from_kp(self, kp): """ :param kp: Maps fields of the model to values :type kp: KnowledgePost :param kp: Maps fields of the model to values :type kr: KnowledgeRepository :return: None :rtype: None """ headers = kp.headers self.uuid = kp.uuid self.path = kp.path self.project = headers.get('project') self.repository = kp.repository_uri self.revision = kp.revision self.title = headers['title'] self.subtitle = headers.get('subtitle') self.tldr = headers['tldr'] self.authors = headers.get('authors', []) self.tags = headers.get('tags', []) self.keywords = get_keywords(self) self.thumbnail = kp.thumbnail_uri self.created_at = headers['created_at'] self.updated_at = headers['updated_at'] if self.created_at > self.updated_at: self.updated_at = self.created_at self.status = kp.status self.private = 0 # we do this check so that no header (None) and False are treated the same if headers.get('private', ''): self.private = 1 self.groups = headers.get('allowed_groups', []) class Email(db.Model): __tablename__ = 'emails' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) trigger_id = db.Column(db.Integer) trigger_type = db.Column(db.String(100)) object_id = db.Column(db.Integer) object_type = db.Column(db.String(100)) sent_at = db.Column(db.DateTime, default=func.now()) subject = db.Column(db.Text) text = db.Column(MediumText()) @unique_constructor( lambda name: name, lambda query, name: query.filter(Group.name == name) ) class Group(db.Model): __tablename__ = 'groups' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), unique=True) _users = db.relationship("User", secondary=assoc_group_user, backref='users', lazy='subquery') @hybrid_property def users(self): return self._users @users.setter def users(self, user_objs): self._users = self._users + user_objs
34.257186
339
0.615527
1f607c43cf8c38fb9a212cd579cb479db8ef6421
1,507
py
Python
Yuanjunling1/Hello word/TestFlask.py
yuanjunling/PycharmProjects
087b1a30818bbe2bf3972c9340f61ca4b792eb7d
[ "bzip2-1.0.6" ]
null
null
null
Yuanjunling1/Hello word/TestFlask.py
yuanjunling/PycharmProjects
087b1a30818bbe2bf3972c9340f61ca4b792eb7d
[ "bzip2-1.0.6" ]
null
null
null
Yuanjunling1/Hello word/TestFlask.py
yuanjunling/PycharmProjects
087b1a30818bbe2bf3972c9340f61ca4b792eb7d
[ "bzip2-1.0.6" ]
null
null
null
# -*- coding:utf-8 -*- import time import calendar list1 = ['python','java','php','C++','C#'] list2 = ['jjj','ppp','lll','ddd'] print "list1[1]:",list1[1] print list1+list2 list2.append('append') print list2 del list2[3] print list2*4 print len(list2) list2.reverse() print list2 tikce = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print "当前时间戳:", tikce cal = calendar.month(2018,6) print "以下输出2018年6月份的日历:" print cal #自定义函数 def printme(str): "打印任何传入的字符串" print str; return ; #调用函数 printme("哈哈哈哈哈哈哈哈哈"); printme("我在调用一次啊"); #可写函数说明 def changeme(mylist): "修改传入的列表" mylist.append([1,2,3]); print "函数获取值:",mylist return #调用changeme函数 mylist = [10,20,30]; changeme(mylist); print "函数外取值: ", mylist #可写函数说明 def printer(sta): print sta; return printer(11111) def printinfo(name,age): "打印任何传入的字符串" print "Name:",name; print "Age",age; return ; #调用printinfo函数 printinfo(name="jun",age=222) def functionname( arg1, *vartuple ): "打印任何传入的参数" print "输出: " print arg1 for var in vartuple: print var return; # 调用printinfo 函数 functionname(10) functionname(10,20,30,40,50); # 可写函数说明 sum = lambda arg1,arg2:arg1 + arg2; # 调用sum函数 print "相加后的值为 : ", sum( 10, 20 ) print "相加后的值为 : ", sum( 20, 20 ) str1 = raw_input("请输入:") print "你输入的内容是: ", str1 str2 = input("请输入:") print "你输入的内容是:",str2; fo = open("D:\\foo.txt","w") print "文件名: ", fo.name print "是否已关闭 : ", fo.closed print "访问模式 : ", fo.mode print "末尾是否强制加空格 : ", fo.softspace
18.8375
60
0.64499
6d18ffe529cad2b614b18b91cb34896d29ec85d8
99,921
py
Python
tests/core.py
antoncohen/incubator-airflow
71954a52fc13accf1130d3d2a00263d7ec369b02
[ "Apache-2.0" ]
null
null
null
tests/core.py
antoncohen/incubator-airflow
71954a52fc13accf1130d3d2a00263d7ec369b02
[ "Apache-2.0" ]
null
null
null
tests/core.py
antoncohen/incubator-airflow
71954a52fc13accf1130d3d2a00263d7ec369b02
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import print_function import json import unittest import bleach import doctest import mock import multiprocessing import os import re import signal import sqlalchemy import subprocess import tempfile import warnings from datetime import timedelta from dateutil.relativedelta import relativedelta from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from freezegun import freeze_time from numpy.testing import assert_array_almost_equal from six.moves.urllib.parse import urlencode from time import sleep from airflow import configuration from airflow.executors import SequentialExecutor from airflow.models import Variable configuration.conf.load_test_config() from airflow import jobs, models, DAG, utils, macros, settings, exceptions from airflow.models import BaseOperator from airflow.operators.bash_operator import BashOperator from airflow.operators.check_operator import CheckOperator, ValueCheckOperator from airflow.operators.dagrun_operator import TriggerDagRunOperator from airflow.operators.python_operator import PythonOperator from airflow.operators.dummy_operator import DummyOperator from airflow.hooks.base_hook import BaseHook from airflow.hooks.sqlite_hook import SqliteHook from airflow.bin import cli from airflow.www import app as application from airflow.settings import Session from airflow.utils import timezone from airflow.utils.timezone import datetime from airflow.utils.state import State from airflow.utils.dates import infer_time_unit, round_time, scale_time_units from lxml import html from airflow.exceptions import AirflowException from airflow.configuration import AirflowConfigException, run_command from jinja2.sandbox import SecurityError from jinja2 import UndefinedError import six NUM_EXAMPLE_DAGS = 20 DEV_NULL = '/dev/null' TEST_DAG_FOLDER = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'dags') DEFAULT_DATE = datetime(2015, 1, 1) DEFAULT_DATE_ISO = DEFAULT_DATE.isoformat() DEFAULT_DATE_DS = DEFAULT_DATE_ISO[:10] TEST_DAG_ID = 'unit_tests' try: import cPickle as pickle except ImportError: # Python 3 import pickle def reset(dag_id=TEST_DAG_ID): session = Session() tis = session.query(models.TaskInstance).filter_by(dag_id=dag_id) tis.delete() session.commit() session.close() reset() class OperatorSubclass(BaseOperator): """ An operator to test template substitution """ template_fields = ['some_templated_field'] def __init__(self, some_templated_field, *args, **kwargs): super(OperatorSubclass, self).__init__(*args, **kwargs) self.some_templated_field = some_templated_field def execute(*args, **kwargs): pass class CoreTest(unittest.TestCase): default_scheduler_args = {"num_runs": 1} def setUp(self): configuration.conf.load_test_config() self.dagbag = models.DagBag( dag_folder=DEV_NULL, include_examples=True) self.args = {'owner': 'airflow', 'start_date': DEFAULT_DATE} self.dag = DAG(TEST_DAG_ID, default_args=self.args) self.dag_bash = self.dagbag.dags['example_bash_operator'] self.runme_0 = self.dag_bash.get_task('runme_0') self.run_after_loop = self.dag_bash.get_task('run_after_loop') self.run_this_last = self.dag_bash.get_task('run_this_last') def test_schedule_dag_no_previous_runs(self): """ Tests scheduling a dag with no previous runs """ dag = DAG(TEST_DAG_ID + 'test_schedule_dag_no_previous_runs') dag.add_task(models.BaseOperator( task_id="faketastic", owner='Also fake', start_date=datetime(2015, 1, 2, 0, 0))) dag_run = jobs.SchedulerJob(**self.default_scheduler_args).create_dag_run(dag) self.assertIsNotNone(dag_run) self.assertEqual(dag.dag_id, dag_run.dag_id) self.assertIsNotNone(dag_run.run_id) self.assertNotEqual('', dag_run.run_id) self.assertEqual( datetime(2015, 1, 2, 0, 0), dag_run.execution_date, msg='dag_run.execution_date did not match expectation: {0}' .format(dag_run.execution_date) ) self.assertEqual(State.RUNNING, dag_run.state) self.assertFalse(dag_run.external_trigger) dag.clear() def test_schedule_dag_fake_scheduled_previous(self): """ Test scheduling a dag where there is a prior DagRun which has the same run_id as the next run should have """ delta = timedelta(hours=1) dag = DAG(TEST_DAG_ID + 'test_schedule_dag_fake_scheduled_previous', schedule_interval=delta, start_date=DEFAULT_DATE) dag.add_task(models.BaseOperator( task_id="faketastic", owner='Also fake', start_date=DEFAULT_DATE)) scheduler = jobs.SchedulerJob(**self.default_scheduler_args) dag.create_dagrun(run_id=models.DagRun.id_for_date(DEFAULT_DATE), execution_date=DEFAULT_DATE, state=State.SUCCESS, external_trigger=True) dag_run = scheduler.create_dag_run(dag) self.assertIsNotNone(dag_run) self.assertEqual(dag.dag_id, dag_run.dag_id) self.assertIsNotNone(dag_run.run_id) self.assertNotEqual('', dag_run.run_id) self.assertEqual( DEFAULT_DATE + delta, dag_run.execution_date, msg='dag_run.execution_date did not match expectation: {0}' .format(dag_run.execution_date) ) self.assertEqual(State.RUNNING, dag_run.state) self.assertFalse(dag_run.external_trigger) def test_schedule_dag_once(self): """ Tests scheduling a dag scheduled for @once - should be scheduled the first time it is called, and not scheduled the second. """ dag = DAG(TEST_DAG_ID + 'test_schedule_dag_once') dag.schedule_interval = '@once' dag.add_task(models.BaseOperator( task_id="faketastic", owner='Also fake', start_date=datetime(2015, 1, 2, 0, 0))) dag_run = jobs.SchedulerJob(**self.default_scheduler_args).create_dag_run(dag) dag_run2 = jobs.SchedulerJob(**self.default_scheduler_args).create_dag_run(dag) self.assertIsNotNone(dag_run) self.assertIsNone(dag_run2) dag.clear() def test_fractional_seconds(self): """ Tests if fractional seconds are stored in the database """ dag = DAG(TEST_DAG_ID + 'test_fractional_seconds') dag.schedule_interval = '@once' dag.add_task(models.BaseOperator( task_id="faketastic", owner='Also fake', start_date=datetime(2015, 1, 2, 0, 0))) start_date = timezone.utcnow() run = dag.create_dagrun( run_id='test_' + start_date.isoformat(), execution_date=start_date, start_date=start_date, state=State.RUNNING, external_trigger=False ) run.refresh_from_db() self.assertEqual(start_date, run.execution_date, "dag run execution_date loses precision") self.assertEqual(start_date, run.start_date, "dag run start_date loses precision ") def test_schedule_dag_start_end_dates(self): """ Tests that an attempt to schedule a task after the Dag's end_date does not succeed. """ delta = timedelta(hours=1) runs = 3 start_date = DEFAULT_DATE end_date = start_date + (runs - 1) * delta dag = DAG(TEST_DAG_ID + 'test_schedule_dag_start_end_dates', start_date=start_date, end_date=end_date, schedule_interval=delta) dag.add_task(models.BaseOperator(task_id='faketastic', owner='Also fake')) # Create and schedule the dag runs dag_runs = [] scheduler = jobs.SchedulerJob(**self.default_scheduler_args) for i in range(runs): dag_runs.append(scheduler.create_dag_run(dag)) additional_dag_run = scheduler.create_dag_run(dag) for dag_run in dag_runs: self.assertIsNotNone(dag_run) self.assertIsNone(additional_dag_run) @freeze_time('2016-01-01') def test_schedule_dag_no_end_date_up_to_today_only(self): """ Tests that a Dag created without an end_date can only be scheduled up to and including the current datetime. For example, if today is 2016-01-01 and we are scheduling from a start_date of 2015-01-01, only jobs up to, but not including 2016-01-01 should be scheduled. """ session = settings.Session() delta = timedelta(days=1) start_date = DEFAULT_DATE runs = 365 dag = DAG(TEST_DAG_ID + 'test_schedule_dag_no_end_date_up_to_today_only', start_date=start_date, schedule_interval=delta) dag.add_task(models.BaseOperator(task_id='faketastic', owner='Also fake')) dag_runs = [] scheduler = jobs.SchedulerJob(**self.default_scheduler_args) for i in range(runs): dag_run = scheduler.create_dag_run(dag) dag_runs.append(dag_run) # Mark the DagRun as complete dag_run.state = State.SUCCESS session.merge(dag_run) session.commit() # Attempt to schedule an additional dag run (for 2016-01-01) additional_dag_run = scheduler.create_dag_run(dag) for dag_run in dag_runs: self.assertIsNotNone(dag_run) self.assertIsNone(additional_dag_run) def test_confirm_unittest_mod(self): self.assertTrue(configuration.conf.get('core', 'unit_test_mode')) def test_pickling(self): dp = self.dag.pickle() self.assertEqual(dp.pickle.dag_id, self.dag.dag_id) def test_rich_comparison_ops(self): class DAGsubclass(DAG): pass dag_eq = DAG(TEST_DAG_ID, default_args=self.args) dag_diff_load_time = DAG(TEST_DAG_ID, default_args=self.args) dag_diff_name = DAG(TEST_DAG_ID + '_neq', default_args=self.args) dag_subclass = DAGsubclass(TEST_DAG_ID, default_args=self.args) dag_subclass_diff_name = DAGsubclass( TEST_DAG_ID + '2', default_args=self.args) for d in [dag_eq, dag_diff_name, dag_subclass, dag_subclass_diff_name]: d.last_loaded = self.dag.last_loaded # test identity equality self.assertEqual(self.dag, self.dag) # test dag (in)equality based on _comps self.assertEqual(dag_eq, self.dag) self.assertNotEqual(dag_diff_name, self.dag) self.assertNotEqual(dag_diff_load_time, self.dag) # test dag inequality based on type even if _comps happen to match self.assertNotEqual(dag_subclass, self.dag) # a dag should equal an unpickled version of itself d = pickle.dumps(self.dag) self.assertEqual(pickle.loads(d), self.dag) # dags are ordered based on dag_id no matter what the type is self.assertLess(self.dag, dag_diff_name) self.assertGreater(self.dag, dag_diff_load_time) self.assertLess(self.dag, dag_subclass_diff_name) # greater than should have been created automatically by functools self.assertGreater(dag_diff_name, self.dag) # hashes are non-random and match equality self.assertEqual(hash(self.dag), hash(self.dag)) self.assertEqual(hash(dag_eq), hash(self.dag)) self.assertNotEqual(hash(dag_diff_name), hash(self.dag)) self.assertNotEqual(hash(dag_subclass), hash(self.dag)) def test_check_operators(self): conn_id = "sqlite_default" captainHook = BaseHook.get_hook(conn_id=conn_id) captainHook.run("CREATE TABLE operator_test_table (a, b)") captainHook.run("insert into operator_test_table values (1,2)") t = CheckOperator( task_id='check', sql="select count(*) from operator_test_table", conn_id=conn_id, dag=self.dag) t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) t = ValueCheckOperator( task_id='value_check', pass_value=95, tolerance=0.1, conn_id=conn_id, sql="SELECT 100", dag=self.dag) t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) captainHook.run("drop table operator_test_table") def test_clear_api(self): task = self.dag_bash.tasks[0] task.clear( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, upstream=True, downstream=True) ti = models.TaskInstance(task=task, execution_date=DEFAULT_DATE) ti.are_dependents_done() def test_illegal_args(self): """ Tests that Operators reject illegal arguments """ with warnings.catch_warnings(record=True) as w: t = BashOperator( task_id='test_illegal_args', bash_command='echo success', dag=self.dag, illegal_argument_1234='hello?') self.assertTrue( issubclass(w[0].category, PendingDeprecationWarning)) self.assertIn( 'Invalid arguments were passed to BashOperator.', w[0].message.args[0]) def test_bash_operator(self): t = BashOperator( task_id='test_bash_operator', bash_command="echo success", dag=self.dag) t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_bash_operator_multi_byte_output(self): t = BashOperator( task_id='test_multi_byte_bash_operator', bash_command=u"echo \u2600", dag=self.dag, output_encoding='utf-8') t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_bash_operator_kill(self): import psutil sleep_time = "100%d" % os.getpid() t = BashOperator( task_id='test_bash_operator_kill', execution_timeout=timedelta(seconds=1), bash_command="/bin/bash -c 'sleep %s'" % sleep_time, dag=self.dag) self.assertRaises( exceptions.AirflowTaskTimeout, t.run, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) sleep(2) pid = -1 for proc in psutil.process_iter(): if proc.cmdline() == ['sleep', sleep_time]: pid = proc.pid if pid != -1: os.kill(pid, signal.SIGTERM) self.fail("BashOperator's subprocess still running after stopping on timeout!") def test_trigger_dagrun(self): def trigga(context, obj): if True: return obj t = TriggerDagRunOperator( task_id='test_trigger_dagrun', trigger_dag_id='example_bash_operator', python_callable=trigga, dag=self.dag) t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_dryrun(self): t = BashOperator( task_id='test_dryrun', bash_command="echo success", dag=self.dag) t.dry_run() def test_sqlite(self): import airflow.operators.sqlite_operator t = airflow.operators.sqlite_operator.SqliteOperator( task_id='time_sqlite', sql="CREATE TABLE IF NOT EXISTS unitest (dummy VARCHAR(20))", dag=self.dag) t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_timeout(self): t = PythonOperator( task_id='test_timeout', execution_timeout=timedelta(seconds=1), python_callable=lambda: sleep(5), dag=self.dag) self.assertRaises( exceptions.AirflowTaskTimeout, t.run, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_python_op(self): def test_py_op(templates_dict, ds, **kwargs): if not templates_dict['ds'] == ds: raise Exception("failure") t = PythonOperator( task_id='test_py_op', provide_context=True, python_callable=test_py_op, templates_dict={'ds': "{{ ds }}"}, dag=self.dag) t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_complex_template(self): def verify_templated_field(context): self.assertEqual(context['ti'].task.some_templated_field['bar'][1], context['ds']) t = OperatorSubclass( task_id='test_complex_template', some_templated_field={ 'foo': '123', 'bar': ['baz', '{{ ds }}'] }, dag=self.dag) t.execute = verify_templated_field t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_template_with_variable(self): """ Test the availability of variables in templates """ val = { 'test_value': 'a test value' } Variable.set("a_variable", val['test_value']) def verify_templated_field(context): self.assertEqual(context['ti'].task.some_templated_field, val['test_value']) t = OperatorSubclass( task_id='test_complex_template', some_templated_field='{{ var.value.a_variable }}', dag=self.dag) t.execute = verify_templated_field t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_template_with_json_variable(self): """ Test the availability of variables (serialized as JSON) in templates """ val = { 'test_value': {'foo': 'bar', 'obj': {'v1': 'yes', 'v2': 'no'}} } Variable.set("a_variable", val['test_value'], serialize_json=True) def verify_templated_field(context): self.assertEqual(context['ti'].task.some_templated_field, val['test_value']['obj']['v2']) t = OperatorSubclass( task_id='test_complex_template', some_templated_field='{{ var.json.a_variable.obj.v2 }}', dag=self.dag) t.execute = verify_templated_field t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_template_with_json_variable_as_value(self): """ Test the availability of variables (serialized as JSON) in templates, but accessed as a value """ val = { 'test_value': {'foo': 'bar'} } Variable.set("a_variable", val['test_value'], serialize_json=True) def verify_templated_field(context): self.assertEqual(context['ti'].task.some_templated_field, u'{"foo": "bar"}') t = OperatorSubclass( task_id='test_complex_template', some_templated_field='{{ var.value.a_variable }}', dag=self.dag) t.execute = verify_templated_field t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_template_non_bool(self): """ Test templates can handle objects with no sense of truthiness """ class NonBoolObject(object): def __len__(self): return NotImplemented def __bool__(self): return NotImplemented t = OperatorSubclass( task_id='test_bad_template_obj', some_templated_field=NonBoolObject(), dag=self.dag) t.resolve_template_files() def test_import_examples(self): self.assertEqual(len(self.dagbag.dags), NUM_EXAMPLE_DAGS) def test_local_task_job(self): TI = models.TaskInstance ti = TI( task=self.runme_0, execution_date=DEFAULT_DATE) job = jobs.LocalTaskJob(task_instance=ti, ignore_ti_state=True) job.run() def test_raw_job(self): TI = models.TaskInstance ti = TI( task=self.runme_0, execution_date=DEFAULT_DATE) ti.dag = self.dag_bash ti.run(ignore_ti_state=True) def test_doctests(self): modules = [utils, macros] for mod in modules: failed, tests = doctest.testmod(mod) if failed: raise Exception("Failed a doctest") def test_variable_set_get_round_trip(self): Variable.set("tested_var_set_id", "Monday morning breakfast") self.assertEqual("Monday morning breakfast", Variable.get("tested_var_set_id")) def test_variable_set_get_round_trip_json(self): value = {"a": 17, "b": 47} Variable.set("tested_var_set_id", value, serialize_json=True) self.assertEqual(value, Variable.get("tested_var_set_id", deserialize_json=True)) def test_get_non_existing_var_should_return_default(self): default_value = "some default val" self.assertEqual(default_value, Variable.get("thisIdDoesNotExist", default_var=default_value)) def test_get_non_existing_var_should_not_deserialize_json_default(self): default_value = "}{ this is a non JSON default }{" self.assertEqual(default_value, Variable.get("thisIdDoesNotExist", default_var=default_value, deserialize_json=True)) def test_variable_setdefault_round_trip(self): key = "tested_var_setdefault_1_id" value = "Monday morning breakfast in Paris" Variable.setdefault(key, value) self.assertEqual(value, Variable.get(key)) def test_variable_setdefault_round_trip_json(self): key = "tested_var_setdefault_2_id" value = {"city": 'Paris', "Hapiness": True} Variable.setdefault(key, value, deserialize_json=True) self.assertEqual(value, Variable.get(key, deserialize_json=True)) def test_variable_setdefault_existing_json(self): key = "tested_var_setdefault_2_id" value = {"city": 'Paris', "Hapiness": True} Variable.set(key, value, serialize_json=True) val = Variable.setdefault(key, value, deserialize_json=True) # Check the returned value, and the stored value are handled correctly. self.assertEqual(value, val) self.assertEqual(value, Variable.get(key, deserialize_json=True)) def test_parameterized_config_gen(self): cfg = configuration.parameterized_config(configuration.DEFAULT_CONFIG) # making sure some basic building blocks are present: self.assertIn("[core]", cfg) self.assertIn("dags_folder", cfg) self.assertIn("sql_alchemy_conn", cfg) self.assertIn("fernet_key", cfg) # making sure replacement actually happened self.assertNotIn("{AIRFLOW_HOME}", cfg) self.assertNotIn("{FERNET_KEY}", cfg) def test_config_use_original_when_original_and_fallback_are_present(self): self.assertTrue(configuration.conf.has_option("core", "FERNET_KEY")) self.assertFalse(configuration.conf.has_option("core", "FERNET_KEY_CMD")) FERNET_KEY = configuration.conf.get('core', 'FERNET_KEY') configuration.conf.set("core", "FERNET_KEY_CMD", "printf HELLO") FALLBACK_FERNET_KEY = configuration.conf.get( "core", "FERNET_KEY" ) self.assertEqual(FERNET_KEY, FALLBACK_FERNET_KEY) # restore the conf back to the original state configuration.conf.remove_option("core", "FERNET_KEY_CMD") def test_config_throw_error_when_original_and_fallback_is_absent(self): self.assertTrue(configuration.conf.has_option("core", "FERNET_KEY")) self.assertFalse(configuration.conf.has_option("core", "FERNET_KEY_CMD")) FERNET_KEY = configuration.conf.get("core", "FERNET_KEY") configuration.conf.remove_option("core", "FERNET_KEY") with self.assertRaises(AirflowConfigException) as cm: configuration.conf.get("core", "FERNET_KEY") exception = str(cm.exception) message = "section/key [core/fernet_key] not found in config" self.assertEqual(message, exception) # restore the conf back to the original state configuration.conf.set("core", "FERNET_KEY", FERNET_KEY) self.assertTrue(configuration.conf.has_option("core", "FERNET_KEY")) def test_config_override_original_when_non_empty_envvar_is_provided(self): key = "AIRFLOW__CORE__FERNET_KEY" value = "some value" self.assertNotIn(key, os.environ) os.environ[key] = value FERNET_KEY = configuration.conf.get('core', 'FERNET_KEY') self.assertEqual(value, FERNET_KEY) # restore the envvar back to the original state del os.environ[key] def test_config_override_original_when_empty_envvar_is_provided(self): key = "AIRFLOW__CORE__FERNET_KEY" value = "" self.assertNotIn(key, os.environ) os.environ[key] = value FERNET_KEY = configuration.conf.get('core', 'FERNET_KEY') self.assertEqual(value, FERNET_KEY) # restore the envvar back to the original state del os.environ[key] def test_round_time(self): rt1 = round_time(datetime(2015, 1, 1, 6), timedelta(days=1)) self.assertEqual(datetime(2015, 1, 1, 0, 0), rt1) rt2 = round_time(datetime(2015, 1, 2), relativedelta(months=1)) self.assertEqual(datetime(2015, 1, 1, 0, 0), rt2) rt3 = round_time(datetime(2015, 9, 16, 0, 0), timedelta(1), datetime( 2015, 9, 14, 0, 0)) self.assertEqual(datetime(2015, 9, 16, 0, 0), rt3) rt4 = round_time(datetime(2015, 9, 15, 0, 0), timedelta(1), datetime( 2015, 9, 14, 0, 0)) self.assertEqual(datetime(2015, 9, 15, 0, 0), rt4) rt5 = round_time(datetime(2015, 9, 14, 0, 0), timedelta(1), datetime( 2015, 9, 14, 0, 0)) self.assertEqual(datetime(2015, 9, 14, 0, 0), rt5) rt6 = round_time(datetime(2015, 9, 13, 0, 0), timedelta(1), datetime( 2015, 9, 14, 0, 0)) self.assertEqual(datetime(2015, 9, 14, 0, 0), rt6) def test_infer_time_unit(self): self.assertEqual('minutes', infer_time_unit([130, 5400, 10])) self.assertEqual('seconds', infer_time_unit([110, 50, 10, 100])) self.assertEqual('hours', infer_time_unit([100000, 50000, 10000, 20000])) self.assertEqual('days', infer_time_unit([200000, 100000])) def test_scale_time_units(self): # use assert_almost_equal from numpy.testing since we are comparing # floating point arrays arr1 = scale_time_units([130, 5400, 10], 'minutes') assert_array_almost_equal(arr1, [2.167, 90.0, 0.167], decimal=3) arr2 = scale_time_units([110, 50, 10, 100], 'seconds') assert_array_almost_equal(arr2, [110.0, 50.0, 10.0, 100.0], decimal=3) arr3 = scale_time_units([100000, 50000, 10000, 20000], 'hours') assert_array_almost_equal(arr3, [27.778, 13.889, 2.778, 5.556], decimal=3) arr4 = scale_time_units([200000, 100000], 'days') assert_array_almost_equal(arr4, [2.315, 1.157], decimal=3) def test_duplicate_dependencies(self): regexp = "Dependency (.*)runme_0(.*)run_after_loop(.*) " \ "already registered" with self.assertRaisesRegexp(AirflowException, regexp): self.runme_0.set_downstream(self.run_after_loop) with self.assertRaisesRegexp(AirflowException, regexp): self.run_after_loop.set_upstream(self.runme_0) def test_bad_trigger_rule(self): with self.assertRaises(AirflowException): DummyOperator( task_id='test_bad_trigger', trigger_rule="non_existant", dag=self.dag) def test_terminate_task(self): """If a task instance's db state get deleted, it should fail""" TI = models.TaskInstance dag = self.dagbag.dags.get('test_utils') task = dag.task_dict.get('sleeps_forever') ti = TI(task=task, execution_date=DEFAULT_DATE) job = jobs.LocalTaskJob( task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor()) # Running task instance asynchronously p = multiprocessing.Process(target=job.run) p.start() sleep(5) settings.engine.dispose() session = settings.Session() ti.refresh_from_db(session=session) # making sure it's actually running self.assertEqual(State.RUNNING, ti.state) ti = session.query(TI).filter_by( dag_id=task.dag_id, task_id=task.task_id, execution_date=DEFAULT_DATE ).one() # deleting the instance should result in a failure session.delete(ti) session.commit() # waiting for the async task to finish p.join() # making sure that the task ended up as failed ti.refresh_from_db(session=session) self.assertEqual(State.FAILED, ti.state) session.close() def test_task_fail_duration(self): """If a task fails, the duration should be recorded in TaskFail""" p = BashOperator( task_id='pass_sleepy', bash_command='sleep 3', dag=self.dag) f = BashOperator( task_id='fail_sleepy', bash_command='sleep 5', execution_timeout=timedelta(seconds=3), retry_delay=timedelta(seconds=0), dag=self.dag) session = settings.Session() try: p.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) except: pass try: f.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) except: pass p_fails = session.query(models.TaskFail).filter_by( task_id='pass_sleepy', dag_id=self.dag.dag_id, execution_date=DEFAULT_DATE).all() f_fails = session.query(models.TaskFail).filter_by( task_id='fail_sleepy', dag_id=self.dag.dag_id, execution_date=DEFAULT_DATE).all() print(f_fails) self.assertEqual(0, len(p_fails)) self.assertEqual(1, len(f_fails)) # C self.assertGreaterEqual(sum([f.duration for f in f_fails]), 3) def test_dag_stats(self): """Correctly sets/dirties/cleans rows of DagStat table""" session = settings.Session() session.query(models.DagRun).delete() session.query(models.DagStat).delete() session.commit() models.DagStat.update([], session=session) run1 = self.dag_bash.create_dagrun( run_id="run1", execution_date=DEFAULT_DATE, state=State.RUNNING) models.DagStat.update([self.dag_bash.dag_id], session=session) qry = session.query(models.DagStat).all() self.assertEqual(3, len(qry)) self.assertEqual(self.dag_bash.dag_id, qry[0].dag_id) for stats in qry: if stats.state == State.RUNNING: self.assertEqual(stats.count, 1) else: self.assertEqual(stats.count, 0) self.assertFalse(stats.dirty) run2 = self.dag_bash.create_dagrun( run_id="run2", execution_date=DEFAULT_DATE + timedelta(days=1), state=State.RUNNING) models.DagStat.update([self.dag_bash.dag_id], session=session) qry = session.query(models.DagStat).all() self.assertEqual(3, len(qry)) self.assertEqual(self.dag_bash.dag_id, qry[0].dag_id) for stats in qry: if stats.state == State.RUNNING: self.assertEqual(stats.count, 2) else: self.assertEqual(stats.count, 0) self.assertFalse(stats.dirty) session.query(models.DagRun).first().state = State.SUCCESS session.commit() models.DagStat.update([self.dag_bash.dag_id], session=session) qry = session.query(models.DagStat).filter(models.DagStat.state == State.SUCCESS).all() self.assertEqual(1, len(qry)) self.assertEqual(self.dag_bash.dag_id, qry[0].dag_id) self.assertEqual(State.SUCCESS, qry[0].state) self.assertEqual(1, qry[0].count) self.assertFalse(qry[0].dirty) qry = session.query(models.DagStat).filter(models.DagStat.state == State.RUNNING).all() self.assertEqual(1, len(qry)) self.assertEqual(self.dag_bash.dag_id, qry[0].dag_id) self.assertEqual(State.RUNNING, qry[0].state) self.assertEqual(1, qry[0].count) self.assertFalse(qry[0].dirty) session.query(models.DagRun).delete() session.query(models.DagStat).delete() session.commit() session.close() def test_run_command(self): if six.PY3: write = r'sys.stdout.buffer.write("\u1000foo".encode("utf8"))' else: write = r'sys.stdout.write(u"\u1000foo".encode("utf8"))' cmd = 'import sys; {0}; sys.stdout.flush()'.format(write) self.assertEqual(run_command("python -c '{0}'".format(cmd)), u'\u1000foo' if six.PY3 else 'foo') self.assertEqual(run_command('echo "foo bar"'), u'foo bar\n') self.assertRaises(AirflowConfigException, run_command, 'bash -c "exit 1"') class CliTests(unittest.TestCase): @classmethod def setUpClass(cls): super(CliTests, cls).setUpClass() cls._cleanup() def setUp(self): super(CliTests, self).setUp() configuration.load_test_config() app = application.create_app() app.config['TESTING'] = True self.parser = cli.CLIFactory.get_parser() self.dagbag = models.DagBag(dag_folder=DEV_NULL, include_examples=True) self.session = Session() def tearDown(self): self._cleanup(session=self.session) super(CliTests, self).tearDown() @staticmethod def _cleanup(session=None): if session is None: session = Session() session.query(models.Pool).delete() session.query(models.Variable).delete() session.commit() session.close() def test_cli_list_dags(self): args = self.parser.parse_args(['list_dags', '--report']) cli.list_dags(args) def test_cli_create_user(self): args = self.parser.parse_args([ 'create_user', '-u', 'test', '-l', 'doe', '-f', 'jon', '-e', 'jdoe@foo.com', '-r', 'Viewer', '--use_random_password' ]) cli.create_user(args) def test_cli_list_tasks(self): for dag_id in self.dagbag.dags.keys(): args = self.parser.parse_args(['list_tasks', dag_id]) cli.list_tasks(args) args = self.parser.parse_args([ 'list_tasks', 'example_bash_operator', '--tree']) cli.list_tasks(args) @mock.patch("airflow.bin.cli.db_utils.initdb") def test_cli_initdb(self, initdb_mock): cli.initdb(self.parser.parse_args(['initdb'])) initdb_mock.assert_called_once_with(False) @mock.patch("airflow.bin.cli.db_utils.resetdb") def test_cli_resetdb(self, resetdb_mock): cli.resetdb(self.parser.parse_args(['resetdb', '--yes'])) resetdb_mock.assert_called_once_with(False) def test_cli_connections_list(self): with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args(['connections', '--list'])) stdout = mock_stdout.getvalue() conns = [[x.strip("'") for x in re.findall("'\w+'", line)[:2]] for ii, line in enumerate(stdout.split('\n')) if ii % 2 == 1] conns = [conn for conn in conns if len(conn) > 0] # Assert that some of the connections are present in the output as # expected: self.assertIn(['aws_default', 'aws'], conns) self.assertIn(['beeline_default', 'beeline'], conns) self.assertIn(['emr_default', 'emr'], conns) self.assertIn(['mssql_default', 'mssql'], conns) self.assertIn(['mysql_default', 'mysql'], conns) self.assertIn(['postgres_default', 'postgres'], conns) self.assertIn(['wasb_default', 'wasb'], conns) # Attempt to list connections with invalid cli args with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args( ['connections', '--list', '--conn_id=fake', '--conn_uri=fake-uri', '--conn_type=fake-type', '--conn_host=fake_host', '--conn_login=fake_login', '--conn_password=fake_password', '--conn_schema=fake_schema', '--conn_port=fake_port', '--conn_extra=fake_extra'])) stdout = mock_stdout.getvalue() # Check list attempt stdout lines = [l for l in stdout.split('\n') if len(l) > 0] self.assertListEqual(lines, [ ("\tThe following args are not compatible with the " + "--list flag: ['conn_id', 'conn_uri', 'conn_extra', " + "'conn_type', 'conn_host', 'conn_login', " + "'conn_password', 'conn_schema', 'conn_port']"), ]) def test_cli_connections_list_redirect(self): cmd = ['airflow', 'connections', '--list'] with tempfile.TemporaryFile() as fp: p = subprocess.Popen(cmd, stdout=fp) p.wait() self.assertEqual(0, p.returncode) def test_cli_connections_add_delete(self): # Add connections: uri = 'postgresql://airflow:airflow@host:5432/airflow' with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args( ['connections', '--add', '--conn_id=new1', '--conn_uri=%s' % uri])) cli.connections(self.parser.parse_args( ['connections', '-a', '--conn_id=new2', '--conn_uri=%s' % uri])) cli.connections(self.parser.parse_args( ['connections', '--add', '--conn_id=new3', '--conn_uri=%s' % uri, '--conn_extra', "{'extra': 'yes'}"])) cli.connections(self.parser.parse_args( ['connections', '-a', '--conn_id=new4', '--conn_uri=%s' % uri, '--conn_extra', "{'extra': 'yes'}"])) cli.connections(self.parser.parse_args( ['connections', '--add', '--conn_id=new5', '--conn_type=hive_metastore', '--conn_login=airflow', '--conn_password=airflow', '--conn_host=host', '--conn_port=9083', '--conn_schema=airflow'])) cli.connections(self.parser.parse_args( ['connections', '-a', '--conn_id=new6', '--conn_uri', "", '--conn_type=google_cloud_platform', '--conn_extra', "{'extra': 'yes'}"])) stdout = mock_stdout.getvalue() # Check addition stdout lines = [l for l in stdout.split('\n') if len(l) > 0] self.assertListEqual(lines, [ ("\tSuccessfully added `conn_id`=new1 : " + "postgresql://airflow:airflow@host:5432/airflow"), ("\tSuccessfully added `conn_id`=new2 : " + "postgresql://airflow:airflow@host:5432/airflow"), ("\tSuccessfully added `conn_id`=new3 : " + "postgresql://airflow:airflow@host:5432/airflow"), ("\tSuccessfully added `conn_id`=new4 : " + "postgresql://airflow:airflow@host:5432/airflow"), ("\tSuccessfully added `conn_id`=new5 : " + "hive_metastore://airflow:airflow@host:9083/airflow"), ("\tSuccessfully added `conn_id`=new6 : " + "google_cloud_platform://:@:") ]) # Attempt to add duplicate with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args( ['connections', '--add', '--conn_id=new1', '--conn_uri=%s' % uri])) stdout = mock_stdout.getvalue() # Check stdout for addition attempt lines = [l for l in stdout.split('\n') if len(l) > 0] self.assertListEqual(lines, [ "\tA connection with `conn_id`=new1 already exists", ]) # Attempt to add without providing conn_id with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args( ['connections', '--add', '--conn_uri=%s' % uri])) stdout = mock_stdout.getvalue() # Check stdout for addition attempt lines = [l for l in stdout.split('\n') if len(l) > 0] self.assertListEqual(lines, [ ("\tThe following args are required to add a connection:" + " ['conn_id']"), ]) # Attempt to add without providing conn_uri with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args( ['connections', '--add', '--conn_id=new'])) stdout = mock_stdout.getvalue() # Check stdout for addition attempt lines = [l for l in stdout.split('\n') if len(l) > 0] self.assertListEqual(lines, [ ("\tThe following args are required to add a connection:" + " ['conn_uri or conn_type']"), ]) # Prepare to add connections session = settings.Session() extra = {'new1': None, 'new2': None, 'new3': "{'extra': 'yes'}", 'new4': "{'extra': 'yes'}"} # Add connections for index in range(1, 6): conn_id = 'new%s' % index result = (session .query(models.Connection) .filter(models.Connection.conn_id == conn_id) .first()) result = (result.conn_id, result.conn_type, result.host, result.port, result.get_extra()) if conn_id in ['new1', 'new2', 'new3', 'new4']: self.assertEqual(result, (conn_id, 'postgres', 'host', 5432, extra[conn_id])) elif conn_id == 'new5': self.assertEqual(result, (conn_id, 'hive_metastore', 'host', 9083, None)) elif conn_id == 'new6': self.assertEqual(result, (conn_id, 'google_cloud_platform', None, None, "{'extra': 'yes'}")) # Delete connections with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args( ['connections', '--delete', '--conn_id=new1'])) cli.connections(self.parser.parse_args( ['connections', '--delete', '--conn_id=new2'])) cli.connections(self.parser.parse_args( ['connections', '--delete', '--conn_id=new3'])) cli.connections(self.parser.parse_args( ['connections', '--delete', '--conn_id=new4'])) cli.connections(self.parser.parse_args( ['connections', '--delete', '--conn_id=new5'])) cli.connections(self.parser.parse_args( ['connections', '--delete', '--conn_id=new6'])) stdout = mock_stdout.getvalue() # Check deletion stdout lines = [l for l in stdout.split('\n') if len(l) > 0] self.assertListEqual(lines, [ "\tSuccessfully deleted `conn_id`=new1", "\tSuccessfully deleted `conn_id`=new2", "\tSuccessfully deleted `conn_id`=new3", "\tSuccessfully deleted `conn_id`=new4", "\tSuccessfully deleted `conn_id`=new5", "\tSuccessfully deleted `conn_id`=new6" ]) # Check deletions for index in range(1, 7): conn_id = 'new%s' % index result = (session.query(models.Connection) .filter(models.Connection.conn_id == conn_id) .first()) self.assertTrue(result is None) # Attempt to delete a non-existing connnection with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args( ['connections', '--delete', '--conn_id=fake'])) stdout = mock_stdout.getvalue() # Check deletion attempt stdout lines = [l for l in stdout.split('\n') if len(l) > 0] self.assertListEqual(lines, [ "\tDid not find a connection with `conn_id`=fake", ]) # Attempt to delete with invalid cli args with mock.patch('sys.stdout', new_callable=six.StringIO) as mock_stdout: cli.connections(self.parser.parse_args( ['connections', '--delete', '--conn_id=fake', '--conn_uri=%s' % uri, '--conn_type=fake-type'])) stdout = mock_stdout.getvalue() # Check deletion attempt stdout lines = [l for l in stdout.split('\n') if len(l) > 0] self.assertListEqual(lines, [ ("\tThe following args are not compatible with the " + "--delete flag: ['conn_uri', 'conn_type']"), ]) session.close() def test_cli_test(self): cli.test(self.parser.parse_args([ 'test', 'example_bash_operator', 'runme_0', DEFAULT_DATE.isoformat()])) cli.test(self.parser.parse_args([ 'test', 'example_bash_operator', 'runme_0', '--dry_run', DEFAULT_DATE.isoformat()])) def test_cli_test_with_params(self): cli.test(self.parser.parse_args([ 'test', 'example_passing_params_via_test_command', 'run_this', '-tp', '{"foo":"bar"}', DEFAULT_DATE.isoformat()])) cli.test(self.parser.parse_args([ 'test', 'example_passing_params_via_test_command', 'also_run_this', '-tp', '{"foo":"bar"}', DEFAULT_DATE.isoformat()])) def test_cli_run(self): cli.run(self.parser.parse_args([ 'run', 'example_bash_operator', 'runme_0', '-l', DEFAULT_DATE.isoformat()])) def test_task_state(self): cli.task_state(self.parser.parse_args([ 'task_state', 'example_bash_operator', 'runme_0', DEFAULT_DATE.isoformat()])) def test_dag_state(self): self.assertEqual(None, cli.dag_state(self.parser.parse_args([ 'dag_state', 'example_bash_operator', DEFAULT_DATE.isoformat()]))) def test_pause(self): args = self.parser.parse_args([ 'pause', 'example_bash_operator']) cli.pause(args) self.assertIn(self.dagbag.dags['example_bash_operator'].is_paused, [True, 1]) args = self.parser.parse_args([ 'unpause', 'example_bash_operator']) cli.unpause(args) self.assertIn(self.dagbag.dags['example_bash_operator'].is_paused, [False, 0]) def test_subdag_clear(self): args = self.parser.parse_args([ 'clear', 'example_subdag_operator', '--no_confirm']) cli.clear(args) args = self.parser.parse_args([ 'clear', 'example_subdag_operator', '--no_confirm', '--exclude_subdags']) cli.clear(args) def test_get_dags(self): dags = cli.get_dags(self.parser.parse_args(['clear', 'example_subdag_operator', '-c'])) self.assertEqual(len(dags), 1) dags = cli.get_dags(self.parser.parse_args(['clear', 'subdag', '-dx', '-c'])) self.assertGreater(len(dags), 1) with self.assertRaises(AirflowException): cli.get_dags(self.parser.parse_args(['clear', 'foobar', '-dx', '-c'])) def test_backfill(self): cli.backfill(self.parser.parse_args([ 'backfill', 'example_bash_operator', '-s', DEFAULT_DATE.isoformat()])) cli.backfill(self.parser.parse_args([ 'backfill', 'example_bash_operator', '-t', 'runme_0', '--dry_run', '-s', DEFAULT_DATE.isoformat()])) cli.backfill(self.parser.parse_args([ 'backfill', 'example_bash_operator', '--dry_run', '-s', DEFAULT_DATE.isoformat()])) cli.backfill(self.parser.parse_args([ 'backfill', 'example_bash_operator', '-l', '-s', DEFAULT_DATE.isoformat()])) def test_process_subdir_path_with_placeholder(self): self.assertEqual(os.path.join(settings.DAGS_FOLDER, 'abc'), cli.process_subdir('DAGS_FOLDER/abc')) def test_trigger_dag(self): cli.trigger_dag(self.parser.parse_args([ 'trigger_dag', 'example_bash_operator', '-c', '{"foo": "bar"}'])) self.assertRaises( ValueError, cli.trigger_dag, self.parser.parse_args([ 'trigger_dag', 'example_bash_operator', '--run_id', 'trigger_dag_xxx', '-c', 'NOT JSON']) ) def test_delete_dag(self): DM = models.DagModel key = "my_dag_id" session = settings.Session() session.add(DM(dag_id=key)) session.commit() cli.delete_dag(self.parser.parse_args([ 'delete_dag', key, '--yes'])) self.assertEqual(session.query(DM).filter_by(dag_id=key).count(), 0) self.assertRaises( AirflowException, cli.delete_dag, self.parser.parse_args([ 'delete_dag', 'does_not_exist_dag', '--yes']) ) def test_pool_create(self): cli.pool(self.parser.parse_args(['pool', '-s', 'foo', '1', 'test'])) self.assertEqual(self.session.query(models.Pool).count(), 1) def test_pool_get(self): cli.pool(self.parser.parse_args(['pool', '-s', 'foo', '1', 'test'])) try: cli.pool(self.parser.parse_args(['pool', '-g', 'foo'])) except Exception as e: self.fail("The 'pool -g foo' command raised unexpectedly: %s" % e) def test_pool_delete(self): cli.pool(self.parser.parse_args(['pool', '-s', 'foo', '1', 'test'])) cli.pool(self.parser.parse_args(['pool', '-x', 'foo'])) self.assertEqual(self.session.query(models.Pool).count(), 0) def test_pool_no_args(self): try: cli.pool(self.parser.parse_args(['pool'])) except Exception as e: self.fail("The 'pool' command raised unexpectedly: %s" % e) def test_variables(self): # Checks if all subcommands are properly received cli.variables(self.parser.parse_args([ 'variables', '-s', 'foo', '{"foo":"bar"}'])) cli.variables(self.parser.parse_args([ 'variables', '-g', 'foo'])) cli.variables(self.parser.parse_args([ 'variables', '-g', 'baz', '-d', 'bar'])) cli.variables(self.parser.parse_args([ 'variables'])) cli.variables(self.parser.parse_args([ 'variables', '-x', 'bar'])) cli.variables(self.parser.parse_args([ 'variables', '-i', DEV_NULL])) cli.variables(self.parser.parse_args([ 'variables', '-e', DEV_NULL])) cli.variables(self.parser.parse_args([ 'variables', '-s', 'bar', 'original'])) # First export cli.variables(self.parser.parse_args([ 'variables', '-e', 'variables1.json'])) first_exp = open('variables1.json', 'r') cli.variables(self.parser.parse_args([ 'variables', '-s', 'bar', 'updated'])) cli.variables(self.parser.parse_args([ 'variables', '-s', 'foo', '{"foo":"oops"}'])) cli.variables(self.parser.parse_args([ 'variables', '-x', 'foo'])) # First import cli.variables(self.parser.parse_args([ 'variables', '-i', 'variables1.json'])) self.assertEqual('original', models.Variable.get('bar')) self.assertEqual('{"foo": "bar"}', models.Variable.get('foo')) # Second export cli.variables(self.parser.parse_args([ 'variables', '-e', 'variables2.json'])) second_exp = open('variables2.json', 'r') self.assertEqual(first_exp.read(), second_exp.read()) second_exp.close() first_exp.close() # Second import cli.variables(self.parser.parse_args([ 'variables', '-i', 'variables2.json'])) self.assertEqual('original', models.Variable.get('bar')) self.assertEqual('{"foo": "bar"}', models.Variable.get('foo')) os.remove('variables1.json') os.remove('variables2.json') def _wait_pidfile(self, pidfile): while True: try: with open(pidfile) as f: return int(f.read()) except: sleep(1) def test_cli_webserver_foreground(self): # Confirm that webserver hasn't been launched. # pgrep returns exit status 1 if no process matched. self.assertEqual(1, subprocess.Popen(["pgrep", "-c", "airflow"]).wait()) self.assertEqual(1, subprocess.Popen(["pgrep", "-c", "gunicorn"]).wait()) # Run webserver in foreground and terminate it. p = subprocess.Popen(["airflow", "webserver"]) p.terminate() p.wait() # Assert that no process remains. self.assertEqual(1, subprocess.Popen(["pgrep", "-c", "airflow"]).wait()) self.assertEqual(1, subprocess.Popen(["pgrep", "-c", "gunicorn"]).wait()) @unittest.skipIf("TRAVIS" in os.environ and bool(os.environ["TRAVIS"]), "Skipping test due to lack of required file permission") def test_cli_webserver_foreground_with_pid(self): # Run webserver in foreground with --pid option pidfile = tempfile.mkstemp()[1] p = subprocess.Popen(["airflow", "webserver", "--pid", pidfile]) # Check the file specified by --pid option exists self._wait_pidfile(pidfile) # Terminate webserver p.terminate() p.wait() @unittest.skipIf("TRAVIS" in os.environ and bool(os.environ["TRAVIS"]), "Skipping test due to lack of required file permission") def test_cli_webserver_background(self): import psutil # Confirm that webserver hasn't been launched. self.assertEqual(1, subprocess.Popen(["pgrep", "-c", "airflow"]).wait()) self.assertEqual(1, subprocess.Popen(["pgrep", "-c", "gunicorn"]).wait()) # Run webserver in background. subprocess.Popen(["airflow", "webserver", "-D"]) pidfile = cli.setup_locations("webserver")[0] self._wait_pidfile(pidfile) # Assert that gunicorn and its monitor are launched. self.assertEqual(0, subprocess.Popen(["pgrep", "-c", "airflow"]).wait()) self.assertEqual(0, subprocess.Popen(["pgrep", "-c", "gunicorn"]).wait()) # Terminate monitor process. pidfile = cli.setup_locations("webserver-monitor")[0] pid = self._wait_pidfile(pidfile) p = psutil.Process(pid) p.terminate() p.wait() # Assert that no process remains. self.assertEqual(1, subprocess.Popen(["pgrep", "-c", "airflow"]).wait()) self.assertEqual(1, subprocess.Popen(["pgrep", "-c", "gunicorn"]).wait()) # Patch for causing webserver timeout @mock.patch("airflow.bin.cli.get_num_workers_running", return_value=0) def test_cli_webserver_shutdown_when_gunicorn_master_is_killed(self, _): # Shorten timeout so that this test doesn't take too long time configuration.conf.set("webserver", "web_server_master_timeout", "10") args = self.parser.parse_args(['webserver']) with self.assertRaises(SystemExit) as e: cli.webserver(args) self.assertEqual(e.exception.code, 1) class SecurityTests(unittest.TestCase): def setUp(self): configuration.load_test_config() configuration.conf.set("webserver", "authenticate", "False") configuration.conf.set("webserver", "expose_config", "True") app = application.create_app() app.config['TESTING'] = True self.app = app.test_client() self.dagbag = models.DagBag( dag_folder=DEV_NULL, include_examples=True) self.dag_bash = self.dagbag.dags['example_bash_operator'] self.runme_0 = self.dag_bash.get_task('runme_0') def get_csrf(self, response): tree = html.fromstring(response.data) form = tree.find('.//form') return form.find('.//input[@name="_csrf_token"]').value def test_csrf_rejection(self): endpoints = ([ "/admin/queryview/", "/admin/airflow/paused?dag_id=example_python_operator&is_paused=false", ]) for endpoint in endpoints: response = self.app.post(endpoint) self.assertIn('CSRF token is missing', response.data.decode('utf-8')) def test_csrf_acceptance(self): response = self.app.get("/admin/queryview/") csrf = self.get_csrf(response) response = self.app.post("/admin/queryview/", data=dict(csrf_token=csrf)) self.assertEqual(200, response.status_code) def test_xss(self): try: self.app.get("/admin/airflow/tree?dag_id=<script>alert(123456)</script>") except: # exception is expected here since dag doesnt exist pass response = self.app.get("/admin/log", follow_redirects=True) self.assertIn(bleach.clean("<script>alert(123456)</script>"), response.data.decode('UTF-8')) def test_chart_data_template(self): """Protect chart_data from being able to do RCE.""" session = settings.Session() Chart = models.Chart chart1 = Chart( label='insecure_chart', conn_id='airflow_db', chart_type='bar', sql="SELECT {{ ''.__class__.__mro__[1].__subclasses__() }}" ) chart2 = Chart( label="{{ ''.__class__.__mro__[1].__subclasses__() }}", conn_id='airflow_db', chart_type='bar', sql="SELECT 1" ) chart3 = Chart( label="{{ subprocess.check_output('ls') }}", conn_id='airflow_db', chart_type='bar', sql="SELECT 1" ) session.add(chart1) session.add(chart2) session.add(chart3) session.commit() chart1 = session.query(Chart).filter(Chart.label == 'insecure_chart').first() with self.assertRaises(SecurityError): self.app.get("/admin/airflow/chart_data?chart_id={}".format(chart1.id)) chart2 = session.query(Chart).filter( Chart.label == "{{ ''.__class__.__mro__[1].__subclasses__() }}" ).first() with self.assertRaises(SecurityError): self.app.get("/admin/airflow/chart_data?chart_id={}".format(chart2.id)) chart3 = session.query(Chart).filter( Chart.label == "{{ subprocess.check_output('ls') }}" ).first() with self.assertRaises(UndefinedError): self.app.get("/admin/airflow/chart_data?chart_id={}".format(chart3.id)) def tearDown(self): configuration.conf.set("webserver", "expose_config", "False") self.dag_bash.clear(start_date=DEFAULT_DATE, end_date=timezone.utcnow()) class WebUiTests(unittest.TestCase): def setUp(self): configuration.load_test_config() configuration.conf.set("webserver", "authenticate", "False") configuration.conf.set("webserver", "expose_config", "True") app = application.create_app() app.config['TESTING'] = True app.config['WTF_CSRF_METHODS'] = [] self.app = app.test_client() self.dagbag = models.DagBag(include_examples=True) self.dag_bash = self.dagbag.dags['example_bash_operator'] self.dag_python = self.dagbag.dags['example_python_operator'] self.sub_dag = self.dagbag.dags['example_subdag_operator'] self.runme_0 = self.dag_bash.get_task('runme_0') self.example_xcom = self.dagbag.dags['example_xcom'] self.dagrun_python = self.dag_python.create_dagrun( run_id="test_{}".format(models.DagRun.id_for_date(timezone.utcnow())), execution_date=DEFAULT_DATE, start_date=timezone.utcnow(), state=State.RUNNING ) self.sub_dag.create_dagrun( run_id="test_{}".format(models.DagRun.id_for_date(timezone.utcnow())), execution_date=DEFAULT_DATE, start_date=timezone.utcnow(), state=State.RUNNING ) self.example_xcom.create_dagrun( run_id="test_{}".format(models.DagRun.id_for_date(timezone.utcnow())), execution_date=DEFAULT_DATE, start_date=timezone.utcnow(), state=State.RUNNING ) def test_index(self): response = self.app.get('/', follow_redirects=True) resp_html = response.data.decode('utf-8') self.assertIn("DAGs", resp_html) self.assertIn("example_bash_operator", resp_html) # The HTML should contain data for the last-run. A link to the specific run, # and the text of the date. url = "/admin/airflow/graph?" + urlencode({ "dag_id": self.dag_python.dag_id, "execution_date": self.dagrun_python.execution_date, }).replace("&", "&amp;") self.assertIn(url, resp_html) self.assertIn( self.dagrun_python.execution_date.strftime("%Y-%m-%d %H:%M"), resp_html) def test_query(self): response = self.app.get('/admin/queryview/') self.assertIn("Ad Hoc Query", response.data.decode('utf-8')) response = self.app.post( "/admin/queryview/", data=dict( conn_id="airflow_db", sql="SELECT+COUNT%281%29+as+TEST+FROM+task_instance")) self.assertIn("TEST", response.data.decode('utf-8')) def test_health(self): response = self.app.get('/health') self.assertIn('The server is healthy!', response.data.decode('utf-8')) def test_noaccess(self): response = self.app.get('/admin/airflow/noaccess') self.assertIn("You don't seem to have access.", response.data.decode('utf-8')) def test_pickle_info(self): response = self.app.get('/admin/airflow/pickle_info') self.assertIn('{', response.data.decode('utf-8')) def test_dag_views(self): response = self.app.get( '/admin/airflow/graph?dag_id=example_bash_operator') self.assertIn("runme_0", response.data.decode('utf-8')) # confirm that the graph page loads when execution_date is blank response = self.app.get( '/admin/airflow/graph?dag_id=example_bash_operator&execution_date=') self.assertIn("runme_0", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/tree?num_runs=25&dag_id=example_bash_operator') self.assertIn("runme_0", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/duration?days=30&dag_id=example_bash_operator') self.assertIn("example_bash_operator", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/tries?days=30&dag_id=example_bash_operator') self.assertIn("example_bash_operator", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/landing_times?' 'days=30&dag_id=example_python_operator') self.assertIn("example_python_operator", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/landing_times?' 'days=30&dag_id=example_xcom') self.assertIn("example_xcom", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/gantt?dag_id=example_bash_operator') self.assertIn("example_bash_operator", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/code?dag_id=example_bash_operator') self.assertIn("example_bash_operator", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/blocked') response = self.app.get( '/admin/configurationview/') self.assertIn("Airflow Configuration", response.data.decode('utf-8')) self.assertIn("Running Configuration", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/rendered?' 'task_id=runme_1&dag_id=example_bash_operator&' 'execution_date={}'.format(DEFAULT_DATE_ISO)) self.assertIn("example_bash_operator", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/log?task_id=run_this_last&' 'dag_id=example_bash_operator&execution_date={}' ''.format(DEFAULT_DATE_ISO)) self.assertIn("run_this_last", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/task?' 'task_id=runme_0&dag_id=example_bash_operator&' 'execution_date={}'.format(DEFAULT_DATE_DS)) self.assertIn("Attributes", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/dag_stats') self.assertIn("example_bash_operator", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/task_stats') self.assertIn("example_bash_operator", response.data.decode('utf-8')) url = ( "/admin/airflow/success?task_id=print_the_context&" "dag_id=example_python_operator&upstream=false&downstream=false&" "future=false&past=false&execution_date={}&" "origin=/admin".format(DEFAULT_DATE_DS)) response = self.app.get(url) self.assertIn("Wait a minute", response.data.decode('utf-8')) response = self.app.get(url + "&confirmed=true") response = self.app.get( '/admin/airflow/clear?task_id=print_the_context&' 'dag_id=example_python_operator&future=true&past=false&' 'upstream=true&downstream=false&' 'execution_date={}&' 'origin=/admin'.format(DEFAULT_DATE_DS)) self.assertIn("Wait a minute", response.data.decode('utf-8')) url = ( "/admin/airflow/success?task_id=section-1&" "dag_id=example_subdag_operator&upstream=true&downstream=true&" "future=false&past=false&execution_date={}&" "origin=/admin".format(DEFAULT_DATE_DS)) response = self.app.get(url) self.assertIn("Wait a minute", response.data.decode('utf-8')) self.assertIn("section-1-task-1", response.data.decode('utf-8')) self.assertIn("section-1-task-2", response.data.decode('utf-8')) self.assertIn("section-1-task-3", response.data.decode('utf-8')) self.assertIn("section-1-task-4", response.data.decode('utf-8')) self.assertIn("section-1-task-5", response.data.decode('utf-8')) response = self.app.get(url + "&confirmed=true") url = ( "/admin/airflow/clear?task_id=print_the_context&" "dag_id=example_python_operator&future=false&past=false&" "upstream=false&downstream=true&" "execution_date={}&" "origin=/admin".format(DEFAULT_DATE_DS)) response = self.app.get(url) self.assertIn("Wait a minute", response.data.decode('utf-8')) response = self.app.get(url + "&confirmed=true") url = ( "/admin/airflow/run?task_id=runme_0&" "dag_id=example_bash_operator&ignore_all_deps=false&ignore_ti_state=true&" "ignore_task_deps=true&execution_date={}&" "origin=/admin".format(DEFAULT_DATE_DS)) response = self.app.get(url) response = self.app.get( "/admin/airflow/refresh?dag_id=example_bash_operator") response = self.app.get("/admin/airflow/refresh_all") response = self.app.post( "/admin/airflow/paused?" "dag_id=example_python_operator&is_paused=false") self.assertIn("OK", response.data.decode('utf-8')) response = self.app.get("/admin/xcom", follow_redirects=True) self.assertIn("Xcoms", response.data.decode('utf-8')) def test_charts(self): session = Session() chart_label = "Airflow task instance by type" chart = session.query( models.Chart).filter(models.Chart.label == chart_label).first() chart_id = chart.id session.close() response = self.app.get( '/admin/airflow/chart' '?chart_id={}&iteration_no=1'.format(chart_id)) self.assertIn("Airflow task instance by type", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/chart_data' '?chart_id={}&iteration_no=1'.format(chart_id)) self.assertIn("example", response.data.decode('utf-8')) response = self.app.get( '/admin/airflow/dag_details?dag_id=example_branch_operator') self.assertIn("run_this_first", response.data.decode('utf-8')) def test_fetch_task_instance(self): url = ( "/admin/airflow/object/task_instances?" "dag_id=example_python_operator&" "execution_date={}".format(DEFAULT_DATE_DS)) response = self.app.get(url) self.assertIn("print_the_context", response.data.decode('utf-8')) def tearDown(self): configuration.conf.set("webserver", "expose_config", "False") self.dag_bash.clear(start_date=DEFAULT_DATE, end_date=timezone.utcnow()) session = Session() session.query(models.DagRun).delete() session.query(models.TaskInstance).delete() session.commit() session.close() class SecureModeWebUiTests(unittest.TestCase): def setUp(self): configuration.load_test_config() configuration.conf.set("webserver", "authenticate", "False") configuration.conf.set("core", "secure_mode", "True") app = application.create_app() app.config['TESTING'] = True self.app = app.test_client() def test_query(self): response = self.app.get('/admin/queryview/') self.assertEqual(response.status_code, 404) def test_charts(self): response = self.app.get('/admin/chart/') self.assertEqual(response.status_code, 404) def tearDown(self): configuration.conf.remove_option("core", "SECURE_MODE") class WebPasswordAuthTest(unittest.TestCase): def setUp(self): configuration.conf.set("webserver", "authenticate", "True") configuration.conf.set("webserver", "auth_backend", "airflow.contrib.auth.backends.password_auth") app = application.create_app() app.config['TESTING'] = True self.app = app.test_client() from airflow.contrib.auth.backends.password_auth import PasswordUser session = Session() user = models.User() password_user = PasswordUser(user) password_user.username = 'airflow_passwordauth' password_user.password = 'password' print(password_user._password) session.add(password_user) session.commit() session.close() def get_csrf(self, response): tree = html.fromstring(response.data) form = tree.find('.//form') return form.find('.//input[@name="_csrf_token"]').value def login(self, username, password): response = self.app.get('/admin/airflow/login') csrf_token = self.get_csrf(response) return self.app.post('/admin/airflow/login', data=dict( username=username, password=password, csrf_token=csrf_token ), follow_redirects=True) def logout(self): return self.app.get('/admin/airflow/logout', follow_redirects=True) def test_login_logout_password_auth(self): self.assertTrue(configuration.conf.getboolean('webserver', 'authenticate')) response = self.login('user1', 'whatever') self.assertIn('Incorrect login details', response.data.decode('utf-8')) response = self.login('airflow_passwordauth', 'wrongpassword') self.assertIn('Incorrect login details', response.data.decode('utf-8')) response = self.login('airflow_passwordauth', 'password') self.assertIn('Data Profiling', response.data.decode('utf-8')) response = self.logout() self.assertIn('form-signin', response.data.decode('utf-8')) def test_unauthorized_password_auth(self): response = self.app.get("/admin/airflow/landing_times") self.assertEqual(response.status_code, 302) def tearDown(self): configuration.load_test_config() session = Session() session.query(models.User).delete() session.commit() session.close() configuration.conf.set("webserver", "authenticate", "False") class WebLdapAuthTest(unittest.TestCase): def setUp(self): configuration.conf.set("webserver", "authenticate", "True") configuration.conf.set("webserver", "auth_backend", "airflow.contrib.auth.backends.ldap_auth") try: configuration.conf.add_section("ldap") except: pass configuration.conf.set("ldap", "uri", "ldap://localhost:3890") configuration.conf.set("ldap", "user_filter", "objectClass=*") configuration.conf.set("ldap", "user_name_attr", "uid") configuration.conf.set("ldap", "bind_user", "cn=Manager,dc=example,dc=com") configuration.conf.set("ldap", "bind_password", "insecure") configuration.conf.set("ldap", "basedn", "dc=example,dc=com") configuration.conf.set("ldap", "cacert", "") app = application.create_app() app.config['TESTING'] = True self.app = app.test_client() def get_csrf(self, response): tree = html.fromstring(response.data) form = tree.find('.//form') return form.find('.//input[@name="_csrf_token"]').value def login(self, username, password): response = self.app.get('/admin/airflow/login') csrf_token = self.get_csrf(response) return self.app.post('/admin/airflow/login', data=dict( username=username, password=password, csrf_token=csrf_token ), follow_redirects=True) def logout(self): return self.app.get('/admin/airflow/logout', follow_redirects=True) def test_login_logout_ldap(self): self.assertTrue(configuration.conf.getboolean('webserver', 'authenticate')) response = self.login('user1', 'userx') self.assertIn('Incorrect login details', response.data.decode('utf-8')) response = self.login('userz', 'user1') self.assertIn('Incorrect login details', response.data.decode('utf-8')) response = self.login('user1', 'user1') self.assertIn('Data Profiling', response.data.decode('utf-8')) response = self.logout() self.assertIn('form-signin', response.data.decode('utf-8')) def test_unauthorized(self): response = self.app.get("/admin/airflow/landing_times") self.assertEqual(response.status_code, 302) def test_no_filter(self): response = self.login('user1', 'user1') self.assertIn('Data Profiling', response.data.decode('utf-8')) self.assertIn('Connections', response.data.decode('utf-8')) def test_with_filters(self): configuration.conf.set('ldap', 'superuser_filter', 'description=superuser') configuration.conf.set('ldap', 'data_profiler_filter', 'description=dataprofiler') response = self.login('dataprofiler', 'dataprofiler') self.assertIn('Data Profiling', response.data.decode('utf-8')) response = self.login('superuser', 'superuser') self.assertIn('Connections', response.data.decode('utf-8')) def tearDown(self): configuration.load_test_config() session = Session() session.query(models.User).delete() session.commit() session.close() configuration.conf.set("webserver", "authenticate", "False") class LdapGroupTest(unittest.TestCase): def setUp(self): configuration.conf.set("webserver", "authenticate", "True") configuration.conf.set("webserver", "auth_backend", "airflow.contrib.auth.backends.ldap_auth") try: configuration.conf.add_section("ldap") except: pass configuration.conf.set("ldap", "uri", "ldap://localhost:3890") configuration.conf.set("ldap", "user_filter", "objectClass=*") configuration.conf.set("ldap", "user_name_attr", "uid") configuration.conf.set("ldap", "bind_user", "cn=Manager,dc=example,dc=com") configuration.conf.set("ldap", "bind_password", "insecure") configuration.conf.set("ldap", "basedn", "dc=example,dc=com") configuration.conf.set("ldap", "cacert", "") def test_group_belonging(self): from airflow.contrib.auth.backends.ldap_auth import LdapUser users = {"user1": ["group1", "group3"], "user2": ["group2"] } for user in users: mu = models.User(username=user, is_superuser=False) auth = LdapUser(mu) self.assertEqual(set(users[user]), set(auth.ldap_groups)) def tearDown(self): configuration.load_test_config() configuration.conf.set("webserver", "authenticate", "False") class FakeWebHDFSHook(object): def __init__(self, conn_id): self.conn_id = conn_id def get_conn(self): return self.conn_id def check_for_path(self, hdfs_path): return hdfs_path class FakeSnakeBiteClientException(Exception): pass class FakeSnakeBiteClient(object): def __init__(self): self.started = True def ls(self, path, include_toplevel=False): """ the fake snakebite client :param path: the array of path to test :param include_toplevel: to return the toplevel directory info :return: a list for path for the matching queries """ if path[0] == '/datadirectory/empty_directory' and not include_toplevel: return [] elif path[0] == '/datadirectory/datafile': return [{ 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1481122343796, 'block_replication': 3, 'modification_time': 1481122343862, 'length': 0, 'blocksize': 134217728, 'owner': u'hdfs', 'path': '/datadirectory/datafile' }] elif path[0] == '/datadirectory/empty_directory' and include_toplevel: return [{ 'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0, 'block_replication': 0, 'modification_time': 1481132141540, 'length': 0, 'blocksize': 0, 'owner': u'hdfs', 'path': '/datadirectory/empty_directory' }] elif path[0] == '/datadirectory/not_empty_directory' and include_toplevel: return [{ 'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0, 'block_replication': 0, 'modification_time': 1481132141540, 'length': 0, 'blocksize': 0, 'owner': u'hdfs', 'path': '/datadirectory/empty_directory' }, { 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1481122343796, 'block_replication': 3, 'modification_time': 1481122343862, 'length': 0, 'blocksize': 134217728, 'owner': u'hdfs', 'path': '/datadirectory/not_empty_directory/test_file' }] elif path[0] == '/datadirectory/not_empty_directory': return [{ 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1481122343796, 'block_replication': 3, 'modification_time': 1481122343862, 'length': 0, 'blocksize': 134217728, 'owner': u'hdfs', 'path': '/datadirectory/not_empty_directory/test_file' }] elif path[0] == '/datadirectory/not_existing_file_or_directory': raise FakeSnakeBiteClientException elif path[0] == '/datadirectory/regex_dir': return [{ 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1481122343796, 'block_replication': 3, 'modification_time': 1481122343862, 'length': 12582912, 'blocksize': 134217728, 'owner': u'hdfs', 'path': '/datadirectory/regex_dir/test1file' }, { 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1481122343796, 'block_replication': 3, 'modification_time': 1481122343862, 'length': 12582912, 'blocksize': 134217728, 'owner': u'hdfs', 'path': '/datadirectory/regex_dir/test2file' }, { 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1481122343796, 'block_replication': 3, 'modification_time': 1481122343862, 'length': 12582912, 'blocksize': 134217728, 'owner': u'hdfs', 'path': '/datadirectory/regex_dir/test3file' }, { 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1481122343796, 'block_replication': 3, 'modification_time': 1481122343862, 'length': 12582912, 'blocksize': 134217728, 'owner': u'hdfs', 'path': '/datadirectory/regex_dir/copying_file_1.txt._COPYING_' }, { 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1481122343796, 'block_replication': 3, 'modification_time': 1481122343862, 'length': 12582912, 'blocksize': 134217728, 'owner': u'hdfs', 'path': '/datadirectory/regex_dir/copying_file_3.txt.sftp' }] else: raise FakeSnakeBiteClientException class FakeHDFSHook(object): def __init__(self, conn_id=None): self.conn_id = conn_id def get_conn(self): client = FakeSnakeBiteClient() return client class ConnectionTest(unittest.TestCase): def setUp(self): configuration.load_test_config() utils.db.initdb() os.environ['AIRFLOW_CONN_TEST_URI'] = ( 'postgres://username:password@ec2.compute.com:5432/the_database') os.environ['AIRFLOW_CONN_TEST_URI_NO_CREDS'] = ( 'postgres://ec2.compute.com/the_database') def tearDown(self): env_vars = ['AIRFLOW_CONN_TEST_URI', 'AIRFLOW_CONN_AIRFLOW_DB'] for ev in env_vars: if ev in os.environ: del os.environ[ev] def test_using_env_var(self): c = SqliteHook.get_connection(conn_id='test_uri') self.assertEqual('ec2.compute.com', c.host) self.assertEqual('the_database', c.schema) self.assertEqual('username', c.login) self.assertEqual('password', c.password) self.assertEqual(5432, c.port) def test_using_unix_socket_env_var(self): c = SqliteHook.get_connection(conn_id='test_uri_no_creds') self.assertEqual('ec2.compute.com', c.host) self.assertEqual('the_database', c.schema) self.assertIsNone(c.login) self.assertIsNone(c.password) self.assertIsNone(c.port) def test_param_setup(self): c = models.Connection(conn_id='local_mysql', conn_type='mysql', host='localhost', login='airflow', password='airflow', schema='airflow') self.assertEqual('localhost', c.host) self.assertEqual('airflow', c.schema) self.assertEqual('airflow', c.login) self.assertEqual('airflow', c.password) self.assertIsNone(c.port) def test_env_var_priority(self): c = SqliteHook.get_connection(conn_id='airflow_db') self.assertNotEqual('ec2.compute.com', c.host) os.environ['AIRFLOW_CONN_AIRFLOW_DB'] = \ 'postgres://username:password@ec2.compute.com:5432/the_database' c = SqliteHook.get_connection(conn_id='airflow_db') self.assertEqual('ec2.compute.com', c.host) self.assertEqual('the_database', c.schema) self.assertEqual('username', c.login) self.assertEqual('password', c.password) self.assertEqual(5432, c.port) del os.environ['AIRFLOW_CONN_AIRFLOW_DB'] def test_dbapi_get_uri(self): conn = BaseHook.get_connection(conn_id='test_uri') hook = conn.get_hook() self.assertEqual('postgres://username:password@ec2.compute.com:5432/the_database', hook.get_uri()) conn2 = BaseHook.get_connection(conn_id='test_uri_no_creds') hook2 = conn2.get_hook() self.assertEqual('postgres://ec2.compute.com/the_database', hook2.get_uri()) def test_dbapi_get_sqlalchemy_engine(self): conn = BaseHook.get_connection(conn_id='test_uri') hook = conn.get_hook() engine = hook.get_sqlalchemy_engine() self.assertIsInstance(engine, sqlalchemy.engine.Engine) self.assertEqual('postgres://username:password@ec2.compute.com:5432/the_database', str(engine.url)) def test_get_connections_env_var(self): conns = SqliteHook.get_connections(conn_id='test_uri') assert len(conns) == 1 assert conns[0].host == 'ec2.compute.com' assert conns[0].schema == 'the_database' assert conns[0].login == 'username' assert conns[0].password == 'password' assert conns[0].port == 5432 def test_get_connections_db(self): conns = BaseHook.get_connections(conn_id='airflow_db') assert len(conns) == 1 assert conns[0].host == 'localhost' assert conns[0].schema == 'airflow' assert conns[0].login == 'root' class WebHDFSHookTest(unittest.TestCase): def setUp(self): configuration.load_test_config() def test_simple_init(self): from airflow.hooks.webhdfs_hook import WebHDFSHook c = WebHDFSHook() self.assertIsNone(c.proxy_user) def test_init_proxy_user(self): from airflow.hooks.webhdfs_hook import WebHDFSHook c = WebHDFSHook(proxy_user='someone') self.assertEqual('someone', c.proxy_user) try: from airflow.hooks.hdfs_hook import HDFSHook import snakebite except ImportError: HDFSHook = None @unittest.skipIf(HDFSHook is None, "Skipping test because HDFSHook is not installed") class HDFSHookTest(unittest.TestCase): def setUp(self): configuration.load_test_config() os.environ['AIRFLOW_CONN_HDFS_DEFAULT'] = ('hdfs://localhost:8020') def test_get_client(self): client = HDFSHook(proxy_user='foo').get_conn() self.assertIsInstance(client, snakebite.client.Client) self.assertEqual('localhost', client.host) self.assertEqual(8020, client.port) self.assertEqual('foo', client.service.channel.effective_user) @mock.patch('airflow.hooks.hdfs_hook.AutoConfigClient') @mock.patch('airflow.hooks.hdfs_hook.HDFSHook.get_connections') def test_get_autoconfig_client(self, mock_get_connections, MockAutoConfigClient): c = models.Connection(conn_id='hdfs', conn_type='hdfs', host='localhost', port=8020, login='foo', extra=json.dumps({'autoconfig': True})) mock_get_connections.return_value = [c] HDFSHook(hdfs_conn_id='hdfs').get_conn() MockAutoConfigClient.assert_called_once_with(effective_user='foo', use_sasl=False) @mock.patch('airflow.hooks.hdfs_hook.AutoConfigClient') def test_get_autoconfig_client_no_conn(self, MockAutoConfigClient): HDFSHook(hdfs_conn_id='hdfs_missing', autoconfig=True).get_conn() MockAutoConfigClient.assert_called_once_with(effective_user=None, use_sasl=False) @mock.patch('airflow.hooks.hdfs_hook.HDFSHook.get_connections') def test_get_ha_client(self, mock_get_connections): c1 = models.Connection(conn_id='hdfs_default', conn_type='hdfs', host='localhost', port=8020) c2 = models.Connection(conn_id='hdfs_default', conn_type='hdfs', host='localhost2', port=8020) mock_get_connections.return_value = [c1, c2] client = HDFSHook().get_conn() self.assertIsInstance(client, snakebite.client.HAClient) try: from airflow.hooks.http_hook import HttpHook except ImportError: HttpHook = None @unittest.skipIf(HttpHook is None, "Skipping test because HttpHook is not installed") class HttpHookTest(unittest.TestCase): def setUp(self): configuration.load_test_config() @mock.patch('airflow.hooks.http_hook.HttpHook.get_connection') def test_http_connection(self, mock_get_connection): c = models.Connection(conn_id='http_default', conn_type='http', host='localhost', schema='http') mock_get_connection.return_value = c hook = HttpHook() hook.get_conn({}) self.assertEqual(hook.base_url, 'http://localhost') @mock.patch('airflow.hooks.http_hook.HttpHook.get_connection') def test_https_connection(self, mock_get_connection): c = models.Connection(conn_id='http_default', conn_type='http', host='localhost', schema='https') mock_get_connection.return_value = c hook = HttpHook() hook.get_conn({}) self.assertEqual(hook.base_url, 'https://localhost') @mock.patch('airflow.hooks.http_hook.HttpHook.get_connection') def test_host_encoded_http_connection(self, mock_get_connection): c = models.Connection(conn_id='http_default', conn_type='http', host='http://localhost') mock_get_connection.return_value = c hook = HttpHook() hook.get_conn({}) self.assertEqual(hook.base_url, 'http://localhost') @mock.patch('airflow.hooks.http_hook.HttpHook.get_connection') def test_host_encoded_https_connection(self, mock_get_connection): c = models.Connection(conn_id='http_default', conn_type='http', host='https://localhost') mock_get_connection.return_value = c hook = HttpHook() hook.get_conn({}) self.assertEqual(hook.base_url, 'https://localhost') send_email_test = mock.Mock() class EmailTest(unittest.TestCase): def setUp(self): configuration.conf.remove_option('email', 'EMAIL_BACKEND') @mock.patch('airflow.utils.email.send_email') def test_default_backend(self, mock_send_email): res = utils.email.send_email('to', 'subject', 'content') mock_send_email.assert_called_with('to', 'subject', 'content') self.assertEqual(mock_send_email.return_value, res) @mock.patch('airflow.utils.email.send_email_smtp') def test_custom_backend(self, mock_send_email): configuration.conf.set('email', 'EMAIL_BACKEND', 'tests.core.send_email_test') utils.email.send_email('to', 'subject', 'content') send_email_test.assert_called_with( 'to', 'subject', 'content', files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed' ) self.assertFalse(mock_send_email.called) class EmailSmtpTest(unittest.TestCase): def setUp(self): configuration.conf.set('smtp', 'SMTP_SSL', 'False') @mock.patch('airflow.utils.email.send_MIME_email') def test_send_smtp(self, mock_send_mime): attachment = tempfile.NamedTemporaryFile() attachment.write(b'attachment') attachment.seek(0) utils.email.send_email_smtp('to', 'subject', 'content', files=[attachment.name]) self.assertTrue(mock_send_mime.called) call_args = mock_send_mime.call_args[0] self.assertEqual(configuration.conf.get('smtp', 'SMTP_MAIL_FROM'), call_args[0]) self.assertEqual(['to'], call_args[1]) msg = call_args[2] self.assertEqual('subject', msg['Subject']) self.assertEqual(configuration.conf.get('smtp', 'SMTP_MAIL_FROM'), msg['From']) self.assertEqual(2, len(msg.get_payload())) self.assertEqual(u'attachment; filename="' + os.path.basename(attachment.name) + '"', msg.get_payload()[-1].get(u'Content-Disposition')) mimeapp = MIMEApplication('attachment') self.assertEqual(mimeapp.get_payload(), msg.get_payload()[-1].get_payload()) @mock.patch('airflow.utils.email.send_MIME_email') def test_send_bcc_smtp(self, mock_send_mime): attachment = tempfile.NamedTemporaryFile() attachment.write(b'attachment') attachment.seek(0) utils.email.send_email_smtp('to', 'subject', 'content', files=[attachment.name], cc='cc', bcc='bcc') self.assertTrue(mock_send_mime.called) call_args = mock_send_mime.call_args[0] self.assertEqual(configuration.conf.get('smtp', 'SMTP_MAIL_FROM'), call_args[0]) self.assertEqual(['to', 'cc', 'bcc'], call_args[1]) msg = call_args[2] self.assertEqual('subject', msg['Subject']) self.assertEqual(configuration.conf.get('smtp', 'SMTP_MAIL_FROM'), msg['From']) self.assertEqual(2, len(msg.get_payload())) self.assertEqual(u'attachment; filename="' + os.path.basename(attachment.name) + '"', msg.get_payload()[-1].get(u'Content-Disposition')) mimeapp = MIMEApplication('attachment') self.assertEqual(mimeapp.get_payload(), msg.get_payload()[-1].get_payload()) @mock.patch('smtplib.SMTP_SSL') @mock.patch('smtplib.SMTP') def test_send_mime(self, mock_smtp, mock_smtp_ssl): mock_smtp.return_value = mock.Mock() mock_smtp_ssl.return_value = mock.Mock() msg = MIMEMultipart() utils.email.send_MIME_email('from', 'to', msg, dryrun=False) mock_smtp.assert_called_with( configuration.conf.get('smtp', 'SMTP_HOST'), configuration.conf.getint('smtp', 'SMTP_PORT'), ) self.assertTrue(mock_smtp.return_value.starttls.called) mock_smtp.return_value.login.assert_called_with( configuration.conf.get('smtp', 'SMTP_USER'), configuration.conf.get('smtp', 'SMTP_PASSWORD'), ) mock_smtp.return_value.sendmail.assert_called_with('from', 'to', msg.as_string()) self.assertTrue(mock_smtp.return_value.quit.called) @mock.patch('smtplib.SMTP_SSL') @mock.patch('smtplib.SMTP') def test_send_mime_ssl(self, mock_smtp, mock_smtp_ssl): configuration.conf.set('smtp', 'SMTP_SSL', 'True') mock_smtp.return_value = mock.Mock() mock_smtp_ssl.return_value = mock.Mock() utils.email.send_MIME_email('from', 'to', MIMEMultipart(), dryrun=False) self.assertFalse(mock_smtp.called) mock_smtp_ssl.assert_called_with( configuration.conf.get('smtp', 'SMTP_HOST'), configuration.conf.getint('smtp', 'SMTP_PORT'), ) @mock.patch('smtplib.SMTP_SSL') @mock.patch('smtplib.SMTP') def test_send_mime_noauth(self, mock_smtp, mock_smtp_ssl): configuration.conf.remove_option('smtp', 'SMTP_USER') configuration.conf.remove_option('smtp', 'SMTP_PASSWORD') mock_smtp.return_value = mock.Mock() mock_smtp_ssl.return_value = mock.Mock() utils.email.send_MIME_email('from', 'to', MIMEMultipart(), dryrun=False) self.assertFalse(mock_smtp_ssl.called) mock_smtp.assert_called_with( configuration.conf.get('smtp', 'SMTP_HOST'), configuration.conf.getint('smtp', 'SMTP_PORT'), ) self.assertFalse(mock_smtp.login.called) @mock.patch('smtplib.SMTP_SSL') @mock.patch('smtplib.SMTP') def test_send_mime_dryrun(self, mock_smtp, mock_smtp_ssl): utils.email.send_MIME_email('from', 'to', MIMEMultipart(), dryrun=True) self.assertFalse(mock_smtp.called) self.assertFalse(mock_smtp_ssl.called) if __name__ == '__main__': unittest.main()
39.82503
109
0.612984
3aeb69028b43018bd7c0c9a352e77898be418539
16,154
py
Python
comb/tf_model_v1.py
kastnerkyle/tf_and_torch_speechmatch
e9bfa11c741c6955ff8cafcc2afd730cd69f7ab8
[ "BSD-3-Clause" ]
1
2019-07-31T00:47:46.000Z
2019-07-31T00:47:46.000Z
comb/tf_model_v1.py
kastnerkyle/tf_and_torch_speechmatch
e9bfa11c741c6955ff8cafcc2afd730cd69f7ab8
[ "BSD-3-Clause" ]
null
null
null
comb/tf_model_v1.py
kastnerkyle/tf_and_torch_speechmatch
e9bfa11c741c6955ff8cafcc2afd730cd69f7ab8
[ "BSD-3-Clause" ]
null
null
null
from __future__ import print_function import os import argparse import numpy as np import tensorflow as tf from collections import namedtuple import logging import shutil from tfbldr.datasets import rsync_fetch, fetch_ljspeech from tfbldr.datasets import wavfile_caching_mel_tbptt_iterator from tfbldr.utils import next_experiment_path from tfbldr import get_logger from tfbldr import run_loop from tfbldr.nodes import Linear from tfbldr.nodes import Linear from tfbldr.nodes import LSTMCell from tfbldr.nodes import BiLSTMLayer from tfbldr.nodes import SequenceConv1dStack from tfbldr.nodes import Embedding from tfbldr.nodes import GaussianAttentionCell from tfbldr.nodes import DiscreteMixtureOfLogistics from tfbldr.nodes import DiscreteMixtureOfLogisticsCost from tfbldr.nodes import AdditiveGaussianNoise from tfbldr import scan seq_len = 48 batch_size = 10 window_mixtures = 10 cell_dropout = .925 #noise_scale = 8. prenet_units = 128 n_filts = 128 n_stacks = 3 enc_units = 128 dec_units = 512 emb_dim = 15 truncation_len = seq_len cell_dropout_scale = cell_dropout epsilon = 1E-8 forward_init = "truncated_normal" rnn_init = "truncated_normal" #basedir = "/Tmp/kastner/lj_speech/LJSpeech-1.0/" #ljspeech = rsync_fetch(fetch_ljspeech, "leto01") # THESE ARE CANNOT BE PAIRED (SOME MISSING), ITERATOR PAIRS THEM UP BY NAME #wavfiles = ljspeech["wavfiles"] #jsonfiles = ljspeech["jsonfiles"] # THESE HAVE TO BE THE SAME TO ENSURE SPLIT IS CORRECT train_random_state = np.random.RandomState(3122) valid_random_state = np.random.RandomState(3122) fake_random_state = np.random.RandomState(1234) class FakeItr(object): def __init__(self, batch_size, seq_len): self.batch_size = batch_size self.seq_len = seq_len self.vocabulary_sizes=[44, 44] self.n_mel_filters = 80 def next_masked_batch(self): # need to make int "strings" of batch_size, random_len (10-50?) # need to make batches of 256, # dummy batch sizes from validation iterator in training code mels = fake_random_state.randn(self.seq_len, self.batch_size, 80) mel_mask = 0. * mels[..., 0] + 1. text = np.random.randint(0, 44, size=(145, self.batch_size, 1)).astype("float32") text_mask = 0. * text[..., 0] + 1. mask = 0. * text_mask + 1. mask_mask = 0. * text_mask + 1. reset = 0. * mask_mask[0] + 1. reset = reset[:, None] # mels = (256, 64, 80) # mel_mask = (256, 64) # text = (145, 64, 1) # text_mask = (145, 64) # mask = (145, 64) # mask_mask = (145, 64) # reset = (64, 1) return mels, mel_mask, text, text_mask, mask, mask_mask, reset train_itr = FakeItr(batch_size, seq_len) valid_itr = FakeItr(batch_size, seq_len) #train_itr = wavfile_caching_mel_tbptt_iterator(wavfiles, jsonfiles, batch_size, seq_len, stop_index=.95, shuffle=True, symbol_processing="chars_only", random_state=train_random_state) #valid_itr = wavfile_caching_mel_tbptt_iterator(wavfiles, jsonfiles, batch_size, seq_len, start_index=.95, shuffle=True, symbol_processing="chars_only", random_state=valid_random_state) """ for i in range(10000): print(i) mels, mel_mask, text, text_mask, mask, mask_mask, reset = train_itr.next_masked_batch() print("done") """ """ # STRONG CHECK TO ENSURE NO OVERLAP IN TRAIN/VALID for tai in train_itr.all_indices_: assert tai not in valid_itr.all_indices_ for vai in valid_itr.all_indices_: assert vai not in train_itr.all_indices_ """ random_state = np.random.RandomState(1442) # use the max of the two blended types... vocabulary_size = max(train_itr.vocabulary_sizes) output_size = train_itr.n_mel_filters def create_graph(): graph = tf.Graph() with graph.as_default(): tf.set_random_seed(2899) text = tf.placeholder(tf.float32, shape=[None, batch_size, 1]) text_mask = tf.placeholder(tf.float32, shape=[None, batch_size]) #mask = tf.placeholder(tf.float32, shape=[None, batch_size, 1]) #mask_mask = tf.placeholder(tf.float32, shape=[None, batch_size]) mels = tf.placeholder(tf.float32, shape=[None, batch_size, output_size]) mel_mask = tf.placeholder(tf.float32, shape=[None, batch_size]) bias = tf.placeholder_with_default(tf.zeros(shape=[]), shape=[]) cell_dropout = tf.placeholder_with_default(cell_dropout_scale * tf.ones(shape=[]), shape=[]) prenet_dropout = tf.placeholder_with_default(0.5 * tf.ones(shape=[]), shape=[]) bn_flag = tf.placeholder_with_default(tf.zeros(shape=[]), shape=[]) att_w_init = tf.placeholder(tf.float32, shape=[batch_size, 2 * enc_units]) att_k_init = tf.placeholder(tf.float32, shape=[batch_size, window_mixtures]) att_h_init = tf.placeholder(tf.float32, shape=[batch_size, dec_units]) att_c_init = tf.placeholder(tf.float32, shape=[batch_size, dec_units]) h1_init = tf.placeholder(tf.float32, shape=[batch_size, dec_units]) c1_init = tf.placeholder(tf.float32, shape=[batch_size, dec_units]) h2_init = tf.placeholder(tf.float32, shape=[batch_size, dec_units]) c2_init = tf.placeholder(tf.float32, shape=[batch_size, dec_units]) in_mels = mels[:-1, :, :] in_mel_mask = mel_mask[:-1] out_mels = mels[1:, :, :] out_mel_mask = mel_mask[1:] projmel1 = Linear([in_mels], [output_size], prenet_units, dropout_flag_prob_keep=prenet_dropout, name="prenet1", random_state=random_state) projmel2 = Linear([projmel1], [prenet_units], prenet_units, dropout_flag_prob_keep=prenet_dropout, name="prenet2", random_state=random_state) text_char_e, t_c_emb = Embedding(text, vocabulary_size, emb_dim, random_state=random_state, name="text_char_emb") #text_phone_e, t_p_emb = Embedding(text, vocabulary_size, emb_dim, random_state=random_state, # name="text_phone_emb") #text_e = (1. - mask) * text_char_e + mask * text_phone_e text_e = text_char_e # masks are either 0 or 1... use embed + voc size of two so that text and mask embs have same size / same impact on the repr #mask_e, m_emb = Embedding(mask, 2, emb_dim, random_state=random_state, # name="mask_emb") conv_text = SequenceConv1dStack([text_e], [emb_dim], n_filts, bn_flag, n_stacks=n_stacks, kernel_sizes=[(1, 1), (3, 3), (5, 5)], name="enc_conv1", random_state=random_state) # text_mask and mask_mask should be the same, doesn't matter which one we use bitext = BiLSTMLayer([conv_text], [n_filts], enc_units, input_mask=text_mask, name="encode_bidir", init=rnn_init, random_state=random_state) def step(inp_t, inp_mask_t, corr_inp_t, att_w_tm1, att_k_tm1, att_h_tm1, att_c_tm1, h1_tm1, c1_tm1, h2_tm1, c2_tm1): o = GaussianAttentionCell([corr_inp_t], [prenet_units], (att_h_tm1, att_c_tm1), att_k_tm1, bitext, 2 * enc_units, dec_units, att_w_tm1, input_mask=inp_mask_t, conditioning_mask=text_mask, #attention_scale=1. / 10., attention_scale=1., step_op="softplus", name="att", random_state=random_state, cell_dropout=1.,#cell_dropout, init=rnn_init) att_w_t, att_k_t, att_phi_t, s = o att_h_t = s[0] att_c_t = s[1] output, s = LSTMCell([corr_inp_t, att_w_t, att_h_t], [prenet_units, 2 * enc_units, dec_units], h1_tm1, c1_tm1, dec_units, input_mask=inp_mask_t, random_state=random_state, cell_dropout=cell_dropout, name="rnn1", init=rnn_init) h1_t = s[0] c1_t = s[1] output, s = LSTMCell([corr_inp_t, att_w_t, h1_t], [prenet_units, 2 * enc_units, dec_units], h2_tm1, c2_tm1, dec_units, input_mask=inp_mask_t, random_state=random_state, cell_dropout=cell_dropout, name="rnn2", init=rnn_init) h2_t = s[0] c2_t = s[1] return output, att_w_t, att_k_t, att_phi_t, att_h_t, att_c_t, h1_t, c1_t, h2_t, c2_t r = scan(step, [in_mels, in_mel_mask, projmel2], [None, att_w_init, att_k_init, None, att_h_init, att_c_init, h1_init, c1_init, h2_init, c2_init]) output = r[0] att_w = r[1] att_k = r[2] att_phi = r[3] att_h = r[4] att_c = r[5] h1 = r[6] c1 = r[7] h2 = r[8] c2 = r[9] pred = Linear([output], [dec_units], output_size, name="out_proj", random_state=random_state) """ mix, means, lins = DiscreteMixtureOfLogistics([proj], [output_size], n_output_channels=1, name="dml", random_state=random_state) cc = DiscreteMixtureOfLogisticsCost(mix, means, lins, out_mels, 256) """ # correct masking cc = (pred - out_mels) ** 2 #cc = out_mel_mask[..., None] * cc #loss = tf.reduce_sum(tf.reduce_sum(cc, axis=-1)) / tf.reduce_sum(out_mel_mask) loss = tf.reduce_mean(tf.reduce_sum(cc, axis=-1)) learning_rate = 0.0001 #steps = tf.Variable(0.) #learning_rate = tf.train.exponential_decay(0.001, steps, staircase=True, # decay_steps=50000, decay_rate=0.5) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, use_locking=True) grad, var = zip(*optimizer.compute_gradients(loss)) grad, _ = tf.clip_by_global_norm(grad, 10.) #train_step = optimizer.apply_gradients(zip(grad, var), global_step=steps) train_step = optimizer.apply_gradients(zip(grad, var)) things_names = ["mels", "mel_mask", "in_mels", "in_mel_mask", "out_mels", "out_mel_mask", "text", "text_mask", #"mask", #"mask_mask", "bias", "cell_dropout", "prenet_dropout", "bn_flag", "pred", #"mix", "means", "lins", "att_w_init", "att_k_init", "att_h_init", "att_c_init", "h1_init", "c1_init", "h2_init", "c2_init", "att_w", "att_k", "att_phi", "att_h", "att_c", "h1", "c1", "h2", "c2", "loss", "train_step", "learning_rate"] things_tf = [eval(name) for name in things_names] for tn, tt in zip(things_names, things_tf): graph.add_to_collection(tn, tt) train_model = namedtuple('Model', things_names)(*things_tf) return graph, train_model g, vs = create_graph() att_w_init = np.zeros((batch_size, 2 * enc_units)) att_k_init = np.zeros((batch_size, window_mixtures)) att_h_init = np.zeros((batch_size, dec_units)) att_c_init = np.zeros((batch_size, dec_units)) h1_init = np.zeros((batch_size, dec_units)) c1_init = np.zeros((batch_size, dec_units)) h2_init = np.zeros((batch_size, dec_units)) c2_init = np.zeros((batch_size, dec_units)) stateful_args = [att_w_init, att_k_init, att_h_init, att_c_init, h1_init, c1_init, h2_init, c2_init] step_count = 0 def loop(sess, itr, extras, stateful_args): """ global step_count global noise_scale step_count += 1 if step_count > 10000: step_count = 0 if noise_scale == 2: noise_scale = 1. else: noise_scale = noise_scale - 2. if noise_scale < .5: noise_scale = .5 """ mels, mel_mask, text, text_mask, mask, mask_mask, reset = itr.next_masked_batch() in_m = mels[:-1] in_mel_mask = mel_mask[:-1] #noise_block = np.clip(random_state.randn(*in_m.shape), -6, 6) #in_m = in_m + noise_scale * noise_block out_m = mels[1:] out_mel_mask = mel_mask[1:] att_w_init = stateful_args[0] att_k_init = stateful_args[1] att_h_init = stateful_args[2] att_c_init = stateful_args[3] h1_init = stateful_args[4] c1_init = stateful_args[5] h2_init = stateful_args[6] c2_init = stateful_args[7] att_w_init *= reset att_k_init *= reset att_h_init *= reset att_c_init *= reset h1_init *= reset c1_init *= reset h2_init *= reset c2_init *= reset feed = { vs.in_mels: in_m, vs.in_mel_mask: in_mel_mask, vs.out_mels: out_m, vs.out_mel_mask: out_mel_mask, vs.bn_flag: 0., vs.text: text, vs.text_mask: text_mask, #vs.mask: mask, #vs.mask_mask: mask_mask, vs.att_w_init: att_w_init, vs.att_k_init: att_k_init, vs.att_h_init: att_h_init, vs.att_c_init: att_c_init, vs.h1_init: h1_init, vs.c1_init: c1_init, vs.h2_init: h2_init, vs.c2_init: c2_init} outs = [vs.att_w, vs.att_k, vs.att_h, vs.att_c, vs.h1, vs.c1, vs.h2, vs.c2, vs.att_phi, vs.loss, vs.train_step] r = sess.run(outs, feed_dict=feed) att_w_np = r[0] att_k_np = r[1] att_h_np = r[2] att_c_np = r[3] h1_np = r[4] c1_np = r[5] h2_np = r[6] c2_np = r[7] att_phi_np = r[8] l = r[-2] _ = r[-1] # set next inits att_w_init = att_w_np[-1] att_k_init = att_k_np[-1] att_h_init = att_h_np[-1] att_c_init = att_c_np[-1] h1_init = h1_np[-1] c1_init = c1_np[-1] h2_init = h2_np[-1] c2_init = c2_np[-1] stateful_args = [att_w_init, att_k_init, att_h_init, att_c_init, h1_init, c1_init, h2_init, c2_init] return l, None, stateful_args with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) for i in range(100): loop(sess, train_itr, {}, stateful_args) print(i) # #run_loop(sess, # loop, train_itr, # loop, train_itr, # n_steps=1000000, # n_train_steps_per=1000, # train_stateful_args=stateful_args, # n_valid_steps_per=0, # valid_stateful_args=stateful_args)
36.965675
185
0.558314
7c5e33d7d151941010f4798ebd32fc89793b3af0
51
py
Python
pywos/__init__.py
refraction-ray/wos-statistics
bb3a23bdcdb588046df1e852d0b2625071d15634
[ "MIT" ]
8
2019-04-08T09:20:01.000Z
2021-09-09T12:38:18.000Z
pywos/__init__.py
refraction-ray/wos-statistics
bb3a23bdcdb588046df1e852d0b2625071d15634
[ "MIT" ]
null
null
null
pywos/__init__.py
refraction-ray/wos-statistics
bb3a23bdcdb588046df1e852d0b2625071d15634
[ "MIT" ]
3
2019-09-20T01:23:57.000Z
2021-09-09T12:38:19.000Z
__author__ = "refraction-ray" __version__ = "0.0.1"
25.5
29
0.72549
5abe2e15772ec6a27f606fbfd3789f2ecebfe7a3
269
py
Python
language-based/cpp/cpp-rf24-test/transposer/RF24/RPi/pyRF24/setup.py
fjctp/random_code
5cbf73fc34b8f51a093ed47e0db676cadc5cb03a
[ "MIT" ]
5
2017-07-17T21:56:33.000Z
2021-01-17T17:31:10.000Z
language-based/cpp/cpp-rf24-test/transposer/RF24/RPi/pyRF24/setup.py
fjctp/random_code
5cbf73fc34b8f51a093ed47e0db676cadc5cb03a
[ "MIT" ]
null
null
null
language-based/cpp/cpp-rf24-test/transposer/RF24/RPi/pyRF24/setup.py
fjctp/random_code
5cbf73fc34b8f51a093ed47e0db676cadc5cb03a
[ "MIT" ]
1
2017-07-18T20:11:50.000Z
2017-07-18T20:11:50.000Z
#!/usr/bin/env python from distutils.core import setup, Extension module_RF24 = Extension('RF24', libraries = ['rf24-bcm', 'boost_python'], sources = ['pyRF24.cpp']) setup(name='RF24', version='1.0', ext_modules=[module_RF24] )
20.692308
53
0.609665
6924ae8775a1c0635ba576ffcec4f0c0d5d420eb
24,322
py
Python
mangadex_openapi/models/order1.py
ongyx/mangadex_openapi
56a244cf90d884b2589ab2466b44442409a296d7
[ "MIT" ]
null
null
null
mangadex_openapi/models/order1.py
ongyx/mangadex_openapi
56a244cf90d884b2589ab2466b44442409a296d7
[ "MIT" ]
null
null
null
mangadex_openapi/models/order1.py
ongyx/mangadex_openapi
56a244cf90d884b2589ab2466b44442409a296d7
[ "MIT" ]
null
null
null
# coding: utf-8 """ MangaDex API MangaDex is an ad-free manga reader offering high-quality images! This document details our API as it is right now. It is in no way a promise to never change it, although we will endeavour to publicly notify any major change. # Authentication You can login with the `/auth/login` endpoint. On success, it will return a JWT that remains valid for 15 minutes along with a session token that allows refreshing without re-authenticating for 1 month. # Rate limits The API enforces rate-limits to protect our servers against malicious and/or mistaken use. The API keeps track of the requests on an IP-by-IP basis. Hence, if you're on a VPN, proxy or a shared network in general, the requests of other users on this network might affect you. At first, a **global limit of 5 requests per second per IP address** is in effect. > This limit is enforced across multiple load-balancers, and thus is not an exact value but rather a lower-bound that we guarantee. The exact value will be somewhere in the range `[5, 5*n]` (with `n` being the number of load-balancers currently active). The exact value within this range will depend on the current traffic patterns we are experiencing. On top of this, **some endpoints are further restricted** as follows: | Endpoint | Requests per time period | Time period in minutes | |------------------------------------|-------------------------- |------------------------| | `POST /account/create` | 1 | 60 | | `GET /account/activate/{code}` | 30 | 60 | | `POST /account/activate/resend` | 5 | 60 | | `POST /account/recover` | 5 | 60 | | `POST /account/recover/{code}` | 5 | 60 | | `POST /auth/login` | 30 | 60 | | `POST /auth/refresh` | 30 | 60 | | `POST /author` | 10 | 60 | | `PUT /author` | 10 | 1 | | `DELETE /author/{id}` | 10 | 10 | | `POST /captcha/solve` | 10 | 10 | | `POST /chapter/{id}/read` | 300 | 10 | | `PUT /chapter/{id}` | 10 | 1 | | `DELETE /chapter/{id}` | 10 | 1 | | `POST /manga` | 10 | 60 | | `PUT /manga/{id}` | 10 | 60 | | `DELETE /manga/{id}` | 10 | 10 | | `POST /cover` | 10 | 1 | | `PUT /cover/{id}` | 10 | 1 | | `DELETE /cover/{id}` | 10 | 10 | | `POST /group` | 10 | 60 | | `PUT /group/{id}` | 10 | 1 | | `DELETE /group/{id}` | 10 | 10 | | `GET /at-home/server/{id}` | 60 | 1 | Calling these endpoints will further provide details via the following headers about your remaining quotas: | Header | Description | |---------------------------|-----------------------------------------------------------------------------| | `X-RateLimit-Limit` | Maximal number of requests this endpoint allows per its time period | | `X-RateLimit-Remaining` | Remaining number of requests within your quota for the current time period | | `X-RateLimit-Retry-After` | Timestamp of the end of the current time period, as UNIX timestamp | # Captchas Some endpoints may require captchas to proceed, in order to slow down automated malicious traffic. Legitimate users might also be affected, based on the frequency of write requests or due certain endpoints being particularly sensitive to malicious use, such as user signup. Once an endpoint decides that a captcha needs to be solved, a 403 Forbidden response will be returned, with the error code `captcha_required_exception`. The sitekey needed for recaptcha to function is provided in both the `X-Captcha-Sitekey` header field, as well as in the error context, specified as `siteKey` parameter. The captcha result of the client can either be passed into the repeated original request with the `X-Captcha-Result` header or alternatively to the `POST /captcha/solve` endpoint. The time a solved captcha is remembered varies across different endpoints and can also be influenced by individual client behavior. Authentication is not required for the `POST /captcha/solve` endpoint, captchas are tracked both by client ip and logged in user id. If you are logged in, you want to send the session token along, so you validate the captcha for your client ip and user id at the same time, but it is not required. # Reading a chapter using the API ## Retrieving pages from the MangaDex@Home network A valid [MangaDex@Home network](https://mangadex.network) page URL is in the following format: `{server-specific base url}/{temporary access token}/{quality mode}/{chapter hash}/{filename}` There are currently 2 quality modes: - `data`: Original upload quality - `data-saver`: Compressed quality Upon fetching a chapter from the API, you will find 4 fields necessary to compute MangaDex@Home page URLs: | Field | Type | Description | |------------------------------|----------|-----------------------------------| | `.data.id` | `string` | API Chapter ID | | `.data.attributes.hash` | `string` | MangaDex@Home Chapter Hash | | `.data.attributes.data` | `array` | data quality mode filenames | | `.data.attributes.dataSaver` | `array` | data-saver quality mode filenames | Example ```json GET /chapter/{id} { ..., \"data\": { \"id\": \"e46e5118-80ce-4382-a506-f61a24865166\", ..., \"attributes\": { ..., \"hash\": \"e199c7d73af7a58e8a4d0263f03db660\", \"data\": [ \"x1-b765e86d5ecbc932cf3f517a8604f6ac6d8a7f379b0277a117dc7c09c53d041e.png\", ... ], \"dataSaver\": [ \"x1-ab2b7c8f30c843aa3a53c29bc8c0e204fba4ab3e75985d761921eb6a52ff6159.jpg\", ... ] } } } ``` From this point you miss only the base URL to an assigned MangaDex@Home server for your client and chapter. This is retrieved via a `GET` request to `/at-home/server/{ chapter .data.id }`. Example: ```json GET /at-home/server/e46e5118-80ce-4382-a506-f61a24865166 { \"baseUrl\": \"https://abcdefg.hijklmn.mangadex.network:12345/some-token\" } ``` The full URL is the constructed as follows ``` { server .baseUrl }/{ quality mode }/{ chapter .data.attributes.hash }/{ chapter .data.attributes.{ quality mode }.[*] } Examples data quality: https://abcdefg.hijklmn.mangadex.network:12345/some-token/data/e199c7d73af7a58e8a4d0263f03db660/x1-b765e86d5ecbc932cf3f517a8604f6ac6d8a7f379b0277a117dc7c09c53d041e.png base url: https://abcdefg.hijklmn.mangadex.network:12345/some-token quality mode: data chapter hash: e199c7d73af7a58e8a4d0263f03db660 filename: x1-b765e86d5ecbc932cf3f517a8604f6ac6d8a7f379b0277a117dc7c09c53d041e.png data-saver quality: https://abcdefg.hijklmn.mangadex.network:12345/some-token/data-saver/e199c7d73af7a58e8a4d0263f03db660/x1-ab2b7c8f30c843aa3a53c29bc8c0e204fba4ab3e75985d761921eb6a52ff6159.jpg base url: https://abcdefg.hijklmn.mangadex.network:12345/some-token quality mode: data-saver chapter hash: e199c7d73af7a58e8a4d0263f03db660 filename: x1-ab2b7c8f30c843aa3a53c29bc8c0e204fba4ab3e75985d761921eb6a52ff6159.jpg ``` If the server you have been assigned fails to serve images, you are allowed to call the `/at-home/server/{ chapter id }` endpoint again to get another server. Whether successful or not, **please do report the result you encountered as detailed below**. This is so we can pull the faulty server out of the network. ## Report In order to keep track of the health of the servers in the network and to improve the quality of service and reliability, we ask that you call the MangaDex@Home report endpoint after each image you retrieve, whether successfully or not. It is a `POST` request against `https://api.mangadex.network/report` and expects the following payload with our example above: | Field | Type | Description | |-----------------------------|------------|-------------------------------------------------------------------------------------| | `url` | `string` | The full URL of the image | | `success` | `boolean` | Whether the image was successfully retrieved | | `cached ` | `boolean` | `true` iff the server returned an `X-Cache` header with a value starting with `HIT` | | `bytes` | `number` | The size in bytes of the retrieved image | | `duration` | `number` | The time in miliseconds that the complete retrieval (not TTFB) of this image took | Examples herafter. **Success:** ```json POST https://api.mangadex.network/report Content-Type: application/json { \"url\": \"https://abcdefg.hijklmn.mangadex.network:12345/some-token/data/e199c7d73af7a58e8a4d0263f03db660/x1-b765e86d5ecbc932cf3f517a8604f6ac6d8a7f379b0277a117dc7c09c53d041e.png\", \"success\": true, \"bytes\": 727040, \"duration\": 235, \"cached\": true } ``` **Failure:** ```json POST https://api.mangadex.network/report Content-Type: application/json { \"url\": \"https://abcdefg.hijklmn.mangadex.network:12345/some-token/data/e199c7d73af7a58e8a4d0263f03db660/x1-b765e86d5ecbc932cf3f517a8604f6ac6d8a7f379b0277a117dc7c09c53d041e.png\", \"success\": false, \"bytes\": 25, \"duration\": 235, \"cached\": false } ``` While not strictly necessary, this helps us monitor the network's healthiness, and we appreciate your cooperation towards this goal. If no one reports successes and failures, we have no way to know that a given server is slow/broken, which eventually results in broken image retrieval for everyone. # Retrieving Covers from the API ## Construct Cover URLs ### Source (original/best quality) `https://uploads.mangadex.org/covers/{ manga.id }/{ cover.filename }`<br/> The extension can be png, jpeg or gif. Example: `https://uploads.mangadex.org/covers/8f3e1818-a015-491d-bd81-3addc4d7d56a/4113e972-d228-4172-a885-cb30baffff97.jpg` ### <=512px wide thumbnail `https://uploads.mangadex.org/covers/{ manga.id }/{ cover.filename }.512.jpg`<br/> The extension is always jpg. Example: `https://uploads.mangadex.org/covers/8f3e1818-a015-491d-bd81-3addc4d7d56a/4113e972-d228-4172-a885-cb30baffff97.jpg.512.jpg` ### <=256px wide thumbnail `https://uploads.mangadex.org/covers/{ manga.id }/{ cover.filename }.256.jpg`<br/> The extension is always jpg. Example: `https://uploads.mangadex.org/covers/8f3e1818-a015-491d-bd81-3addc4d7d56a/4113e972-d228-4172-a885-cb30baffff97.jpg.256.jpg` ## ℹ️ Where to find Cover filename ? Look at the [Get cover operation](#operation/get-cover) endpoint to get Cover information. Also, if you get a Manga resource, you'll have, if available a `covert_art` relationship which is the main cover id. # Static data ## Manga publication demographic | Value | Description | |------------------|---------------------------| | shounen | Manga is a Shounen | | shoujo | Manga is a Shoujo | | josei | Manga is a Josei | | seinen | Manga is a Seinen | ## Manga status | Value | Description | |------------------|---------------------------| | ongoing | Manga is still going on | | completed | Manga is completed | | hiatus | Manga is paused | | cancelled | Manga has been cancelled | ## Manga reading status | Value | |------------------| | reading | | on_hold | | plan\\_to\\_read | | dropped | | re\\_reading | | completed | ## Manga content rating | Value | Description | |------------------|---------------------------| | safe | Safe content | | suggestive | Suggestive content | | erotica | Erotica content | | pornographic | Pornographic content | ## CustomList visibility | Value | Description | |------------------|---------------------------| | public | CustomList is public | | private | CustomList is private | ## Relationship types | Value | Description | |------------------|--------------------------------| | manga | Manga resource | | chapter | Chapter resource | | cover_art | A Cover Art for a manga `*` | | author | Author resource | | artist | Author resource (drawers only) | | scanlation_group | ScanlationGroup resource | | tag | Tag resource | | user | User resource | | custom_list | CustomList resource | `*` Note, that on manga resources you get only one cover_art resource relation marking the primary cover if there are more than one. By default this will be the latest volume's cover art. If you like to see all the covers for a given manga, use the cover search endpoint for your mangaId and select the one you wish to display. ## Manga links data In Manga attributes you have the `links` field that is a JSON object with some strange keys, here is how to decode this object: | Key | Related site | URL | URL details | |-------|---------------|-----------------------------------------------------------------------------------------------|----------------------------------------------------------------| | al | anilist | https://anilist.co/manga/`{id}` | Stored as id | | ap | animeplanet | https://www.anime-planet.com/manga/`{slug}` | Stored as slug | | bw | bookwalker.jp | https://bookwalker.jp/`{slug}` | Stored has \"series/{id}\" | | mu | mangaupdates | https://www.mangaupdates.com/series.html?id=`{id}` | Stored has id | | nu | novelupdates | https://www.novelupdates.com/series/`{slug}` | Stored has slug | | kt | kitsu.io | https://kitsu.io/api/edge/manga/`{id}` or https://kitsu.io/api/edge/manga?filter[slug]={slug} | If integer, use id version of the URL, otherwise use slug one | | amz | amazon | N/A | Stored as full URL | | ebj | ebookjapan | N/A | Stored as full URL | | mal | myanimelist | https://myanimelist.net/manga/{id} | Store as id | | raw | N/A | N/A | Stored as full URL, untranslated stuff URL (original language) | | engtl | N/A | N/A | Stored as full URL, official english licenced URL | # noqa: E501 OpenAPI spec version: 5.0.21 Contact: mangadexstaff@gmail.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class Order1(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 = { "created_at": "str", "updated_at": "str", "publish_at": "str", "volume": "str", "chapter": "str", } attribute_map = { "created_at": "createdAt", "updated_at": "updatedAt", "publish_at": "publishAt", "volume": "volume", "chapter": "chapter", } def __init__( self, created_at=None, updated_at=None, publish_at=None, volume=None, chapter=None, ): # noqa: E501 """Order1 - a model defined in Swagger""" # noqa: E501 self._created_at = None self._updated_at = None self._publish_at = None self._volume = None self._chapter = None self.discriminator = None if created_at is not None: self.created_at = created_at if updated_at is not None: self.updated_at = updated_at if publish_at is not None: self.publish_at = publish_at if volume is not None: self.volume = volume if chapter is not None: self.chapter = chapter @property def created_at(self): """Gets the created_at of this Order1. # noqa: E501 :return: The created_at of this Order1. # noqa: E501 :rtype: str """ return self._created_at @created_at.setter def created_at(self, created_at): """Sets the created_at of this Order1. :param created_at: The created_at of this Order1. # noqa: E501 :type: str """ allowed_values = ["asc", "desc"] # noqa: E501 if created_at not in allowed_values: raise ValueError( "Invalid value for `created_at` ({0}), must be one of {1}".format( # noqa: E501 created_at, allowed_values ) ) self._created_at = created_at @property def updated_at(self): """Gets the updated_at of this Order1. # noqa: E501 :return: The updated_at of this Order1. # noqa: E501 :rtype: str """ return self._updated_at @updated_at.setter def updated_at(self, updated_at): """Sets the updated_at of this Order1. :param updated_at: The updated_at of this Order1. # noqa: E501 :type: str """ allowed_values = ["asc", "desc"] # noqa: E501 if updated_at not in allowed_values: raise ValueError( "Invalid value for `updated_at` ({0}), must be one of {1}".format( # noqa: E501 updated_at, allowed_values ) ) self._updated_at = updated_at @property def publish_at(self): """Gets the publish_at of this Order1. # noqa: E501 :return: The publish_at of this Order1. # noqa: E501 :rtype: str """ return self._publish_at @publish_at.setter def publish_at(self, publish_at): """Sets the publish_at of this Order1. :param publish_at: The publish_at of this Order1. # noqa: E501 :type: str """ allowed_values = ["asc", "desc"] # noqa: E501 if publish_at not in allowed_values: raise ValueError( "Invalid value for `publish_at` ({0}), must be one of {1}".format( # noqa: E501 publish_at, allowed_values ) ) self._publish_at = publish_at @property def volume(self): """Gets the volume of this Order1. # noqa: E501 :return: The volume of this Order1. # noqa: E501 :rtype: str """ return self._volume @volume.setter def volume(self, volume): """Sets the volume of this Order1. :param volume: The volume of this Order1. # noqa: E501 :type: str """ allowed_values = ["asc", "desc"] # noqa: E501 if volume not in allowed_values: raise ValueError( "Invalid value for `volume` ({0}), must be one of {1}".format( # noqa: E501 volume, allowed_values ) ) self._volume = volume @property def chapter(self): """Gets the chapter of this Order1. # noqa: E501 :return: The chapter of this Order1. # noqa: E501 :rtype: str """ return self._chapter @chapter.setter def chapter(self, chapter): """Sets the chapter of this Order1. :param chapter: The chapter of this Order1. # noqa: E501 :type: str """ allowed_values = ["asc", "desc"] # noqa: E501 if chapter not in allowed_values: raise ValueError( "Invalid value for `chapter` ({0}), must be one of {1}".format( # noqa: E501 chapter, allowed_values ) ) self._chapter = chapter 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 if issubclass(Order1, dict): for key, value in self.items(): result[key] = 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, Order1): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
93.187739
17,143
0.527259
8f5da364a5fd29ef7de20891e0e64a3ca3624985
3,863
py
Python
quorumtoolbox/raft.py
chainstack/quorum-toolbox
e9d25b1118891d27b27bb6f3c8907a805183f873
[ "Apache-2.0" ]
1
2021-06-24T18:03:40.000Z
2021-06-24T18:03:40.000Z
quorumtoolbox/raft.py
chainstack/quorum-toolbox
e9d25b1118891d27b27bb6f3c8907a805183f873
[ "Apache-2.0" ]
5
2019-12-10T03:28:14.000Z
2020-05-28T15:49:59.000Z
quorumtoolbox/raft.py
chainstack/quorum-toolbox
e9d25b1118891d27b27bb6f3c8907a805183f873
[ "Apache-2.0" ]
null
null
null
import json import os from quorumtoolbox.utils import templating from quorumtoolbox.utils.enode_utils import make_enode_id2 from quorumtoolbox.utils.node_utils import make_node_param class Raft: raft_dir_name = 'raft' raft_id_file_name = 'raftid.json' def __init__(self, context, enode_id_geth, # e.g. 'enode://$enode@$geth_ip:$geth_port?discport=$discport' node_state, # 'initial' or 'new' port=50400, # default value in quorum. need to make enode_id. block_time=50, # default value in quorum. mint blocks at this many milliseconds interval peers=None): self.context = context self.enode_id_geth = enode_id_geth self.port = port self.enode_id = make_enode_id2(self.enode_id_geth, self.port) self.block_time = block_time self.node_state = node_state self.peers = [] if peers is None else peers self._raft_id = None self.init_node(self.node_state) self.base_dir = os.path.join(context, self.raft_dir_name) self.raft_id_file = os.path.join(self.base_dir, self.raft_id_file_name) self.write_raft_id() # configuration related to this class instance self.build_config = { 'raft': { 'block_time': self.block_time, 'raft_id': self._raft_id, 'node_state': self.node_state }, 'enode_id': self.enode_id, 'network': { 'port': self.port, 'peers': self.peers }, 'local': { 'raft_id_file': self.raft_id_file } } # configuration related to launching this instance of raft, used in cmd line args when launching geth. # https://github.com/jpmorganchase/quorum/blob/master/raft/doc.md self.launch_params = { 'raft': '--raft', 'rpcapi': make_node_param('--rpcapi', 'raft'), 'raftport': make_node_param('--raftport', self.port), # mint blocks in this many millisecond interval 'raftblocktime': make_node_param('--raftblocktime', self.block_time) } if self._raft_id is not None: self.launch_params['raftjoinexisting'] = make_node_param( '--raftjoinexisting', self._raft_id) # join an existing network with this id def init_node(self, node_state): { 'initial': self.init_initial, 'new': self.init_new }[node_state]() # This node is forming the initial network. RAFT_ID will be automatically assigned by network (based on static-nodes # .json). so, don't bother. def init_initial(self): self._raft_id = None # This node is new to the network and a raft joining id has to be retrieved from peers. def init_new(self): self._raft_id = self.get_raft_id() @property def joining_id(self): return self._raft_id @property def build_configuration(self): return self.build_config @property def launch_parameters(self): return self.launch_params def get_raft_id(self): # moved to orchestrator # mocked return return 0 def write_raft_id(self): if self._raft_id is not None: templating.template_substitute(self.raft_id_file, {'raft_id': self._raft_id}) else: templating.template_substitute(self.raft_id_file, {'raft_id': 'null'}) def get_raft_joining_id(self): raft_joining_id = raft_utils.get_raft_joining_id(self.peers, self.enode_id) return raft_joining_id def sanity_check(self): pass def __str__(self): return json.dumps(self.build_config) def __repr__(self): pass
31.92562
120
0.613513
0971a1a0947763425a7ae66b9ca836cdb8e3e95c
7,563
py
Python
script/old/compare_vcf-0.0.1.py
genepii/seqmet
89fdab79131c861d4a5aae364ecdbeb3a9e0ae23
[ "MIT" ]
null
null
null
script/old/compare_vcf-0.0.1.py
genepii/seqmet
89fdab79131c861d4a5aae364ecdbeb3a9e0ae23
[ "MIT" ]
null
null
null
script/old/compare_vcf-0.0.1.py
genepii/seqmet
89fdab79131c861d4a5aae364ecdbeb3a9e0ae23
[ "MIT" ]
null
null
null
from __future__ import print_function import os import sys import getopt ##Count the number of minor variants in a target vcf reported as major variant in a reference vcf #v0.0.1 def main(argv): global ref global var global con global oup global oud global mode global bed global region global min_depth global min_freq ref = '' var = '' con = '' oup = '' oud = './' mode = ['raw'] bed = '' region = '' min_depth = 20 min_freq = 0.01 try: opts, args = getopt.getopt(argv, 'hr:c:v:o:x:m:b:R:d:f:', ['help', 'ref', 'con', 'var', 'output', 'outdir', 'mode', 'bed', 'region', 'min_depth', 'min_freq']) for opt, arg in opts: if opt in ('-h', '--help'): usage() sys.exit() elif opt in ('-r', '--ref'): ref = arg elif opt in ('-c', '--con'): con = arg elif opt in ('-v', '--var'): var = arg elif opt in ('-o', '--output'): oup = arg elif opt in ('-x', '--outdir'): oud = arg elif opt in ('-m', '--mode'): mode = [] for i in range(len(arg.split(','))): mode.append(arg.split(',')[i]) elif opt in ('-b', '--bed'): bed = arg elif opt in ('-R', '--region'): region = arg elif opt in ('-d', '--min_depth'): min_depth = int(arg) elif opt in ('-f', '--min_freq'): min_freq = float(arg) if ref == '' or con == '' or var == '': usage() sys.exit() if oup == '': oup = var.split("/")[-1].split(".")[0] + '_' + region.split("/")[-1].split(".")[0] except getopt.GetoptError: usage() sys.exit(2) def usage(): print('usage: ' + sys.argv[0] + ' -h --help -r --ref [fasta] --con [vcf] --var [vcf] -o --output [tsv] -m --mode [raw,cov,common,expected] -b --bed [bed] -R --region [bed] -d --min_depth [int] -f --min_freq [float]') if __name__ == '__main__': main(sys.argv[1:]) def count_commented(file): lines = open(file, 'r').read().rstrip('\n').split('\n') count = 0 for line in lines: if line[0] == "#": count += 1 return count flatten = lambda t: [item for sublist in t for item in sublist] seq = [[x.replace('\r\n','\n').split('\n')[0], ''.join(x.replace('\r\n','\n').split('\n')[1:]).replace(' ','')] for x in open(ref, 'r').read().rstrip('\n').split('>')[1:]] cons = open(con, 'r').read().rstrip('\n').split('\n')[count_commented(con):] vas = open(var, 'r').read().rstrip('\n').split('\n')[count_commented(var):] bga = [x.split('\t') for x in open(bed, 'r').read().replace('\r\n','\n').rstrip('\n').split('\n')] depth = [] for i in range(len(bga)): depth.append([int(bga[i][3]) for x in range(int(bga[i][1]),int(bga[i][2]))]) depth = flatten(depth) if region != '': treg = [x.split('\t') for x in open(region, 'r').read().replace('\r\n','\n').rstrip('\n').split('\n')] reg = [] for i in range(len(treg)): reg.append([int(x) for x in range(int(treg[i][1]),int(treg[i][2]))]) reg = flatten(reg) else: reg = [] vas_chrom, vas_pos, vas_ref, vas_alt, vas_af, cons_chrom, cons_pos, cons_ref, cons_alt, cons_af = ([] for i in range(10)) temp = [] exp = [] common = 0 expected = 0 for i in range(len(vas)): vas_chrom.append(vas[i].split('\t')[0]) vas_pos.append(int(vas[i].split('\t')[1])-1) vas_ref.append(vas[i].split('\t')[3]) vas_alt.append(vas[i].split('\t')[4]) vas_af.append(float(vas[i].split('\t')[7].split(';')[3].split('=')[1])) for i in range(len(cons)): cons_chrom.append(cons[i].split('\t')[0]) cons_pos.append(int(cons[i].split('\t')[1])-1) cons_ref.append(cons[i].split('\t')[3]) cons_alt.append(cons[i].split('\t')[4]) cons_af.append(float(cons[i].split('\t')[7].split(';')[3].split('=')[1])) for i in range(len(cons_chrom)): if cons_alt[i][0] == '-': cons_temp = cons_ref[i] cons_ref[i] = cons_ref[i] + cons_alt[i][1:] cons_alt[i] = cons_temp if cons_alt[i][0] == '+': cons_alt[i] = cons_ref[i] + cons_alt[i][1:] for i in range(len(vas_chrom)): if vas_alt[i][0] == '-': vas_temp = vas_ref[i] vas_ref[i] = vas_ref[i] + vas_alt[i][1:] vas_alt[i] = vas_temp if vas_alt[i][0] == '+': vas_alt[i] = vas_ref[i] + vas_alt[i][1:] for i in range(len(cons_chrom)): if (cons_pos[i] in reg or reg == []) and depth[cons_pos[i]] >= min_depth and float(cons_af[i]) >= min_freq: if float(cons_af[i]) >= 0.5: if cons_pos[i] in vas_pos: vas_index = vas_pos.index(cons_pos[i]) if cons_alt[i] == vas_alt[vas_index] and float(vas_af[vas_index]) >= 0.5: pass #print([cons_pos[i], cons_alt[i], vas_alt[vas_index], "old"]) else: expected += 1 exp.append([cons_pos[i], cons_alt[i], vas_alt[vas_index]]) else: expected += 1 exp.append([cons_pos[i], cons_alt[i], "ref1"]) for i in range(len(vas_chrom)): if (vas_pos[i] in reg or reg == []) and depth[vas_pos[i]] >= min_depth and float(vas_af[i]) >= min_freq: if float(vas_af[i]) < 0.5: if vas_pos[i] in cons_pos: cons_index = cons_pos.index(vas_pos[i]) if vas_alt[i] == cons_alt[cons_index] and float(cons_af[cons_index]) >= 0.5: common += 1 temp.append([vas_pos[i], vas_alt[i], cons_alt[cons_index]]) elif vas_alt[i] == seq[[x[0] for x in seq].index(vas_chrom[i])][1][vas_pos[i]:vas_pos[i]+len(vas_alt[i])] and vas_ref[i] != seq[[x[0] for x in seq].index(vas_chrom[i])][1][vas_pos[i]:vas_pos[i]+len(vas_ref[i])]: common += 1 temp.append([vas_pos[i], vas_alt[i], "ref2"]) else: if vas_pos[i] in cons_pos: cons_index = cons_pos.index(vas_pos[i]) if vas_alt[i] != cons_alt[cons_index] and float(cons_af[cons_index]) >= 0.5: expected += 1 exp.append([vas_pos[i], vas_alt[i], cons_alt[cons_index]]) else: expected += 1 exp.append([vas_pos[i], vas_alt[i], "ref3"]) exp = sorted(exp, key=lambda i: i[0]) print(exp) print (temp) if "cov" in mode: w = open(oud + oup + "_cov.tsv", 'a+') if expected > 0: w.write(con.split("/")[-1].split(".")[0] + "\t" + str(round(float(common)/float(expected), 2)) + "\n") else: w.write(con.split("/")[-1].split(".")[0] + "\t0.0\n") w.close() if "common" in mode: w = open(oud + oup + "_common.tsv", 'a+') w.write(con.split("/")[-1].split(".")[0] + "\t" + str(common) + "\n") w.close() if "expected" in mode: w = open(oud + oup + "_expected.tsv", 'a+') w.write(con.split("/")[-1].split(".")[0] + "\t" + str(expected) + "\n") w.close() if "raw" in mode: w = open(oud + oup + "_raw.tsv", 'a+') w.write(con.split("/")[-1].split(".")[0] + "\t" + str(common) + "//" + str(expected) + "\n") w.close() print (str(common) + "//" + str(expected))
38.005025
224
0.492662
32c9df6086648fadb4c805373b98205b72ccf085
263
py
Python
applications/MeshMovingApplication/tests/run_cpp_unit_tests.py
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/MeshMovingApplication/tests/run_cpp_unit_tests.py
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/MeshMovingApplication/tests/run_cpp_unit_tests.py
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
from KratosMultiphysics import * from KratosMultiphysics.MeshMovingApplication import * def run(): Tester.SetVerbosity(Tester.Verbosity.PROGRESS) # TESTS_OUTPUTS Tester.RunTestSuite("MeshMovingApplicationFastSuite") if __name__ == '__main__': run()
26.3
66
0.78327
e11b0a9986536f0a40f34d3edd5b249b71b48c00
742
py
Python
{{ cookiecutter.package_name }}/{{ cookiecutter.module_name }}/routers/default.py
triaxtec/fastapi-serverless-cookiecutter
fe5ca7ebb0fbe47ee55adbe93431b02862e62544
[ "MIT" ]
15
2020-05-09T16:34:29.000Z
2021-06-05T14:26:34.000Z
example/example/routers/default.py
triaxtec/fastapi-serverless-cookiecutter
fe5ca7ebb0fbe47ee55adbe93431b02862e62544
[ "MIT" ]
null
null
null
example/example/routers/default.py
triaxtec/fastapi-serverless-cookiecutter
fe5ca7ebb0fbe47ee55adbe93431b02862e62544
[ "MIT" ]
1
2020-08-13T18:40:55.000Z
2020-08-13T18:40:55.000Z
from functools import lru_cache from pathlib import Path from fastapi import APIRouter, Depends, FastAPI from markdown import markdown from starlette.responses import HTMLResponse router = APIRouter() def register_router(app: FastAPI) -> None: """ Register this router against the application """ app.include_router(router) @lru_cache def _get_changelog_html() -> bytes: changelog_path: Path = Path(__file__).parent.parent / "CHANGELOG.md" _changelog_html = markdown(changelog_path.read_text()) return _changelog_html @router.get("/changelog", response_class=HTMLResponse) async def changelog() -> HTMLResponse: """ Display the changelog for this API """ return HTMLResponse(content=_get_changelog_html())
27.481481
72
0.762803
992ae8fc9f3ab9f4a8c386747556ffa62ed5e7d1
17,748
py
Python
abs_templates_ec/routing/fill.py
boblinchuan/BAG2_TEMPLATES_EC
e0e4a41c1780edb035cd619b9cea2e27e3fc5f51
[ "BSD-3-Clause" ]
1
2020-06-02T22:41:46.000Z
2020-06-02T22:41:46.000Z
abs_templates_ec/routing/fill.py
boblinchuan/BAG2_TEMPLATES_EC
e0e4a41c1780edb035cd619b9cea2e27e3fc5f51
[ "BSD-3-Clause" ]
12
2018-10-23T18:08:37.000Z
2022-02-24T10:51:34.000Z
abs_templates_ec/routing/fill.py
boblinchuan/BAG2_TEMPLATES_EC
e0e4a41c1780edb035cd619b9cea2e27e3fc5f51
[ "BSD-3-Clause" ]
18
2018-07-14T01:36:09.000Z
2021-05-25T18:38:00.000Z
# -*- coding: utf-8 -*- """This module defines dummy/power fill related templates.""" from typing import TYPE_CHECKING, Dict, Set, Any, Tuple, List import numpy as np from bag.util.search import BinaryIterator from bag.layout.util import BBox from bag.layout.template import TemplateBase from ..analog_core.base import AnalogBase, AnalogBaseInfo if TYPE_CHECKING: from bag.layout.objects import Instance from bag.layout.template import TemplateDB class PowerFill(TemplateBase): """A power fill template. Parameters ---------- temp_db : TemplateDB the template database. lib_name : str the layout library name. params : Dict[str, Any] the parameter values. used_names : Set[str] a set of already used cell names. **kwargs : dictionary of optional parameters. See documentation of :class:`bag.layout.template.TemplateBase` for details. """ def __init__(self, temp_db, lib_name, params, used_names, **kwargs): # type: (TemplateDB, str, Dict[str, Any], Set[str], **kwargs) -> None TemplateBase.__init__(self, temp_db, lib_name, params, used_names, **kwargs) @classmethod def get_params_info(cls): # type: () -> Dict[str, str] return dict( fill_config='the fill configuration dictionary.', top_layer='the top fill layer.', bot_layer='the bottom fill layer.', show_pins='True to show pins.', ) @classmethod def get_default_param_values(cls): # type: () -> Dict[str, Any] return dict( top_layer=None, show_pins=True, ) def get_layout_basename(self): bot_lay = self.params['bot_layer'] top_lay = self.params['top_layer'] if top_lay is None: top_lay = bot_lay + 1 return 'power_fill_m%dm%d' % (bot_lay, top_lay) def draw_layout(self): # type: () -> None fill_config = self.params['fill_config'] bot_layer = self.params['bot_layer'] top_layer = self.params['top_layer'] show_pins = self.params['show_pins'] if top_layer is None: top_layer = bot_layer + 1 blk_w, blk_h = self.grid.get_fill_size(top_layer, fill_config, unit_mode=True) bnd_box = BBox(0, 0, blk_w, blk_h, self.grid.resolution, unit_mode=True) self.set_size_from_bound_box(top_layer, bnd_box) self.array_box = bnd_box vdd_list, vss_list = None, None for lay in range(bot_layer, top_layer + 1): fill_width, fill_space, space, space_le = fill_config[lay] vdd_list, vss_list = self.do_power_fill(lay, space, space_le, vdd_warrs=vdd_list, vss_warrs=vss_list, fill_width=fill_width, fill_space=fill_space, unit_mode=True) if lay == bot_layer: self.add_pin('VDD_b', vdd_list, show=False) self.add_pin('VSS_b', vss_list, show=False) self.add_pin('VDD', vdd_list, show=show_pins) self.add_pin('VSS', vss_list, show=show_pins) @classmethod def get_fill_orient(cls, orient_mode): if orient_mode == 0: return 'R0' elif orient_mode == 1: return 'MY' elif orient_mode == 2: return 'MX' elif orient_mode == 3: return 'R180' else: raise ValueError('Unknown orientation mode: %d' % orient_mode) @classmethod def add_fill_blocks(cls, template, # type: TemplateBase bound_box, # type: BBox fill_config, # type: Dict[int, Tuple[int, int, int, int]] bot_layer, # type: int top_layer, # type: int orient_mode=0, # type: int ): # type: (...) -> List[List[Instance]] # TODO: This method does not work when if fill size changes as layer changes. # TODO: Fix in the future. # number of wire types per fill block ntype = 2 # error checking if top_layer <= bot_layer: raise ValueError('Must have top_layer > bot_layer.') grid = template.grid blk_w, blk_h = grid.get_fill_size(top_layer, fill_config, unit_mode=True) xl = bound_box.left_unit yb = bound_box.bottom_unit xr = bound_box.right_unit yt = bound_box.top_unit if xl % blk_w != 0 or xr % blk_w != 0 or yb % blk_h != 0 or yt % blk_h != 0: raise ValueError('%s is not on power fill grid.' % bound_box) # figure out where we can draw fill blocks. tot_w = xr - xl tot_h = yt - yb nx = tot_w // blk_w ny = tot_h // blk_h use_fill_list = [] shape = (nx, ny) inst_info_list2 = [] for layer in range(bot_layer, top_layer + 1): fill_w, fill_sp, sp, sp_le = fill_config[layer] cur_dir = grid.get_direction(layer) cur_pitch = grid.get_track_pitch(layer, unit_mode=True) fill_pitch = fill_w + fill_sp is_horiz = cur_dir == 'x' uf_mat = np.ones(shape, dtype=bool) if is_horiz: perp_dir = 'y' blk_dim = blk_w num_tr = tot_h // (cur_pitch * fill_pitch) tr_c0 = yb spx = sp_le spy = sp uf_mat_set = uf_mat.transpose() else: perp_dir = 'x' blk_dim = blk_h num_tr = tot_w // (cur_pitch * fill_pitch) tr_c0 = xl spx = sp spy = sp_le uf_mat_set = uf_mat cur_tr = grid.coord_to_track(layer, tr_c0, unit_mode=True) + fill_pitch / 2 for idx in range(num_tr): blk_idx = idx // ntype wl, wu = grid.get_wire_bounds(layer, cur_tr, width=fill_w, unit_mode=True) test_box = bound_box.with_interval(perp_dir, wl, wu, unit_mode=True) for block_box in template.blockage_iter(layer, test_box, spx=spx, spy=spy): bl, bu = block_box.get_interval(cur_dir, unit_mode=True) nstart = max(bl - tr_c0, 0) // blk_dim nstop = max(bu - tr_c0, 0) // blk_dim uf_mat_set[blk_idx, nstart:nstop + 1] = False cur_tr += fill_pitch if layer > bot_layer: prev_uf_mat = use_fill_list[-1] uf_tot = prev_uf_mat & uf_mat inst_info_list = [] for x0, y0, nx, ny in cls._get_fill_mosaics(uf_tot): inst_info_list.append((x0, y0, nx, ny)) inst_info_list2.append(inst_info_list) use_fill_list.append(uf_mat) inst_params = dict( fill_config=fill_config, show_pins=False ) xinc = 0 if (orient_mode & 1 == 0) else 1 yinc = 0 if (orient_mode & 2 == 0) else 1 inst_list2 = [] orient = cls.get_fill_orient(orient_mode) for idx, inst_info_list in enumerate(inst_info_list2): inst_list = [] inst_params['bot_layer'] = bot_layer + idx master = template.new_template(params=inst_params, temp_cls=PowerFill) for x0, y0, nx, ny in inst_info_list: loc = xl + (x0 + xinc) * blk_w, yb + (y0 + yinc) * blk_h inst = template.add_instance(master, loc=loc, orient=orient, nx=nx, ny=ny, spx=blk_w, spy=blk_h, unit_mode=True) inst_list.append(inst) inst_list2.append(inst_list) return inst_list2 @classmethod def _get_fill_mosaics(cls, uf_mat): # TODO: use Eppestein's Polygon dissection instead of greedy algorithm nx, ny = uf_mat.shape idx_mat = np.full((nx, ny, 2), -1) for xidx in range(nx): for yidx in range(ny): if uf_mat[xidx, yidx]: if xidx > 0 and idx_mat[xidx - 1, yidx, 1] == yidx: cur_xl = idx_mat[xidx, yidx, 0] = idx_mat[xidx - 1, yidx, 0] idx_mat[xidx - 1, yidx, :] = -1 else: cur_xl = idx_mat[xidx, yidx, 0] = xidx if yidx > 0 and idx_mat[xidx, yidx - 1, 0] == cur_xl: cur_yb = idx_mat[xidx, yidx, 1] = idx_mat[xidx, yidx - 1, 1] idx_mat[xidx, yidx - 1, :] = -1 if xidx > 0 and idx_mat[xidx - 1, yidx, 1] == cur_yb: idx_mat[xidx, yidx, 0] = idx_mat[xidx - 1, yidx, 0] idx_mat[xidx - 1, yidx, :] = -1 else: idx_mat[xidx, yidx, 1] = yidx x_list, y_list = np.nonzero(idx_mat[:, :, 0] >= 0) for xidx, yidx in zip(x_list, y_list): x0, y0 = idx_mat[xidx, yidx, :] nx = xidx - x0 + 1 ny = yidx - y0 + 1 yield x0, y0, nx, ny class DecapFillCore(AnalogBase): """A decap cell used for power fill Parameters ---------- temp_db : TemplateDB the template database. lib_name : str the layout library name. params : Dict[str, Any] the parameter values. used_names : Set[str] a set of already used cell names. **kwargs : dictionary of optional parameters. See documentation of :class:`bag.layout.template.TemplateBase` for details. """ def __init__(self, temp_db, lib_name, params, used_names, **kwargs): # type: (TemplateDB, str, Dict[str, Any], Set[str], **kwargs) -> None AnalogBase.__init__(self, temp_db, lib_name, params, used_names, **kwargs) @classmethod def get_params_info(cls): # type: () -> Dict[str, str] return dict( lch='channel length, in meters.', ptap_w='NMOS substrate width, in meters/number of fins.', ntap_w='PMOS substrate width, in meters/number of fins.', wp='PMOS width.', wn='NMOS width.', thp='PMOS threshold.', thn='NMOS threshold.', nx='number of horizontal blocks of fill.', ny='number of vertical blocks of fill.', fill_config='the fill configuration dictionary.', top_layer='Top power fill layer', sup_width='Supply track width.', options='other AnalogBase options', show_pins='True to create pin labels.', ) @classmethod def get_default_param_values(cls): # type: () -> Dict[str, Any] return dict( sup_width=2, options=None, show_pins=True, ) def get_layout_basename(self): lay = self.params['top_layer'] nx = self.params['nx'] ny = self.params['ny'] return 'decap_fill_core_lay%d_%dx%d' % (lay, nx, ny) def draw_layout(self): # type: () -> None lch = self.params['lch'] ptap_w = self.params['ptap_w'] ntap_w = self.params['ntap_w'] wp = self.params['wp'] wn = self.params['wn'] thp = self.params['thp'] thn = self.params['thn'] nx = self.params['nx'] ny = self.params['ny'] fill_config = self.params['fill_config'] top_layer = self.params['top_layer'] sup_width = self.params['sup_width'] options = self.params['options'] show_pins = self.params['show_pins'] if options is None: options = {} # get power fill size w_tot, h_tot = self.grid.get_fill_size(top_layer, fill_config, unit_mode=True) w_tot *= nx h_tot *= ny # get number of fingers info = AnalogBaseInfo(self.grid, lch, 0, top_layer=top_layer) bin_iter = BinaryIterator(2, None) while bin_iter.has_next(): fg_cur = bin_iter.get_next() w_cur = info.get_placement_info(fg_cur).tot_width if w_cur < w_tot: bin_iter.save() bin_iter.up() elif w_cur > w_tot: bin_iter.down() else: bin_iter.save() break fg_tot = bin_iter.get_last_save() if fg_tot is None: raise ValueError('Decaep cell width exceed fill width.') self.draw_base(lch, fg_tot, ptap_w, ntap_w, [wn], [thn], [wp], [thp], ng_tracks=[1], pg_tracks=[1], n_orientations=['MX'], p_orientations=['R0'], top_layer=top_layer, min_height=h_tot, **options) if self.bound_box.height_unit > h_tot: raise ValueError('Decap cell height exceed fill height.') nmos = self.draw_mos_conn('nch', 0, 0, fg_tot, 0, 0) pmos = self.draw_mos_conn('pch', 0, 0, fg_tot, 2, 2, gate_pref_loc='s') vss_tid = self.make_track_id('pch', 0, 'g', 0) vdd_tid = self.make_track_id('nch', 0, 'g', 0) self.connect_to_substrate('ptap', nmos['d']) self.connect_to_substrate('ntap', pmos['s']) vss_g = self.connect_to_tracks([nmos['s'], pmos['g']], vss_tid) vdd_g = self.connect_to_tracks([pmos['d'], nmos['g']], vdd_tid) vss, vdd = self.fill_dummy(vdd_width=sup_width, vss_width=sup_width) vss.append(vss_g) vdd.append(vdd_g) self.add_pin('VSS', vss, label='VSS:', show=show_pins) self.add_pin('VDD', vdd, label='VDD:', show=show_pins) class DecapFill(TemplateBase): """A power fill cell containing decap Parameters ---------- temp_db : TemplateDB the template database. lib_name : str the layout library name. params : Dict[str, Any] the parameter values. used_names : Set[str] a set of already used cell names. **kwargs : dictionary of optional parameters. See documentation of :class:`bag.layout.template.TemplateBase` for details. """ def __init__(self, temp_db, lib_name, params, used_names, **kwargs): # type: (TemplateDB, str, Dict[str, Any], Set[str], **kwargs) -> None TemplateBase.__init__(self, temp_db, lib_name, params, used_names, **kwargs) @classmethod def get_params_info(cls): # type: () -> Dict[str, str] return dict( fill_config='the fill configuration dictionary.', decap_params='decap parameters.', nx='number of horizontal blocks of fill.', ny='number of vertical blocks of fill.', top_layer='Top power fill layer', show_pins='True to show pins.', ) @classmethod def get_default_param_values(cls): # type: () -> Dict[str, Any] return dict( show_pins=True, ) def get_layout_basename(self): lay = self.params['top_layer'] nx = self.params['nx'] ny = self.params['ny'] return 'decap_fill_lay%d_%dx%d' % (lay, nx, ny) def draw_layout(self): # type: () -> None fill_config = self.params['fill_config'] decap_params = self.params['decap_params'] nx = self.params['nx'] ny = self.params['ny'] top_layer = self.params['top_layer'] show_pins = self.params['show_pins'] params = decap_params.copy() params['nx'] = nx params['ny'] = ny params['fill_config'] = fill_config params['top_layer'] = top_layer master_cap = self.new_template(params=params, temp_cls=DecapFillCore) w_blk, h_blk = self.grid.get_fill_size(top_layer, fill_config, unit_mode=True) w_tot = w_blk * nx h_tot = h_blk * ny dx = (w_tot - master_cap.bound_box.width_unit) // 2 cap_inst = self.add_instance(master_cap, 'XCAP', (dx, 0), unit_mode=True) hm_layer = master_cap.mos_conn_layer + 1 if top_layer <= hm_layer: raise ValueError('top layer must be at least %d' % (hm_layer + 1)) # set size res = self.grid.resolution self.array_box = bnd_box = BBox(0, 0, w_tot, h_tot, res, unit_mode=True) self.set_size_from_bound_box(top_layer, bnd_box) self.add_cell_boundary(bnd_box) # do power fill ym_layer = hm_layer + 1 vdd_list = cap_inst.get_all_port_pins('VDD') vss_list = cap_inst.get_all_port_pins('VSS') fill_width, fill_space, space, space_le = fill_config[ym_layer] vdd_list, vss_list = self.do_power_fill(ym_layer, space, space_le, vdd_warrs=vdd_list, vss_warrs=vss_list, fill_width=fill_width, fill_space=fill_space, unit_mode=True) if top_layer > ym_layer: params = dict(fill_config=fill_config, show_pins=False) inst = None for bot_layer in range(ym_layer, top_layer): params['bot_layer'] = bot_layer master = self.new_template(params=params, temp_cls=PowerFill) inst = self.add_instance(master, 'X%d' % bot_layer, nx=nx, ny=ny, spx=w_blk, spy=h_blk, unit_mode=True) vdd_list = self.connect_wires(inst.get_all_port_pins('VDD')) vss_list = self.connect_wires(inst.get_all_port_pins('VSS')) self.add_pin('VDD', vdd_list, show=show_pins) self.add_pin('VSS', vss_list, show=show_pins)
37.842217
94
0.557809
d17eb7e052c5058835c8b47a0dee17e359633385
2,396
py
Python
gae/tests/FIXTURES.py
benletchford/stratego.io
040d8d0775594f531d588700128e86f744be2dff
[ "MIT" ]
29
2015-12-03T04:11:05.000Z
2022-01-21T15:34:37.000Z
gae/tests/FIXTURES.py
benletchford/stratego.io
040d8d0775594f531d588700128e86f744be2dff
[ "MIT" ]
10
2020-04-12T16:01:40.000Z
2022-02-26T07:56:55.000Z
gae/tests/FIXTURES.py
benletchford/stratego.io
040d8d0775594f531d588700128e86f744be2dff
[ "MIT" ]
9
2016-03-13T11:54:02.000Z
2021-11-28T04:28:51.000Z
import json import copy SETUP = [ [ {'rank': '1', 'side': 3}, {'rank': '2', 'side': 3}, {'rank': '3', 'side': 3}, {'rank': '3', 'side': 3}, {'rank': '4', 'side': 3}, {'rank': '4', 'side': 3}, {'rank': '4', 'side': 3}, {'rank': '5', 'side': 3}, {'rank': '5', 'side': 3}, {'rank': '5', 'side': 3} ], [ {'rank': '5', 'side': 3}, {'rank': '6', 'side': 3}, {'rank': '6', 'side': 3}, {'rank': '6', 'side': 3}, {'rank': '6', 'side': 3}, {'rank': '7', 'side': 3}, {'rank': '7', 'side': 3}, {'rank': '7', 'side': 3}, {'rank': '7', 'side': 3}, {'rank': '8', 'side': 3} ], [ {'rank': '8', 'side': 3}, {'rank': '8', 'side': 3}, {'rank': '8', 'side': 3}, {'rank': '8', 'side': 3}, {'rank': '9', 'side': 3}, {'rank': '9', 'side': 3}, {'rank': '9', 'side': 3}, {'rank': '9', 'side': 3}, {'rank': '9', 'side': 3}, {'rank': '9', 'side': 3} ], [ {'rank': '9', 'side': 3}, {'rank': '9', 'side': 3}, {'rank': 'S', 'side': 3}, {'rank': 'B', 'side': 3}, {'rank': 'B', 'side': 3}, {'rank': 'B', 'side': 3}, {'rank': 'B', 'side': 3}, {'rank': 'B', 'side': 3}, {'rank': 'B', 'side': 3}, {'rank': 'F', 'side': 3} ] ] SETUP_0 = copy.deepcopy(SETUP) for row in SETUP_0: for cell in row: cell['side'] = 0 SETUP_1 = copy.deepcopy(SETUP) SETUP_1 = SETUP_1[::-1] for i in xrange(0, len(SETUP_1)): SETUP_1[i] = SETUP_1[i][::-1] for row in SETUP_1: for cell in row: cell['side'] = 1 DEFAULT_GAME = SETUP_1 + [ [0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0] ] + SETUP_0 MARSHAL = { 'rank': '1', 'side': 0 } GENERAL = { 'rank': '2', 'side': 0 } COLONEL = { 'rank': '3', 'side': 0 } MAJOR = { 'rank': '4', 'side': 0 } CAPTAIN = { 'rank': '5', 'side': 0 } LIEUTENANT = { 'rank': '6', 'side': 0 } SERGEANT = { 'rank': '7', 'side': 0 } MINER = { 'rank': '8', 'side': 0 } SCOUT = { 'rank': '9', 'side': 0 } SPY = { 'rank': 'S', 'side': 0 } FLAG = { 'rank': 'F', 'side': 0 } BOMB = { 'rank': 'B', 'side': 0 }
18.015038
39
0.34975
45051d34467ef1e78cf83176b967ab4504b0a086
627
py
Python
backend/manage.py
ecto0310/groupware
e1c9f76b19e6d1f6782f8e2b287ff75d1351fa83
[ "MIT" ]
3
2020-03-23T19:18:00.000Z
2021-04-12T04:01:17.000Z
backend/manage.py
ecto0310/groupware
e1c9f76b19e6d1f6782f8e2b287ff75d1351fa83
[ "MIT" ]
95
2020-03-07T12:29:38.000Z
2022-02-17T22:44:07.000Z
backend/manage.py
ecto0310/groupware
e1c9f76b19e6d1f6782f8e2b287ff75d1351fa83
[ "MIT" ]
2
2021-12-27T16:50:36.000Z
2021-12-27T16:53:12.000Z
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'digigru.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
28.5
73
0.682616
8a86e9dedef1815cfb6f54f846da9292da04752e
333
py
Python
ics_demo/main.py
lielongxingkong/ics-demo
21a08945f3983eb409916a7380549f74e3ba5171
[ "MIT" ]
null
null
null
ics_demo/main.py
lielongxingkong/ics-demo
21a08945f3983eb409916a7380549f74e3ba5171
[ "MIT" ]
null
null
null
ics_demo/main.py
lielongxingkong/ics-demo
21a08945f3983eb409916a7380549f74e3ba5171
[ "MIT" ]
null
null
null
import tornado.ioloop import tornado.web from ics_demo.dao import init_db from ics_demo.remote_services import init_proxy from ics_demo.routes import urls application = tornado.web.Application(urls) if __name__ == "__main__": init_db() init_proxy() application.listen(8888) tornado.ioloop.IOLoop.instance().start()
23.785714
47
0.774775
99b2a7994bb66178b4ae8e195e8a71e4ee9137c0
7,111
py
Python
Lab/4/Dynamics/lagrangian_dynamics_example.py
rparak/Programming-for-robots-and-manipulators-VRM
40157b39de410a3daa8a59bdce11d865d14f321c
[ "MIT" ]
1
2021-04-09T20:38:52.000Z
2021-04-09T20:38:52.000Z
Lab/4/Dynamics/lagrangian_dynamics_example.py
rparak/Programming-for-robots-and-manipulators-VRM
40157b39de410a3daa8a59bdce11d865d14f321c
[ "MIT" ]
null
null
null
Lab/4/Dynamics/lagrangian_dynamics_example.py
rparak/Programming-for-robots-and-manipulators-VRM
40157b39de410a3daa8a59bdce11d865d14f321c
[ "MIT" ]
5
2021-04-30T17:56:01.000Z
2022-03-30T10:09:00.000Z
""" ## =========================================================================== ## MIT License Copyright (c) 2020 Roman Parak 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. ## =========================================================================== ## Author : Roman Parak Email : Roman.Parak@outlook.com Github : https://github.com/rparak File Name: lagrangian_dynamics_example.py ## =========================================================================== ## """ # System (Default Lib.) import sys # Numpy (Array computing Lib.) [pip3 install numpy] import numpy as np # Mtaplotlib (Visualization Lib.) [pip3 install matplotlib] import matplotlib.pyplot as plt # Integrate a system of ordinary differential equations (ODE) [pip3 install scipy] from scipy.integrate import odeint class Dynamics_Ctrl(object): def __init__(self, L, m, time, dt): # << PUBLIC >> # # Arm Length [m] self.L = [L[0], L[1]] # Arm Length (1/2) - Center of Gravity [m] self.lg = [L[0]/2, L[1]/2] # Mass [kg] self.m = [m[0], m[1]] # Moment of Invertia [kg.m^2] self.I = [(1/3)*(m[0])*(L[0]**2), (1/3)*(m[1])*(L[1]**2)] # Gravitational acceleration [m/s^2] self.g = 9.81 # Initial Time Parameters (Calculation) self.t = np.arange(0.0, time, dt) # << PRIVATE >> # # Axes and Label initialization. self.__ax = [0, 0, 0, 0] self.__y_label = [r'$\dot\theta_1$', r'$\ddot\theta_1$', r'$\dot\theta_2$', r'$\ddot\theta_2$'] # Display (Plot) variables. self.__plt = plt self.__fig, ((self.__ax[0], self.__ax[1]), (self.__ax[2], self.__ax[3])) = self.__plt.subplots(2, 2) def __lagrangian_dynamics(self, input_p, time): """ Description: For many applications with fixed-based robots we need to find a multi-body dynamics formulated as: M(\theta)\ddot\theta + b(\theta, \dot\theta) + g(\theta) = \tau M(\theta) -> Generalized mass matrix (orthogonal). \theta,\dot\theta,\ddot\theta -> Generalized position, velocity and acceleration vectors. b(\theta, \dot\theta) -> Coriolis and centrifugal terms. g(\theta) -> Gravitational terms. \tau -> External generalized forces. Euler-Lagrange equation: L = T - U T -> Kinetic Energy (Translation + Rotation Part): (1/2) * m * v^2 + (1/2) * I * \omega^2 -> with moment of invertia U -> Potential Energy: m * g * h Args: (1) input_p [Float Array]: Initial position of the Robot (2 Joints) -> Theta_{1, 2} and 1_Derivation Theta_{1,2} (2) time [Float]: Derivation of the Time. Returns: (1): param 1, param 3 [Float]: 1_Derivation Theta_{1,2} (2): param 2, param 4 [Float]: 2_Derivation Theta_{1,2} """ theta_1 = input_p[0]; theta_2 = input_p[2] dtheta_1 = input_p[1]; dtheta_2 = input_p[3] # Generalized mass matrix -> M(\theta) M_Mat = np.matrix([ [self.I[0] + self.I[1] + self.m[0] * (self.lg[0]**2) + self.m[1] * ((self.L[0]**2) + (self.lg[1]**2) + 2 * self.L[0] * self.lg[1] * np.cos(theta_2)), self.I[1] + self.m[1] * ((self.lg[1]**2) + self.L[0] * self.lg[1] * np.cos(theta_2))], [self.I[1] + self.m[1] * ((self.lg[1]**2) + self.L[0] * self.lg[1] * np.cos(theta_2)), self.I[1] + self.m[1] * (self.lg[1]**2)] ]) # Coriolis and centrifugal terms -> b(\theta, \dot\theta) b_Mat = np.matrix([ [(-1) * self.m[1] * self.L[0] * self.lg[1] * dtheta_2 * (2 * dtheta_1 + dtheta_2) * np.sin(theta_2)], [self.m[1] * self.L[0] * self.lg[1] * (dtheta_1**2) *np.sin(theta_2)] ]) # Gravitational terms -> g(\theta) g_Mat = np.matrix([ [self.m[0] * self.g * self.lg[0] * np.cos(theta_1) + self.m[1] * self.g * (self.L[0] * np.cos(theta_1) + self.lg[1] * np.cos(theta_1 + theta_2))], [self.m[1] * self.g * self.lg[1] * np.cos(theta_1 + theta_2)] ]) # \tau -> External generalized forces. tau_Mat = np.matrix([[0.0], [0.0]]) # Ordinary Differential Equations (ODE) -> From Motion Equation # {\ddotTheta_1, \ddotTheta_2} ode_r = np.linalg.inv(M_Mat).dot(-b_Mat - g_Mat) + tau_Mat return [dtheta_1, ode_r[0][0], dtheta_2, ode_r[1][0]] def display_result(self, input_p): """ Description: Function for calculating and displaying the results of Lagrangian Dynamics Calculation. Args: (1) input_p [Float Array]: Initial position of the Robot (2 Joints) -> Theta_{1, 2} and 1_Derivation Theta_{1,2} """ calc_r = odeint(self.__lagrangian_dynamics, input_p, self.t) self.__fig.suptitle('Lagrangian Dynamics: Example', fontsize = 50, fontweight ='normal') for i in range(len(self.__ax)): self.__ax[i].plot(self.t, calc_r[:, i]) self.__ax[i].grid() self.__ax[i].set_xlabel(r'time [s]', fontsize=20) self.__ax[i].set_ylabel(self.__y_label[i], fontsize=20) # Set additional parameters for successful display of the robot environment self.__plt.show() def main(): # Initialization of the Class (Control Dynamics - Lagrangian) # Input: # (1) Length of Arms (Link 1, Link2) [Float Array] # (2) Mass # (3) Time [INT] # (4) Derivation of the Time [Float] # Example: # x = Dynamics_Ctrl([1.0, 1.0], [1.25, 2.0], 10, 0.1) lD_c = Dynamics_Ctrl([0.3, 0.25], [1.0, 1.0], 10, 0.01) # Initial position of the Robot (2 Joints) -> Theta_{1, 2} and 1_Derivation Theta_{1,2} initial_p = [0.1*np.pi, 0.0, 0.1*np.pi, 0.0] # Display the result of the calculation: # The figure with the resulting 1_Derivation Theta_{1,2}, 2_Derivation Theta_{1,2} lD_c.display_result(initial_p) if __name__ == '__main__': sys.exit(main())
43.895062
249
0.577697
0cb6495e0f846d64a917c60cd170b9e1e48764af
868
py
Python
python/soma_workflow/clean_server.py
denisri/soma-workflow
bc6f2f50d34437e86e850cb0d05ff26b041d560d
[ "CECILL-B" ]
null
null
null
python/soma_workflow/clean_server.py
denisri/soma-workflow
bc6f2f50d34437e86e850cb0d05ff26b041d560d
[ "CECILL-B" ]
null
null
null
python/soma_workflow/clean_server.py
denisri/soma-workflow
bc6f2f50d34437e86e850cb0d05ff26b041d560d
[ "CECILL-B" ]
null
null
null
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import ''' @author: Jinpeng LI @contact: mr.li.jinpeng@gmail.com @organization: I2BM, Neurospin, Gif-sur-Yvette, France @organization: CATI, France @organization: U{IFR 49<http://www.ifr49.org>} @license: U{CeCILL version 2<http://www.cecill.info/licences/Licence_CeCILL_V2-en.html>} ''' ''' start to check the requirement on the server side ''' import os import sys resName = None i = 0 while i < len(sys.argv): if sys.argv[i] == "-r": resName = sys.argv[i + 1] break i = i + 1 lines2cmd = [ "kill $(ps -ef | grep 'python -m soma_workflow.start_database_server' | grep '%s' \ | grep -v grep | awk '{print $2}')" % (resName), "rm ~/.soma-workflow.cfg" ] for line2cmd in lines2cmd: os.system("echo '%s' " % (line2cmd)) os.system(line2cmd)
20.186047
88
0.644009
6a2b82ca881c58611fff3bca5df1fee1f5c86a2f
418
py
Python
configs/mobilenet_v2/pspnet_m-v2-d8_512x1024_80k_cityscapes.py
Xlinford/mmsegmentation
8b444de5e6db2af2538a73a93ac75204f5c3bb2f
[ "Apache-2.0" ]
null
null
null
configs/mobilenet_v2/pspnet_m-v2-d8_512x1024_80k_cityscapes.py
Xlinford/mmsegmentation
8b444de5e6db2af2538a73a93ac75204f5c3bb2f
[ "Apache-2.0" ]
null
null
null
configs/mobilenet_v2/pspnet_m-v2-d8_512x1024_80k_cityscapes.py
Xlinford/mmsegmentation
8b444de5e6db2af2538a73a93ac75204f5c3bb2f
[ "Apache-2.0" ]
null
null
null
_base_ = '../pspnet/pspnet_r101-d8_512x1024_80k_cityscapes.py' model = dict( pretrained='mmcls://mobilenet_v2', backbone=dict( _delete_=True, type='MobileNetV2', widen_factor=1., strides=(1, 2, 2, 1, 1, 1, 1), dilations=(1, 1, 1, 2, 2, 4, 4), out_indices=(1, 2, 4, 6)), decode_head=dict(in_channels=320), auxiliary_head=dict(in_channels=96))
32.153846
63
0.583732
8a8d0ed340effd4b711673ee77a305bf0989fdc6
1,186
py
Python
simple_linear_regression/utils.py
awesome-archive/Machine-Learning-with-Python
898ebbf2d7c780cb5a89bad51d0b7e043e25879f
[ "MIT" ]
942
2019-01-19T18:56:49.000Z
2022-03-31T19:09:56.000Z
simple_linear_regression/utils.py
skylaronomics/Machine-Learning-with-Python
186a6f38f6719e5610e0143aecdf170c842ff107
[ "MIT" ]
4
2019-01-22T15:17:47.000Z
2019-08-25T14:02:44.000Z
simple_linear_regression/utils.py
skylaronomics/Machine-Learning-with-Python
186a6f38f6719e5610e0143aecdf170c842ff107
[ "MIT" ]
176
2019-01-21T10:19:52.000Z
2022-03-02T20:10:27.000Z
from helpers.stats import correlation, standard_deviation, mean, de_mean def predict(alpha, beta, x_i): return beta * x_i + alpha def error(alpha, beta, x_i, y_i): return y_i - predict(alpha, beta, x_i) def sum_of_squared_errors(alpha, beta, x, y): return sum(error(alpha, beta, x_i, y_i) ** 2 for x_i, y_i in zip(x, y)) def least_squares_fit(x, y): beta = correlation(x, y) * standard_deviation(y) / standard_deviation(x) alpha = mean(y) - beta * mean(x) return alpha, beta def total_sum_of_squares(y): """The total squared variation of y_i's from their mean""" return sum(v ** 2 for v in de_mean(y)) def r_squared(alpha, beta, x, y): """the fraction of variation in y captured by the model""" return 1 - sum_of_squared_errors(alpha, beta, x, y) / total_sum_of_squares(y) def squared_error(x_i, y_i, theta): alpha, beta = theta return error(alpha, beta, x_i, y_i) ** 2 def squared_error_gradient(x_i, y_i, theta): alpha, beta = theta return [-2 * error(alpha, beta, x_i, y_i), # alpha partial derivative -2 * error(alpha, beta, x_i, y_i) * x_i] # beta partial derivative
26.355556
82
0.653457
b6f3a07f10a9cf08ac0889af13af388ba2842c7d
9,533
py
Python
var/spack/repos/builtin/packages/py-dask/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2020-08-13T15:24:33.000Z
2021-10-18T18:38:19.000Z
var/spack/repos/builtin/packages/py-dask/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
6
2022-02-26T11:44:34.000Z
2022-03-12T12:14:50.000Z
var/spack/repos/builtin/packages/py-dask/package.py
carlabguillen/spack
7070bb892f9bdb5cf9e76e0eecd64f6cc5f4695c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2020-09-15T02:37:59.000Z
2020-09-21T04:34:38.000Z
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyDask(PythonPackage): """Dask is a flexible parallel computing library for analytics.""" homepage = "https://github.com/dask/dask/" url = "https://pypi.io/packages/source/d/dask/dask-1.1.0.tar.gz" maintainers = ['skosukhin'] version('2.16.0', sha256='2af5b0dcd48ce679ce0321cf91de623f4fe376262789b951fefa3c334002f350') version('1.2.2', sha256='5e7876bae2a01b355d1969b73aeafa23310febd8c353163910b73e93dc7e492c') version('1.1.2', sha256='93b355b9a9c9a3ddbb39fab99d5759aad5cfd346f4520b87788970e80cf97256') version('1.1.0', sha256='e76088e8931b326c05a92d2658e07b94a6852b42c13a7560505a8b2354871454') version('0.17.4', sha256='c111475a3d1f8cba41c8094e1fb1831c65015390dcef0308042a11a9606a2f6d') version('0.8.1', sha256='43deb1934cd033668e5e60b735f45c9c3ee2813f87bd51c243f975e55267fa43') variant('array', default=True, description='Install requirements for dask.array') variant('bag', default=True, description='Install requirements for dask.bag') variant('dataframe', default=True, description='Install requirements for dask.dataframe') variant('distributed', default=True, description='Install requirements for dask.distributed') variant('diagnostics', default=False, description='Install requirements for dask.diagnostics') variant('delayed', default=True, description='Install requirements for dask.delayed (dask.imperative)') variant('yaml', default=True, description='Ensure support for YAML configuration files') conflicts('+distributed', when='@:0.4.0,0.7.6:0.8.1') conflicts('+diagnostics', when='@:0.5.0') conflicts('+yaml', when='@:0.17.5') depends_on('python@2.7:2.8,3.5:', type=('build', 'run')) depends_on('python@3.5:', type=('build', 'run'), when='@2.0.0:') depends_on('python@3.6:', type=('build', 'run'), when='@2.7.0:') depends_on('py-setuptools', type='build') depends_on('py-pytest@3.1.0:', type='test') depends_on('py-requests', type='test') depends_on('py-pytest-runner', type='test') # Requirements for dask.array depends_on('py-numpy@1.10.4:', type=('build', 'run'), when='+array') depends_on('py-numpy@1.11.0:', type=('build', 'run'), when='@0.17.3: +array') depends_on('py-numpy@1.13.0:', type=('build', 'run'), when='@1.2.1: +array') depends_on('py-toolz', type=('build', 'run'), when='+array') depends_on('py-toolz@0.7.2:', type=('build', 'run'), when='@0.7.0: +array') depends_on('py-toolz@0.7.3:', type=('build', 'run'), when='@0.14.1: +array') depends_on('py-toolz@0.8.2:', type=('build', 'run'), when='@2.13.0: +array') # Requirements for dask.bag depends_on('py-dill', type=('build', 'run'), when='@:0.7.5 +bag') depends_on('py-cloudpickle', type=('build', 'run'), when='@0.7.6: +bag') depends_on('py-cloudpickle@0.2.1:', type=('build', 'run'), when='@0.8.2: +bag') depends_on('py-cloudpickle@0.2.2:', type=('build', 'run'), when='@2.13.0: +bag') depends_on('py-fsspec@0.3.3:', type=('build', 'run'), when='@2.2.0: +bag') depends_on('py-fsspec@0.5.1:', type=('build', 'run'), when='@2.5.0: +bag') depends_on('py-fsspec@0.6.0:', type=('build', 'run'), when='@2.8.0: +bag') depends_on('py-toolz', type=('build', 'run'), when='+bag') depends_on('py-toolz@0.7.2:', type=('build', 'run'), when='@0.7.0: +bag') depends_on('py-toolz@0.7.3:', type=('build', 'run'), when='@0.14.1: +bag') depends_on('py-toolz@0.8.2:', type=('build', 'run'), when='@2.13.0: +bag') depends_on('py-partd', type=('build', 'run'), when='+bag') depends_on('py-partd@0.3.2:', type=('build', 'run'), when='@0.6.0: +bag') depends_on('py-partd@0.3.3:', type=('build', 'run'), when='@0.9.0: +bag') depends_on('py-partd@0.3.5:', type=('build', 'run'), when='@0.10.2: +bag') depends_on('py-partd@0.3.6:', type=('build', 'run'), when='@0.12.0: +bag') depends_on('py-partd@0.3.7:', type=('build', 'run'), when='@0.13.0: +bag') depends_on('py-partd@0.3.8:', type=('build', 'run'), when='@0.15.0: +bag') depends_on('py-partd@0.3.10:', type=('build', 'run'), when='@2.0.0: +bag') # Requirements for dask.dataframe depends_on('py-numpy@1.10.4:', type=('build', 'run'), when='+dataframe') depends_on('py-numpy@1.11.0:', type=('build', 'run'), when='@0.17.3: +dataframe') depends_on('py-numpy@1.13.0:', type=('build', 'run'), when='@1.2.1: +dataframe') depends_on('py-pandas@0.16.0:', type=('build', 'run'), when='+dataframe') depends_on('py-pandas@0.18.0:', type=('build', 'run'), when='@0.9.0: +dataframe') depends_on('py-pandas@0.19.0:', type=('build', 'run'), when='@0.14.0: +dataframe') depends_on('py-pandas@0.21.0:', type=('build', 'run'), when='@1.2.1: +dataframe') depends_on('py-pandas@0.23.0:', type=('build', 'run'), when='@2.11.0: +dataframe') depends_on('py-toolz', type=('build', 'run'), when='+dataframe') depends_on('py-toolz@0.7.2:', type=('build', 'run'), when='@0.7.0: +dataframe') depends_on('py-toolz@0.7.3:', type=('build', 'run'), when='@0.14.1: +dataframe') depends_on('py-toolz@0.8.2:', type=('build', 'run'), when='@2.13.0: +dataframe') depends_on('py-partd', type=('build', 'run'), when='+dataframe') depends_on('py-partd@0.3.2:', type=('build', 'run'), when='@0.6.0: +dataframe') depends_on('py-partd@0.3.3:', type=('build', 'run'), when='@0.9.0: +dataframe') depends_on('py-partd@0.3.5:', type=('build', 'run'), when='@0.10.2: +dataframe') depends_on('py-partd@0.3.7:', type=('build', 'run'), when='@0.13.0: +dataframe') depends_on('py-partd@0.3.8:', type=('build', 'run'), when='@0.15.0: +dataframe') depends_on('py-partd@0.3.10:', type=('build', 'run'), when='@2.0.0: +dataframe') depends_on('py-cloudpickle@0.2.1:', type=('build', 'run'), when='@0.8.2:2.6.0 +dataframe') depends_on('py-fsspec@0.3.3:', type=('build', 'run'), when='@2.2.0: +dataframe') depends_on('py-fsspec@0.5.1:', type=('build', 'run'), when='@2.5.0: +dataframe') depends_on('py-fsspec@0.6.0:', type=('build', 'run'), when='@2.8.0: +dataframe') # Requirements for dask.distributed depends_on('py-dill', type=('build', 'run'), when='@:0.7.5 +distributed') depends_on('py-pyzmq', type=('build', 'run'), when='@:0.7.5 +distributed') depends_on('py-distributed', type=('build', 'run'), when='@0.8.2: +distributed') depends_on('py-distributed@1.9:', type=('build', 'run'), when='@0.9.0: +distributed') depends_on('py-distributed@1.10:', type=('build', 'run'), when='@0.10.0: +distributed') depends_on('py-distributed@1.14:', type=('build', 'run'), when='@0.12.0: +distributed') depends_on('py-distributed@1.15:', type=('build', 'run'), when='@0.13.0: +distributed') depends_on('py-distributed@1.16:', type=('build', 'run'), when='@0.14.1: +distributed') depends_on('py-distributed@1.20:', type=('build', 'run'), when='@0.16.0: +distributed') depends_on('py-distributed@1.21:', type=('build', 'run'), when='@0.17.0: +distributed') depends_on('py-distributed@1.22:', type=('build', 'run'), when='@0.18.0: +distributed') depends_on('py-distributed@2.0:', type=('build', 'run'), when='@2.0.0: +distributed') # Requirements for dask.diagnostics depends_on('py-bokeh', type=('build', 'run'), when='+diagnostics') depends_on('py-bokeh@1.0.0:', type=('build', 'run'), when='@2.0.0: +diagnostics') # Requirements for dask.delayed depends_on('py-cloudpickle@0.2.1:', type=('build', 'run'), when='@2,7.0: +delayed') depends_on('py-cloudpickle@0.2.2:', type=('build', 'run'), when='@2.13.0: +delayed') depends_on('py-toolz@0.7.2:', type=('build', 'run'), when='@0.8.1: +delayed') depends_on('py-toolz@0.7.3:', type=('build', 'run'), when='@0.14.1: +delayed') depends_on('py-toolz@0.8.2:', type=('build', 'run'), when='@2.13.0: +delayed') # Support for YAML configuration files depends_on('py-pyyaml', type=('build', 'run'), when='+yaml') @property def import_modules(self): modules = ['dask'] if self.spec.satisfies('@0.9.0:'): modules.append('dask.bytes') if self.spec.satisfies('@:0.20.2'): modules.append('dask.store') if '+array' in self.spec: modules.append('dask.array') if '+bag' in self.spec: modules.append('dask.bag') if self.spec.satisfies('@:0.7.5 +distributed'): modules.append('dask.distributed') if '+dataframe' in self.spec: modules.append('dask.dataframe') if self.spec.satisfies('@0.8.2:'): modules.append('dask.dataframe.tseries') if self.spec.satisfies('@0.12.0:'): modules.append('dask.dataframe.io') if '+diagnostics' in self.spec: modules.append('dask.diagnostics') return modules
56.744048
111
0.584916
0e64d8059adcdcc5e280a38434e13289a75819ad
87
py
Python
haas/tests/compat.py
itziakos/haas
93a2e886f66d7fb40f39305032cad6614fcc52a1
[ "BSD-3-Clause" ]
4
2017-10-10T06:45:35.000Z
2021-02-27T09:44:16.000Z
haas/tests/compat.py
itziakos/haas
93a2e886f66d7fb40f39305032cad6614fcc52a1
[ "BSD-3-Clause" ]
34
2015-02-24T17:04:15.000Z
2017-01-05T12:35:14.000Z
haas/tests/compat.py
itziakos/haas
93a2e886f66d7fb40f39305032cad6614fcc52a1
[ "BSD-3-Clause" ]
4
2018-03-05T19:05:19.000Z
2019-12-11T08:42:22.000Z
try: from unittest import mock # noqa except ImportError: import mock # noqa
17.4
37
0.689655
15730b993c708ebe347397c0edc36e778cad4dbb
1,663
py
Python
Tests/test_EMBL_unittest.py
amblina/biopython
5045a7a3e86d5b32e0eaab941ab35daac86c59f8
[ "PostgreSQL" ]
3
2021-08-17T15:28:41.000Z
2022-02-12T06:43:22.000Z
Tests/test_EMBL_unittest.py
amblina/biopython
5045a7a3e86d5b32e0eaab941ab35daac86c59f8
[ "PostgreSQL" ]
32
2016-11-21T07:38:21.000Z
2017-08-16T13:00:03.000Z
Tests/test_EMBL_unittest.py
amblina/biopython
5045a7a3e86d5b32e0eaab941ab35daac86c59f8
[ "PostgreSQL" ]
8
2016-11-24T18:57:35.000Z
2022-01-16T08:15:25.000Z
# Copyright 2015 by Kai Blin. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import unittest import warnings from os import path from Bio import SeqIO class EMBLTests(unittest.TestCase): def test_embl_content_after_co(self): """Test an AssertionError is thrown by content after a CO line""" def parse_content_after_co(): rec = SeqIO.read(path.join('EMBL', 'xx_after_co.embl'), 'embl') self.assertRaises(AssertionError, parse_content_after_co) try: parse_content_after_co() except AssertionError as e: self.assertEqual(str(e), "Unexpected content after SQ or CO line: 'XX'") else: self.assertTrue(False, "Error message without explanation raised by content after CO line") def test_embl_0_line(self): """Test SQ line with 0 length sequence""" # Biopython 1.67 and older would parse this file with a warning: # 'Expected sequence length 1740, found 1744 (TIR43YW1_CE).' and # the coordinates 1740 added to the sequence as four extra letters. with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") rec = SeqIO.read(path.join('EMBL', 'embl_with_0_line.embl'), 'embl') self.assertEqual(len(w), 0, "Unexpected parser warnings: " + "\n".join(str(warn.message) for warn in w)) self.assertEqual(len(rec), 1740) if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) unittest.main(testRunner=runner)
38.674419
116
0.677691
1c1b841469504e5cc7702e81177d0526d85bac19
3,629
py
Python
.history/Missions_to_Mars/scrape_mars_20200812112856.py
ermiasgelaye/web-scraping-challenge
f99c3436dfb0169595c46dae7733d90e21385cc6
[ "ADSL" ]
null
null
null
.history/Missions_to_Mars/scrape_mars_20200812112856.py
ermiasgelaye/web-scraping-challenge
f99c3436dfb0169595c46dae7733d90e21385cc6
[ "ADSL" ]
null
null
null
.history/Missions_to_Mars/scrape_mars_20200812112856.py
ermiasgelaye/web-scraping-challenge
f99c3436dfb0169595c46dae7733d90e21385cc6
[ "ADSL" ]
2
2020-11-02T08:12:16.000Z
2021-05-17T21:45:42.000Z
from splinter import Browser from bs4 import BeautifulSoup as bs import pandas as pd import time import re # This is for debugging def savetofile(contents): file = open('_temporary.txt',"w",encoding="utf-8") file.write(contents) file.close() def scrape(): executable_path = {"executable_path": "chromedriver"} browser = Browser("chrome", **executable_path, headless=False) # NASA Mars News url = 'https://mars.nasa.gov/news/' browser.visit(url) time.sleep(3) html = browser.html soup = bs(html, 'html.parser') slides = soup.find_all('li', class_='slide') content_title = slides[0].find('div', class_='content_title') news_title = content_title.text.strip() article_teaser_body = slides[0].find('div', class_='article_teaser_body') news_p = article_teaser_body.text.strip() # JPL Mars Space Images base_url = 'https://www.jpl.nasa.gov' url = base_url + '/spaceimages/?search=&category=Mars' browser.visit(url) time.sleep(1) html = browser.html soup = bs(html, 'html.parser') featured_image_url = base_url + soup.find('a',class_='button fancybox')['data-fancybox-href'] # Mars Weather url = 'https://twitter.com/marswxreport?lang=en' browser.visit(url) time.sleep(3) weather_html = browser.html soup = bs(weather_html, "html.parser") # print(weathersoup.prettify()) mars_tweets = [soup.find_all('p', class_="TweetTextSize"), soup.find_all('span', class_="css-901oao css-16my406 r-1qd0xha r-ad9z0x r-bcqeeo r-qvutc0")] mars_weather=[] for tweets in mars_tweets: mars_tweet = tweets for tweet in mars_tweet: if 'InSight' in tweet.text: mars_weather = tweet.text if tweet.a in tweet: mars_weather = mars_weather.strip(tweet.a.text) break # Mars facts url = 'https://space-facts.com/mars/' browser.visit(url) # not necessary, but added for checking the operation time.sleep(1) dfs = pd.read_html(url) for df in dfs: try: df = df.rename(columns={0: "Description", 1: "Value"}) df = df.set_index("Description") marsfacts_html = df.to_html().replace('\n', '') # df.to_html('marsfacts.html') # to save to a file to test break except: continue # Mars Hemispheres base_url = 'https://astrogeology.usgs.gov' url = base_url + '/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' browser.visit(url) time.sleep(1) html = browser.html soup = bs(html, 'html.parser') items = soup.find_all('div', class_='item') urls = [] titles = [] for item in items: urls.append(base_url + item.find('a')['href']) titles.append(item.find('h3').text.strip()) img_urls = [] for oneurl in urls: browser.visit(oneurl) time.sleep(1) html = browser.html soup = bs(html, 'html.parser') oneurl = base_url+soup.find('img',class_='wide-image')['src'] img_urls.append(oneurl) hemisphere_image_urls = [] for i in range(len(titles)): hemisphere_image_urls.append({'title':titles[i],'img_url':img_urls[i]}) # Assigning scraped data to a page marspage = {} marspage["news_title"] = news_title marspage["news_p"] = news_p marspage["featured_image_url"] = featured_image_url marspage["mars_weather"] = mars_weather marspage["marsfacts_html"] = marsfacts_html marspage["hemisphere_image_urls"] = hemisphere_image_urls return marspage
28.131783
155
0.63213
1d6017390c3c32c6b03e85d4ce8f8875cf229c0e
3,708
py
Python
pilot/control/payloads/eventservice.py
yesw2000/pilot2
96228c886e36913c141c4e95722dabb4b6733932
[ "Apache-2.0" ]
null
null
null
pilot/control/payloads/eventservice.py
yesw2000/pilot2
96228c886e36913c141c4e95722dabb4b6733932
[ "Apache-2.0" ]
null
null
null
pilot/control/payloads/eventservice.py
yesw2000/pilot2
96228c886e36913c141c4e95722dabb4b6733932
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # 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 # # Authors: # - Wen Guan, wen.guan@cern.ch, 2017-2018 # - Paul Nilsson, paul.nilsson@cern.ch, 2021 import os import time from pilot.common import exception from pilot.control.payloads import generic from pilot.eventservice.workexecutor.workexecutor import WorkExecutor import logging logger = logging.getLogger(__name__) class Executor(generic.Executor): def __init__(self, args, job, out, err, traces): super(Executor, self).__init__(args, job, out, err, traces) def run_payload(self, job, cmd, out, err): """ (add description) :param job: job object. :param cmd: (unused in ES mode) :param out: stdout file object. :param err: stderr file object. :return: """ self.pre_setup(job) # get the payload command from the user specific code pilot_user = os.environ.get('PILOT_USER', 'atlas').lower() user = __import__('pilot.user.%s.common' % pilot_user, globals(), locals(), [pilot_user], 0) # Python 2/3 self.post_setup(job) self.utility_before_payload(job) self.utility_with_payload(job) try: executable = user.get_payload_command(job) except exception.PilotException: logger.fatal('could not define payload command') return None logger.info("payload execution command: %s" % executable) try: payload = {'executable': executable, 'workdir': job.workdir, 'output_file': out, 'error_file': err, 'job': job} logger.debug("payload: %s" % payload) logger.info("Starting EventService WorkExecutor") executor_type = self.get_executor_type() executor = WorkExecutor(args=executor_type) executor.set_payload(payload) executor.start() logger.info("EventService WorkExecutor started") logger.info("ESProcess started with pid: %s" % executor.get_pid()) job.pid = executor.get_pid() if job.pid: job.pgrp = os.getpgid(job.pid) self.utility_after_payload_started(job) except Exception as e: logger.error('could not execute: %s' % str(e)) return None return executor def get_executor_type(self): """ Get the executor type. This is usually the 'generic' type, which means normal event service. It can also be 'raythena' if specified in the Pilot options. :return: executor type dictionary. """ # executor_type = 'hpo' if job.is_hpo else os.environ.get('PILOT_ES_EXECUTOR_TYPE', 'generic') # return {'executor_type': executor_type} return {'executor_type': os.environ.get('PILOT_ES_EXECUTOR_TYPE', 'generic')} def wait_graceful(self, args, proc): """ (add description) :param args: :param proc: :return: """ t1 = time.time() while proc.is_alive(): if args.graceful_stop.is_set(): logger.debug("Graceful stop is set, stopping work executor") proc.stop() break if time.time() > t1 + 300: # 5 minutes logger.info("Process is still running") t1 = time.time() time.sleep(2) while proc.is_alive(): time.sleep(2) exit_code = proc.get_exit_code() return exit_code
31.423729
123
0.607335
4e48b56268cd5de32e8a29e856002b3c0e6d3482
9,509
py
Python
src/SGAN.py
PranavEranki/Semi-Supervised-GANs
705c59a07bd1aeefeec86dfa85f9fcee78e5c78f
[ "MIT" ]
1
2021-01-18T14:40:35.000Z
2021-01-18T14:40:35.000Z
src/SGAN.py
PranavEranki/Semi-Supervised-GANs
705c59a07bd1aeefeec86dfa85f9fcee78e5c78f
[ "MIT" ]
null
null
null
src/SGAN.py
PranavEranki/Semi-Supervised-GANs
705c59a07bd1aeefeec86dfa85f9fcee78e5c78f
[ "MIT" ]
null
null
null
# coding: utf-8 # In[25]: import argparse import os import numpy as np import math import torchvision.transforms as transforms from torchvision.utils import save_image from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch os.makedirs('images', exist_ok=True) # In[2]: ''' Set Defaults ''' num_epochs = 200 batch_size = 64 num_classes = 10 # number of classes for dataset lr = 0.0002 b1 = 0.5 # adam: decay of first order momentum of gradient b2 = 0.999 # adam: decay of first order momentum of gradient n_cpu = 8 # number of cpu threads to use during batch generation latent_dim = 100 # dimensionality of the latent space img_size = 32 # size of each image dimension channels = 1 # number of output image channels sample_interval = 400 # interval between image sampling # In[3]: # Set cuda if torch.cuda.is_available(): cuda = True else: cuda = False # In[4]: def weights_init_normal(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.zero_() # In[5]: class Generator(nn.Module): def __init__(self): super(Generator, self).__init__() self.label_emb = nn.Embedding(num_classes, latent_dim) self.init_size = img_size // 4 # Initial size before upsampling self.linear = nn.Sequential( nn.Linear(latent_dim, 128*self.init_size**2), ) self.conv1 = nn.Sequential( nn.BatchNorm2d(128), nn.Upsample(scale_factor=2), nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(128, 0.8), nn.LeakyReLU(0.2, inplace=True), nn.Upsample(scale_factor=2) ) self.conv2 = nn.Sequential( nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64, 0.8), nn.LeakyReLU(0.2, inplace=True) ) self.conv3 = nn.Sequential( nn.Conv2d(in_channels=64, out_channels=channels, kernel_size=3, stride=1, padding=1), nn.Tanh() ) def forward(self, noise): out = self.linear(noise) out = out.view(out.shape[0], 128, self.init_size, self.init_size) img = self.conv1(out) img = self.conv2(img) img = self.conv3(img) return img # In[6]: class Discriminator(nn.Module): def __init__(self): super(Discriminator, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(in_channels=channels, out_channels=16, kernel_size=3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0.25), ) self.conv2 = nn.Sequential( nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0.25), nn.BatchNorm2d(num_features=32, eps=0.8) ) self.conv3 = nn.Sequential( nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0.25), nn.BatchNorm2d(num_features=64, eps=0.8) ) self.conv4 = nn.Sequential( nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0.25), nn.BatchNorm2d(num_features=128, eps=0.8) ) # The height and width of downsampled image ds_size = img_size // 2**4 # Output layers self.adv_layer = nn.Sequential( nn.Linear(in_features=128*ds_size**2, out_features=1), nn.Sigmoid() ) self.aux_layer = nn.Sequential( nn.Linear(in_features=128*ds_size**2, out_features=num_classes+1), nn.Softmax() ) def forward(self, img): out = self.conv1(img) out = self.conv2(out) out = self.conv3(out) out = self.conv4(out) out = out.view(out.shape[0], -1) validity = self.adv_layer(out) label = self.aux_layer(out) return validity, label # In[7]: # Loss functions adversarial_loss = torch.nn.BCELoss() auxiliary_loss = torch.nn.CrossEntropyLoss() # In[8]: # Initialize generator and discriminator generator = Generator() discriminator = Discriminator() if cuda: generator.cuda() discriminator.cuda() adversarial_loss.cuda() auxiliary_loss.cuda() # In[9]: # Initialize weights generator.apply(weights_init_normal) discriminator.apply(weights_init_normal) # In[10]: # Configure DataLoader DATA_FOLDER = './torch_data/MNIST' def mnist_data(): compose = transforms.Compose([ transforms.Resize(img_size), transforms.ToTensor(), transforms.Normalize((.5, .5, .5), (.5, .5, .5)) ]) out_dir = '{}/dataset'.format(DATA_FOLDER) return datasets.MNIST(root=out_dir, train=True, transform=compose, download=True) data = mnist_data() dataloader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True) # In[20]: # Optimizers optimizer_G = torch.optim.Adam(generator.parameters(), lr=lr, betas=(b1, b2)) optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=lr, betas=(b1, b2)) FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor LongTensor = torch.cuda.LongTensor if cuda else torch.LongTensor # In[19]: # Defining ground-truth for real and fake images def real_data_groundtruth(size): ''' Variable containing ones, with shape = size, 1 ''' data = Variable(torch.ones(size, 1), requires_grad=False) if torch.cuda.is_available(): return data.cuda() return data def fake_data_groundtruth(size): ''' Variable containing zeros, with shape = size, 1 ''' data = Variable(torch.zeros(size, 1), requires_grad=False) if torch.cuda.is_available(): return data.cuda() return data def fake_aux_groundtruth(size): ''' Variable containing num_classes+1, with shape = size ''' data = Variable(LongTensor(size).fill_(num_classes), requires_grad=False) return data # In[12]: def noise(size): n = Variable(torch.randn(size, latent_dim)) if torch.cuda.is_available(): return n.cuda() else: return n # In[23]: def train_discriminator(optimizer_D, real_imgs, fake_imgs, labels): optimizer_D.zero_grad() # Loss for real images real_pred, real_aux = discriminator(real_imgs) d_real_loss = (adversarial_loss(real_pred, valid) + auxiliary_loss(real_aux, labels)) / 2.0 # Loss for fake images fake_pred, fake_aux = discriminator(fake_imgs) d_fake_loss = (adversarial_loss(fake_pred, fake) + auxiliary_loss(fake_aux, fake_aux_gt)) / 2.0 # Total discriminator loss d_loss = (d_real_loss + d_fake_loss) / 2.0 # Calculate discriminator accuracy pred = np.concatenate([real_aux.data.cpu().numpy(), fake_aux.data.cpu().numpy()], axis=0) gt = np.concatenate([labels.data.cpu().numpy(), fake_aux_gt.data.cpu().numpy()], axis=0) d_acc = np.mean(np.argmax(pred, axis=1) == gt) d_loss.backward() optimizer_D.step() return d_loss, d_acc # In[13]: def train_generator(optimizer_G, gen_imgs): optimizer_G.zero_grad() # Loss measures generator's ability to fool the discriminator validity, _ = discriminator(gen_imgs) g_loss = adversarial_loss(validity, valid) g_loss.backward() optimizer_G.step() return g_loss # In[26]: ''' Start Training ''' for epoch in range(num_epochs): for i, (imgs, labels) in enumerate(dataloader): batch_size_ = imgs.shape[0] # Adversarial ground truths valid = real_data_groundtruth(batch_size_) fake = fake_data_groundtruth(batch_size_) fake_aux_gt = fake_aux_groundtruth(batch_size_) # Configure input real_imgs = Variable(imgs.type(FloatTensor)) labels = Variable(labels.type(LongTensor)) ############################################### # Train Generator # ############################################### gen_imgs = generator(noise(batch_size_)) g_loss = train_generator(optimizer_G, gen_imgs) ############################################### # Train Discriminator # ############################################### fake_imgs = generator(noise(batch_size_)).detach() d_loss, d_acc = train_discriminator(optimizer_D, real_imgs, fake_imgs, labels) # Display Progress print ("[Epoch %d/%d] [Batch %d/%d] [D loss: %f, acc: %d%%] [G loss: %f]" % (epoch, num_epochs, i, len(dataloader), d_loss.item(), 100 * d_acc, g_loss.item())) batches_done = epoch * len(dataloader) + i if batches_done % sample_interval == 0: save_image(gen_imgs.data[:25], 'images/%d.png' % batches_done, nrow=5, normalize=True) # In[ ]:
28.133136
123
0.612157
780b04fad752e44bfbf8f8470f4b674f1838cb0a
1,195
py
Python
multiprocessing_queue.py
Bartoshko/python_playground
a9a609e6b90303b0b15af52f48c500573627a822
[ "MIT" ]
null
null
null
multiprocessing_queue.py
Bartoshko/python_playground
a9a609e6b90303b0b15af52f48c500573627a822
[ "MIT" ]
null
null
null
multiprocessing_queue.py
Bartoshko/python_playground
a9a609e6b90303b0b15af52f48c500573627a822
[ "MIT" ]
null
null
null
from multiprocessing import Process, Queue import time def reader_proc(queue): print('starting new read') ## Read from the queue; this will be spawned as a separate Process while True: msg = queue.get() # Read from the queue and do nothing if (msg == 'DONE'): break def writer(count, queue): ## Write to the queue print('starting new writter') for ii in range(0, count): queue.put(ii) # Write 'count' numbers into the queue queue.put('DONE') if __name__ == '__main__': pqueue = Queue() # writer() writes to pqueue from _this_ process for count in [10 ** 5, 10 ** 6, 10 ** 5]: ### reader_proc() reads from pqueue as a separate process reader_p = Process(target=reader_proc, args=((pqueue),)) reader_p.daemon = True reader_p.start() # Launch reader_proc() as a separate python process _start = time.time() writer(count, pqueue) # Send a lot of stuff to reader() reader_p.join() # Wait for the reader to finish print("Sending {0} numbers to Queue() took {1} seconds" .format(count, (time.time() - _start))) print('finished')
33.194444
77
0.615063
c55d39c751718cdb4e63aa3da65bf7a16d16bbdf
1,751
py
Python
pomp/example_problems/doubleintegrator.py
Aand1/pyOptimalMotionPlanning
5f06b4331149b86538e1ecfa7ccb9915c8cb510a
[ "Apache-2.0" ]
null
null
null
pomp/example_problems/doubleintegrator.py
Aand1/pyOptimalMotionPlanning
5f06b4331149b86538e1ecfa7ccb9915c8cb510a
[ "Apache-2.0" ]
null
null
null
pomp/example_problems/doubleintegrator.py
Aand1/pyOptimalMotionPlanning
5f06b4331149b86538e1ecfa7ccb9915c8cb510a
[ "Apache-2.0" ]
1
2021-07-07T16:15:52.000Z
2021-07-07T16:15:52.000Z
from OpenGL.GL import * from geometric import * from ..spaces.objective import * from ..spaces.statespace import * from ..spaces.configurationspace import * from ..spaces.edgechecker import * from ..spaces.metric import * from ..planners.problem import PlanningProblem class DoubleIntegratorVisualizer: def __init__(self,workspace): self.base = workspace def toScreen(self,q): return q[0],q[1] def toState(self,x,y): return (x,y,0,0) def drawObstaclesGL(self): self.base.drawObstaclesGL() def drawVerticesGL(self,qs): self.base.drawVerticesGL(qs) def drawRobotGL(self,q): glColor3f(0,0,1) glPointSize(7.0) self.drawVerticesGL([q]) l = 0.05 glBegin(GL_LINES) glVertex2f(q[0],q[1]) glVertex2f(q[0]+l*q[2],q[1]+l*q[3]) glEnd() def drawGoalGL(self,goal): self.base.drawGoalGL(goal) def drawInterpolatorGL(self,interpolator): self.base.drawInterpolatorGL(interpolator) def doubleIntegratorTest(): cspace = Geometric2DCSpace() #cspace.addObstacle(Circle(0.5,0.4,0.39)) vspace = BoxConfigurationSpace([-1,-1],[1,1]) aspace = BoxConfigurationSpace([-5,-5],[5,5]) start = [0.06,0.25,0,0] goal = [0.94,0.25,0,0] objective = TimeObjectiveFunction() goalRadius = 0.2 controlSpace = CVControlSpace(cspace,vspace,aspace,dt=0.05,dtmax=0.5) return PlanningProblem(controlSpace,start,goal, objective=objective, visualizer=DoubleIntegratorVisualizer(cspace), goalRadius = goalRadius, euclidean = True)
30.189655
74
0.606511
8bb18bb68c796b4377cc238b3450fd493b581ee4
2,324
py
Python
src/checks.py
DiscordLiz/salamander
87e8dbddacd4d55672491685007237493295cf5a
[ "Apache-2.0" ]
null
null
null
src/checks.py
DiscordLiz/salamander
87e8dbddacd4d55672491685007237493295cf5a
[ "Apache-2.0" ]
1
2021-03-23T05:13:57.000Z
2021-03-23T05:41:41.000Z
src/checks.py
DiscordLiz/salamander
87e8dbddacd4d55672491685007237493295cf5a
[ "Apache-2.0" ]
null
null
null
# Copyright 2020-present Michael Hall # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from discord.ext import commands from .bot import SalamanderContext def owner_in_guild(): # prevents commands.is_owner() # being mixed in requiring commands.guild_only() stacked on guild checks async def predicate(ctx: SalamanderContext) -> bool: if ctx.guild: return await ctx.bot.is_owner(ctx.author) return False return commands.check(predicate) def mod(): def predicate(ctx: SalamanderContext) -> bool: if ctx.guild: if ctx.guild.owner == ctx.author: return True return ctx.bot.privlevel_manager.member_is_mod(ctx.guild.id, ctx.author.id) return False return commands.check(predicate) def guildowner(): def predicate(ctx: SalamanderContext) -> bool: if ctx.guild: return ctx.author == ctx.guild.owner return False return commands.check(predicate) def admin(): def predicate(ctx: SalamanderContext) -> bool: if ctx.guild: if ctx.guild.owner == ctx.author: return True return ctx.bot.privlevel_manager.member_is_admin( ctx.guild.id, ctx.author.id ) return False return commands.check(predicate) def mod_or_perms(**perms): return commands.check_any( commands.has_guild_permissions(**perms), mod(), owner_in_guild() ) def admin_or_perms(**perms): return commands.check_any( commands.has_guild_permissions(**perms), admin(), owner_in_guild() ) def guildowner_or_perms(**perms): return commands.check_any( commands.has_guild_permissions(**perms), guildowner(), owner_in_guild() )
27.666667
87
0.673838
b2277b4f72a74777c9f4a1b8015389e459391965
2,082
py
Python
CTFd/forms/self.py
DevLuce/CTFd-Korean
3e45d640c7cab9fd4d4d869e443334ae4fe97e22
[ "Apache-2.0" ]
null
null
null
CTFd/forms/self.py
DevLuce/CTFd-Korean
3e45d640c7cab9fd4d4d869e443334ae4fe97e22
[ "Apache-2.0" ]
null
null
null
CTFd/forms/self.py
DevLuce/CTFd-Korean
3e45d640c7cab9fd4d4d869e443334ae4fe97e22
[ "Apache-2.0" ]
null
null
null
from flask import session from wtforms import PasswordField, SelectField, StringField from wtforms.fields.html5 import DateField, URLField from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.forms.users import attach_custom_user_fields, build_custom_user_fields from CTFd.utils.countries import SELECT_COUNTRIES_LIST from CTFd.utils.user import get_current_user def SettingsForm(*args, **kwargs): class _SettingsForm(BaseForm): # name = StringField("User Name") name = StringField("유저 이름") # email = StringField("Email") email = StringField("이메일") # password = PasswordField("Password") password = PasswordField("비밀번호") # confirm = PasswordField("Current Password") confirm = PasswordField("현재 비밀번호") # affiliation = StringField("Affiliation") affiliation = StringField("소속") # website = URLField("Website") website = URLField("웹사이트") # country = SelectField("Country", choices=SELECT_COUNTRIES_LIST) country = SelectField("국가", choices=SELECT_COUNTRIES_LIST) # submit = SubmitField("Submit") submit = SubmitField("적용") @property def extra(self): fields_kwargs = _SettingsForm.get_field_kwargs() return build_custom_user_fields( self, include_entries=True, fields_kwargs=fields_kwargs, field_entries_kwargs={"user_id": session["id"]}, ) @staticmethod def get_field_kwargs(): user = get_current_user() field_kwargs = {"editable": True} if user.filled_all_required_fields is False: # Show all fields field_kwargs = {} return field_kwargs field_kwargs = _SettingsForm.get_field_kwargs() attach_custom_user_fields(_SettingsForm, **field_kwargs) return _SettingsForm(*args, **kwargs) class TokensForm(BaseForm): expiration = DateField("Expiration") submit = SubmitField("Generate")
35.288136
80
0.654659
f5661af2f7898698ec56ca1aceb2df3a18f18de2
14,510
py
Python
lib/rucio/api/replica.py
arisfkiaras/rucio
275793a04aa85f25bf84705a893ef18679bd305a
[ "Apache-2.0" ]
null
null
null
lib/rucio/api/replica.py
arisfkiaras/rucio
275793a04aa85f25bf84705a893ef18679bd305a
[ "Apache-2.0" ]
null
null
null
lib/rucio/api/replica.py
arisfkiaras/rucio
275793a04aa85f25bf84705a893ef18679bd305a
[ "Apache-2.0" ]
null
null
null
# Copyright 2013-2018 CERN for the benefit of the ATLAS collaboration. # # 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. # # Authors: # - Vincent Garonne <vgaronne@gmail.com>, 2013-2016 # - Cedric Serfon <cedric.serfon@cern.ch>, 2014-2019 # - Thomas Beermann <thomas.beermann@cern.ch>, 2014 # - Mario Lassnig <mario.lassnig@cern.ch>, 2017-2019 # - Hannes Hansen <hannes.jakob.hansen@cern.ch>, 2019 # - Andrew Lister <andrew.lister@stfc.ac.uk>, 2019 # # PY3K COMPATIBLE from rucio.api import permission from rucio.db.sqla.constants import BadFilesStatus from rucio.core import replica from rucio.core.rse import get_rse_id, get_rse_name from rucio.common import exception from rucio.common.schema import validate_schema from rucio.common.types import InternalAccount, InternalScope from rucio.common.utils import api_update_return_dict def get_bad_replicas_summary(rse_expression=None, from_date=None, to_date=None): """ List the bad file replicas summary. Method used by the rucio-ui. :param rse_expression: The RSE expression. :param from_date: The start date. :param to_date: The end date. :param session: The database session in use. """ replicas = replica.get_bad_replicas_summary(rse_expression=rse_expression, from_date=from_date, to_date=to_date) return [api_update_return_dict(r) for r in replicas] def list_bad_replicas_status(state=BadFilesStatus.BAD, rse=None, younger_than=None, older_than=None, limit=None, list_pfns=False): """ List the bad file replicas history states. Method used by the rucio-ui. :param state: The state of the file (SUSPICIOUS or BAD). :param rse: The RSE name. :param younger_than: datetime object to select bad replicas younger than this date. :param older_than: datetime object to select bad replicas older than this date. :param limit: The maximum number of replicas returned. """ rse_id = None if rse is not None: rse_id = get_rse_id(rse=rse) replicas = replica.list_bad_replicas_status(state=state, rse_id=rse_id, younger_than=younger_than, older_than=older_than, limit=limit, list_pfns=list_pfns) return [api_update_return_dict(r) for r in replicas] def declare_bad_file_replicas(pfns, reason, issuer): """ Declare a list of bad replicas. :param pfns: The list of PFNs. :param reason: The reason of the loss. :param issuer: The issuer account. """ kwargs = {} if not permission.has_permission(issuer=issuer, action='declare_bad_file_replicas', kwargs=kwargs): raise exception.AccessDenied('Account %s can not declare bad replicas' % (issuer)) issuer = InternalAccount(issuer) replicas = replica.declare_bad_file_replicas(pfns=pfns, reason=reason, issuer=issuer, status=BadFilesStatus.BAD) for k in list(replicas): try: rse = get_rse_name(rse_id=k) replicas[rse] = replicas.pop(k) except exception.RSENotFound: pass return replicas def declare_suspicious_file_replicas(pfns, reason, issuer): """ Declare a list of bad replicas. :param pfns: The list of PFNs. :param reason: The reason of the loss. :param issuer: The issuer account. """ kwargs = {} if not permission.has_permission(issuer=issuer, action='declare_suspicious_file_replicas', kwargs=kwargs): raise exception.AccessDenied('Account %s can not declare suspicious replicas' % (issuer)) issuer = InternalAccount(issuer) replicas = replica.declare_bad_file_replicas(pfns=pfns, reason=reason, issuer=issuer, status=BadFilesStatus.SUSPICIOUS) for k in list(replicas): try: rse = get_rse_name(rse_id=k) replicas[rse] = replicas.pop(k) except exception.RSENotFound: pass return replicas def get_did_from_pfns(pfns, rse): """ Get the DIDs associated to a PFN on one given RSE :param pfns: The list of PFNs. :param rse: The RSE name. :returns: A dictionary {pfn: {'scope': scope, 'name': name}} """ rse_id = get_rse_id(rse=rse) replicas = replica.get_did_from_pfns(pfns=pfns, rse_id=rse_id) for r in replicas: for k in r.keys(): r[k]['scope'] = r[k]['scope'].external yield r def list_replicas(dids, schemes=None, unavailable=False, request_id=None, ignore_availability=True, all_states=False, rse_expression=None, client_location=None, domain=None, signature_lifetime=None, resolve_archives=True, resolve_parents=False, issuer=None): """ List file replicas for a list of data identifiers. :param dids: The list of data identifiers (DIDs). :param schemes: A list of schemes to filter the replicas. (e.g. file, http, ...) :param unavailable: Also include unavailable replicas in the list. :param request_id: ID associated with the request for debugging. :param all_states: Return all replicas whatever state they are in. Adds an extra 'states' entry in the result dictionary. :param rse_expression: The RSE expression to restrict replicas on a set of RSEs. :param client_location: Client location dictionary for PFN modification {'ip', 'fqdn', 'site'} :param domain: The network domain for the call, either None, 'wan' or 'lan'. Compatibility fallback: None falls back to 'wan'. :param signature_lifetime: If supported, in seconds, restrict the lifetime of the signed PFN. :param resolve_archives: When set to True, find archives which contain the replicas. :param resolve_parents: When set to True, find all parent datasets which contain the replicas. :param issuer: The issuer account. """ validate_schema(name='r_dids', obj=dids) # Allow selected authenticated users to retrieve signed URLs. # Unauthenticated users, or permission-less users will get the raw URL without the signature. sign_urls = False if permission.has_permission(issuer=issuer, action='get_signed_url', kwargs={}): sign_urls = True for d in dids: d['scope'] = InternalScope(d['scope']) replicas = replica.list_replicas(dids=dids, schemes=schemes, unavailable=unavailable, request_id=request_id, ignore_availability=ignore_availability, all_states=all_states, rse_expression=rse_expression, client_location=client_location, domain=domain, sign_urls=sign_urls, signature_lifetime=signature_lifetime, resolve_archives=resolve_archives, resolve_parents=resolve_parents) for rep in replicas: # 'rses' and 'states' use rse_id as the key. This needs updating to be rse. keys = ['rses', 'states'] for k in keys: old_dict = rep.get(k, None) if old_dict is not None: new_dict = {} for rse_id in old_dict: rse = get_rse_name(rse_id=rse_id) if rse_id is not None else None new_dict[rse] = old_dict[rse_id] rep[k] = new_dict rep['scope'] = rep['scope'].external if 'parents' in rep: new_parents = [] for p in rep['parents']: scope, name = p.split(':') scope = InternalScope(scope, fromExternal=False).external new_parents.append('{}:{}'.format(scope, name)) rep['parents'] = new_parents yield rep def add_replicas(rse, files, issuer, ignore_availability=False): """ Bulk add file replicas. :param rse: The RSE name. :param files: The list of files. :param issuer: The issuer account. :param ignore_availability: Ignore the RSE blacklisting. :returns: True is successful, False otherwise """ validate_schema(name='dids', obj=files) rse_id = get_rse_id(rse=rse) kwargs = {'rse': rse, 'rse_id': rse_id} if not permission.has_permission(issuer=issuer, action='add_replicas', kwargs=kwargs): raise exception.AccessDenied('Account %s can not add file replicas on %s' % (issuer, rse)) if not permission.has_permission(issuer=issuer, action='skip_availability_check', kwargs=kwargs): ignore_availability = False issuer = InternalAccount(issuer) for f in files: f['scope'] = InternalScope(f['scope']) if 'account' in f: f['account'] = InternalAccount(f['account']) replica.add_replicas(rse_id=rse_id, files=files, account=issuer, ignore_availability=ignore_availability) def delete_replicas(rse, files, issuer, ignore_availability=False): """ Bulk delete file replicas. :param rse: The RSE name. :param files: The list of files. :param issuer: The issuer account. :param ignore_availability: Ignore the RSE blacklisting. :returns: True is successful, False otherwise """ validate_schema(name='r_dids', obj=files) rse_id = get_rse_id(rse=rse) kwargs = {'rse': rse, 'rse_id': rse_id} if not permission.has_permission(issuer=issuer, action='delete_replicas', kwargs=kwargs): raise exception.AccessDenied('Account %s can not delete file replicas on %s' % (issuer, rse)) if not permission.has_permission(issuer=issuer, action='skip_availability_check', kwargs=kwargs): ignore_availability = False for f in files: f['scope'] = InternalScope(f['scope']) replica.delete_replicas(rse_id=rse_id, files=files, ignore_availability=ignore_availability) def update_replicas_states(rse, files, issuer): """ Update File replica information and state. :param rse: The RSE name. :param files: The list of files. :param issuer: The issuer account. """ validate_schema(name='dids', obj=files) rse_id = get_rse_id(rse=rse) kwargs = {'rse': rse, 'rse_id': rse_id} if not permission.has_permission(issuer=issuer, action='update_replicas_states', kwargs=kwargs): raise exception.AccessDenied('Account %s can not update file replicas state on %s' % (issuer, rse)) replicas = [] for file in files: rep = file rep['rse_id'] = rse_id rep['scope'] = InternalScope(rep['scope']) replicas.append(rep) replica.update_replicas_states(replicas=replicas) def list_dataset_replicas(scope, name, deep=False): """ :param scope: The scope of the dataset. :param name: The name of the dataset. :param deep: Lookup at the file level. :returns: A list of dict dataset replicas """ scope = InternalScope(scope) replicas = replica.list_dataset_replicas(scope=scope, name=name, deep=deep) for r in replicas: r['scope'] = r['scope'].external yield r def list_dataset_replicas_vp(scope, name, deep=False): """ :param scope: The scope of the dataset. :param name: The name of the dataset. :param deep: Lookup at the file level. :returns: If VP exists a list of dicts of sites, otherwise a list of dicts of dataset replicas NOTICE: This is an RnD function and might change or go away at any time. """ scope = InternalScope(scope) for r in replica.list_dataset_replicas_vp(scope=scope, name=name, deep=deep): yield api_update_return_dict(r) def list_datasets_per_rse(rse, filters=None, limit=None): """ :param scope: The scope of the dataset. :param name: The name of the dataset. :param filters: dictionary of attributes by which the results should be filtered. :param limit: limit number. :param session: Database session to use. :returns: A list of dict dataset replicas """ rse_id = get_rse_id(rse=rse) if 'scope' in filters: filters['scope'] = InternalScope(filters['scope']) for r in replica.list_datasets_per_rse(rse_id, filters=filters, limit=limit): yield api_update_return_dict(r) def add_bad_pfns(pfns, issuer, state, reason=None, expires_at=None): """ Add bad PFNs. :param pfns: the list of new files. :param issuer: The issuer account. :param state: One of the possible states : BAD, SUSPICIOUS, TEMPORARY_UNAVAILABLE. :param reason: A string describing the reason of the loss. :param expires_at: Specify a timeout for the TEMPORARY_UNAVAILABLE replicas. None for BAD files. :param session: The database session in use. :returns: True is successful. """ kwargs = {'state': state} if not permission.has_permission(issuer=issuer, action='add_bad_pfns', kwargs=kwargs): raise exception.AccessDenied('Account %s can not declare bad PFNs' % (issuer)) issuer = InternalAccount(issuer) return replica.add_bad_pfns(pfns=pfns, account=issuer, state=state, reason=reason, expires_at=expires_at) def get_suspicious_files(rse_expression, younger_than=None, nattempts=None): """ List the list of suspicious files on a list of RSEs :param rse_expression: The RSE expression where the suspicious files are located :param younger_than: datetime object to select the suspicious replicas younger than this date. :param nattempts: The number of time the replicas have been declared suspicious """ replicas = replica.get_suspicious_files(rse_expression=rse_expression, younger_than=younger_than, nattempts=nattempts) return [api_update_return_dict(r) for r in replicas] def set_tombstone(rse, scope, name, issuer): """ Sets a tombstone on one replica. :param rse: name of the RSE. :param scope: scope of the replica DID. :param name: name of the replica DID. :param issuer: The issuer account """ rse_id = get_rse_id(rse) if not permission.has_permission(issuer=issuer, action='set_tombstone', kwargs={}): raise exception.AccessDenied('Account %s can not set tombstones' % (issuer)) scope = InternalScope(scope) replica.set_tombstone(rse_id, scope, name)
38.08399
159
0.68856
67be05e673335e54502248514101b477feb7a01b
2,344
py
Python
care/facility/api/viewsets/facility_capacity.py
MaharashtraStateInnovationSociety/care
6e7794d2ecb08fa17f2fcea6a4bb0c829f8e48a2
[ "MIT" ]
1
2021-07-03T14:07:50.000Z
2021-07-03T14:07:50.000Z
care/facility/api/viewsets/facility_capacity.py
albernsrya/care
d7c971371dd557953d8e35e23f9c4c36aa05facb
[ "MIT" ]
null
null
null
care/facility/api/viewsets/facility_capacity.py
albernsrya/care
d7c971371dd557953d8e35e23f9c4c36aa05facb
[ "MIT" ]
null
null
null
from dry_rest_permissions.generics import DRYPermissions from rest_framework.decorators import action from rest_framework.generics import get_object_or_404 from rest_framework.mixins import ListModelMixin from rest_framework.permissions import IsAuthenticated from care.facility.api.serializers.facility_capacity import ( FacilityCapacityHistorySerializer, FacilityCapacitySerializer, ) from care.facility.api.viewsets import FacilityBaseViewset from care.facility.models import Facility, FacilityCapacity from care.users.models import User class FacilityCapacityViewSet(FacilityBaseViewset, ListModelMixin): lookup_field = "external_id" serializer_class = FacilityCapacitySerializer queryset = FacilityCapacity.objects.filter(deleted=False) permission_classes = ( IsAuthenticated, DRYPermissions, ) def get_queryset(self): user = self.request.user queryset = self.queryset.filter(facility__external_id=self.kwargs.get("facility_external_id")) if user.is_superuser: return queryset elif self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: return queryset.filter(facility__district=user.district) elif self.request.user.user_type >= User.TYPE_VALUE_MAP["StateLabAdmin"]: return queryset.filter(facility__state=user.state) return queryset.filter(facility__users__id__exact=user.id) def get_object(self): return get_object_or_404(self.get_queryset(), room_type=self.kwargs.get("external_id")) def get_facility(self): facility_qs = Facility.objects.filter(external_id=self.kwargs.get("facility_external_id")) if not self.request.user.is_superuser: facility_qs.filter(users__id__exact=self.request.user.id) return get_object_or_404(facility_qs) def perform_create(self, serializer): serializer.save(facility=self.get_facility()) @action(detail=True, methods=["get"]) def history(self, request, *args, **kwargs): obj = self.get_object() page = self.paginate_queryset(obj.history.all()) model = obj.history.__dict__["model"] serializer = FacilityCapacityHistorySerializer(model, page, many=True) serializer.is_valid() return self.get_paginated_response(serializer.data)
41.122807
102
0.74744
00979c408a0c2ef2f26556bad3f92bd55cf409df
1,548
py
Python
095-solano/results/parse_solano_pres.py
worace/california-2016-election-precinct-maps
39e9a6e797aca1b5b5f5129294807dfadb5a795d
[ "MIT" ]
82
2016-12-30T02:07:31.000Z
2022-02-26T00:39:38.000Z
095-solano/results/parse_solano_pres.py
worace/california-2016-election-precinct-maps
39e9a6e797aca1b5b5f5129294807dfadb5a795d
[ "MIT" ]
3
2017-01-16T19:12:31.000Z
2017-04-03T03:07:29.000Z
095-solano/results/parse_solano_pres.py
worace/california-2016-election-precinct-maps
39e9a6e797aca1b5b5f5129294807dfadb5a795d
[ "MIT" ]
29
2017-01-02T08:45:30.000Z
2021-11-17T15:19:31.000Z
import sys import os import re import csv filepath = sys.argv[1] if not os.path.exists('results/'): os.makedirs('results/') f = open(filepath,'r') precincts = f.read().split('\n\n') headers = ['pct16','pres_clinton','pres_trump','pres_johnson','pres_stein','pres_lariva','pres_other'] output = open('results/%s.csv' % filepath.replace('.txt',''),'w') csvwriter = csv.writer(output) csvwriter.writerow(headers) for precinct in precincts: # print precincts row = [] pct16 = re.search(r'(?:Precinct\n.+)(\d{5})',precinct,flags=re.MULTILINE).group(1) row.append(pct16) clintonline = re.search(r'.*CLINTON .+',precinct).group(0) # print yesline clinton = re.split(r'\t',clintonline)[1] row.append(clinton) trumpline = re.search(r'.*TRUMP .+',precinct).group(0) # print trumpline trump = re.split(r'\t',trumpline)[1] row.append(trump) johnsonline = re.search(r'.*JOHNSON .+',precinct).group(0) # print johnsonline johnson = re.split(r'\t',johnsonline)[1] row.append(johnson) steinline = re.search(r'.*STEIN .+',precinct).group(0) # print steinline stein = re.split(r'\t',steinline)[1] row.append(stein) larivaline = re.search(r'.*LA RIVA .+',precinct).group(0) # print larivaline lariva = re.split(r'\t',larivaline)[1] row.append(lariva) otherline = re.search(r'.*WRITE-IN .+',precinct).group(0) # print otherline other = re.split(r'\t',otherline)[1] row.append(other) csvwriter.writerow(row) f.close() output.close()
26.689655
102
0.644703
0d138a1cf2a97e16b74b964687af6b0f24e4faa1
6,018
py
Python
ibis/backends/pandas/__init__.py
gforsyth/ibis
25db64c5afe18a21e60a999d25a741b32f7b2c3e
[ "Apache-2.0" ]
null
null
null
ibis/backends/pandas/__init__.py
gforsyth/ibis
25db64c5afe18a21e60a999d25a741b32f7b2c3e
[ "Apache-2.0" ]
null
null
null
ibis/backends/pandas/__init__.py
gforsyth/ibis
25db64c5afe18a21e60a999d25a741b32f7b2c3e
[ "Apache-2.0" ]
null
null
null
from __future__ import annotations import importlib from typing import Any, MutableMapping import pandas as pd from pydantic import Field import ibis.common.exceptions as com import ibis.config import ibis.expr.operations as ops import ibis.expr.schema as sch import ibis.expr.types as ir from ibis.backends.base import BaseBackend from ibis.backends.pandas.client import ( PandasDatabase, PandasTable, ibis_schema_to_pandas, ) class BasePandasBackend(BaseBackend): """ Base class for backends based on pandas. """ name = "pandas" backend_table_type = pd.DataFrame class Options(ibis.config.BaseModel): enable_trace: bool = Field( default=False, description="Enable tracing for execution.", ) def do_connect( self, dictionary: MutableMapping[str, pd.DataFrame], ) -> None: """Construct a client from a dictionary of pandas DataFrames. Parameters ---------- dictionary Mutable mapping of string table names to pandas DataFrames. Examples -------- >>> import ibis >>> ibis.pandas.connect({"t": pd.DataFrame({"a": [1, 2, 3]})}) """ # register dispatchers from ibis.backends.pandas import execution # noqa F401 from ibis.backends.pandas import udf # noqa F401 self.dictionary = dictionary self.schemas: MutableMapping[str, sch.Schema] = {} def from_dataframe( self, df: pd.DataFrame, name: str = 'df', client: BasePandasBackend | None = None, ) -> ir.Table: """Construct an ibis table from a pandas DataFrame. Parameters ---------- df A pandas DataFrame name The name of the pandas DataFrame client Client dictionary will be mutated with the name of the DataFrame, if not provided a new client is created Returns ------- Table A table expression """ if client is None: return self.connect({name: df}).table(name) client.dictionary[name] = df return client.table(name) @property def version(self) -> str: return pd.__version__ @property def current_database(self): raise NotImplementedError('pandas backend does not support databases') def list_databases(self, like=None): raise NotImplementedError('pandas backend does not support databases') def list_tables(self, like=None, database=None): return self._filter_with_like(list(self.dictionary.keys()), like) def table(self, name: str, schema: sch.Schema = None): df = self.dictionary[name] schema = sch.infer(df, schema=schema or self.schemas.get(name, None)) return self.table_class(name, schema, self).to_expr() def database(self, name=None): return self.database_class(name, self) def load_data(self, table_name, obj, **kwargs): # kwargs is a catch all for any options required by other backends. self.dictionary[table_name] = obj def get_schema(self, table_name, database=None): schemas = self.schemas try: schema = schemas[table_name] except KeyError: schemas[table_name] = schema = sch.infer( self.dictionary[table_name] ) return schema def compile(self, expr, *args, **kwargs): return expr def create_table(self, table_name, obj=None, schema=None): """Create a table.""" if obj is None and schema is None: raise com.IbisError('Must pass expr or schema') if obj is not None: if not self._supports_conversion(obj): raise com.BackendConversionError( f"Unable to convert {obj.__class__} object " f"to backend type: {self.__class__.backend_table_type}" ) df = self._convert_object(obj) else: pandas_schema = self._convert_schema(schema) dtypes = dict(pandas_schema) df = self._from_pandas( pd.DataFrame(columns=dtypes.keys()).astype(dtypes) ) self.dictionary[table_name] = df if schema is not None: self.schemas[table_name] = schema @classmethod def _supports_conversion(cls, obj: Any) -> bool: return True @staticmethod def _convert_schema(schema: sch.Schema): return ibis_schema_to_pandas(schema) @staticmethod def _from_pandas(df: pd.DataFrame) -> pd.DataFrame: return df @classmethod def _convert_object(cls, obj: Any) -> Any: return cls.backend_table_type(obj) @classmethod def has_operation(cls, operation: type[ops.Value]) -> bool: execution = importlib.import_module( f"ibis.backends.{cls.name}.execution" ) execute_node = execution.execute_node op_classes = {op for op, *_ in execute_node.funcs.keys()} return operation in op_classes or any( issubclass(operation, op_impl) for op_impl in op_classes if issubclass(op_impl, ops.Value) ) class Backend(BasePandasBackend): name = 'pandas' database_class = PandasDatabase table_class = PandasTable def execute(self, query, params=None, limit='default', **kwargs): from ibis.backends.pandas.core import execute_and_reset if limit != 'default': raise ValueError( 'limit parameter to execute is not yet implemented in the ' 'pandas backend' ) if not isinstance(query, ir.Expr): raise TypeError( "`query` has type {!r}, expected ibis.expr.types.Expr".format( type(query).__name__ ) ) return execute_and_reset(query, params=params, **kwargs)
29.940299
78
0.608175
40a48c20fde253a8d8f2a92d818f9e294c299a74
6,386
py
Python
tensorflow_probability/python/bijectors/sigmoid_test.py
jakee417/probability-1
ae7117f37ac441bc7a888167ea23e5e620c5bcde
[ "Apache-2.0" ]
3,670
2018-02-14T03:29:40.000Z
2022-03-30T01:19:52.000Z
tensorflow_probability/python/bijectors/sigmoid_test.py
jakee417/probability-1
ae7117f37ac441bc7a888167ea23e5e620c5bcde
[ "Apache-2.0" ]
1,395
2018-02-24T02:28:49.000Z
2022-03-31T16:12:06.000Z
tensorflow_probability/python/bijectors/sigmoid_test.py
jakee417/probability-1
ae7117f37ac441bc7a888167ea23e5e620c5bcde
[ "Apache-2.0" ]
1,135
2018-02-14T01:51:10.000Z
2022-03-28T02:24:11.000Z
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Sigmoid Tests.""" # Dependency imports from absl.testing import parameterized import numpy as np from scipy import special import tensorflow.compat.v2 as tf from tensorflow_probability.python import bijectors as tfb from tensorflow_probability.python.bijectors import bijector_test_util from tensorflow_probability.python.internal import test_util @test_util.test_all_tf_execution_regimes class SigmoidBijectorTest(test_util.TestCase): """Tests correctness of the Y = g(X) = (1 + exp(-X))^-1 transformation.""" def testBijector(self): self.assertStartsWith(tfb.Sigmoid().name, 'sigmoid') x = np.linspace(-10., 10., 100).reshape([2, 5, 10]).astype(np.float32) y = special.expit(x) ildj = -np.log(y) - np.log1p(-y) bijector = tfb.Sigmoid() self.assertAllClose( y, self.evaluate(bijector.forward(x)), atol=0., rtol=1e-2) self.assertAllClose( x, self.evaluate(bijector.inverse(y)), atol=0., rtol=1e-4) self.assertAllClose( ildj, self.evaluate(bijector.inverse_log_det_jacobian( y, event_ndims=0)), atol=0., rtol=1e-6) self.assertAllClose( -ildj, self.evaluate(bijector.forward_log_det_jacobian( x, event_ndims=0)), atol=0., rtol=1e-4) def testScalarCongruency(self): bijector_test_util.assert_scalar_congruency( tfb.Sigmoid(), lower_x=-7., upper_x=7., eval_func=self.evaluate, rtol=.1) def testBijectiveAndFinite(self): x = np.linspace(-100., 100., 100).astype(np.float32) eps = 1e-3 y = np.linspace(eps, 1. - eps, 100).astype(np.float32) bijector_test_util.assert_bijective_and_finite( tfb.Sigmoid(), x, y, eval_func=self.evaluate, event_ndims=0, atol=0., rtol=1e-4) @test_util.test_all_tf_execution_regimes class ShiftedScaledSigmoidBijectorTest(test_util.TestCase): """Tests correctness of Sigmoid with `low` and `high` parameters set.""" def testBijector(self): low = np.array([[-3.], [0.], [5.]]).astype(np.float32) high = 12. bijector = tfb.Sigmoid(low=low, high=high, validate_args=True) equivalent_bijector = tfb.Chain([ tfb.Shift(shift=low), tfb.Scale(scale=high-low), tfb.Sigmoid()]) x = [[[1., 2., -5., -0.3]]] y = self.evaluate(equivalent_bijector.forward(x)) self.assertAllClose(y, self.evaluate(bijector.forward(x))) self.assertAllClose( x, self.evaluate(bijector.inverse(y)[..., :1, :]), rtol=1e-5) self.assertAllClose( self.evaluate(equivalent_bijector.inverse_log_det_jacobian( y, event_ndims=1)), self.evaluate(bijector.inverse_log_det_jacobian( y, event_ndims=1)), rtol=1e-5) self.assertAllClose( self.evaluate(equivalent_bijector.forward_log_det_jacobian( x, event_ndims=1)), self.evaluate(bijector.forward_log_det_jacobian( x, event_ndims=1))) def testNumericallySuperiorToEquivalentChain(self): x = np.array([-5., 3., 17., 23.]).astype(np.float32) low = -0.08587775 high = 0.12498104 bijector = tfb.Sigmoid(low=low, high=high, validate_args=True) equivalent_bijector = tfb.Chain([ tfb.Shift(shift=low), tfb.Scale(scale=high-low), tfb.Sigmoid()]) self.assertAllLessEqual(self.evaluate(bijector.forward(x)), high) # The mathematically equivalent `Chain` bijector can return values greater # than the intended upper bound of `high`. self.assertTrue( (self.evaluate(equivalent_bijector.forward(x)) > high).any()) def testScalarCongruency(self): low = -2. high = 5. bijector = tfb.Sigmoid(low=low, high=high, validate_args=True) bijector_test_util.assert_scalar_congruency( bijector, lower_x=-5., upper_x=3.5, eval_func=self.evaluate, rtol=0.05) def testBijectiveAndFinite(self): low = -5. high = 8. bijector = tfb.Sigmoid(low=low, high=high, validate_args=True) x = np.linspace(-10, 10, num=100).astype(np.float32) eps = 1e-6 y = np.linspace(low + eps, high - eps, num=100).astype(np.float32) bijector_test_util.assert_bijective_and_finite( bijector, x, y, eval_func=self.evaluate, event_ndims=0) def testAssertHighGtLow(self): low = np.array([1., 1., 1.], dtype=np.float32) high = np.array([1., 2., 3.], dtype=np.float32) with self.assertRaisesOpError('not defined when `low` >= `high`'): bijector = tfb.Sigmoid(low=low, high=high, validate_args=True) self.evaluate(bijector.forward(3.)) def testEdgeCaseRequiringClipping(self): np.set_printoptions(floatmode='unique', precision=None) lo = np.float32(0.010489981) hi = test_util.floats_near( 0.010499111, 100, dtype=np.float32)[:, np.newaxis] self.assertAllEqual([100, 1], hi.shape) xs = test_util.floats_near(9.814646, 100, dtype=np.float32) bijector = tfb.Sigmoid(low=lo, high=hi, validate_args=True) answers = bijector.forward(xs) self.assertAllEqual([100, 100], answers.shape) for ans1, hi1 in zip(self.evaluate(answers), hi): self.assertAllLessEqual(ans1, hi1) @parameterized.named_parameters( ('32bitGraph', np.float32, False), ('64bitGraph', np.float64, False), ('32bitXLA', np.float32, True), ('64bitXLA', np.float64, True), ) @test_util.numpy_disable_gradient_test def testLeftTail(self, dtype, do_compile): x = np.linspace(-50., -8., 1000).astype(dtype) @tf.function(autograph=False, jit_compile=do_compile) def fn(x): return tf.math.log(tfb.Sigmoid().forward(x)) vals = fn(x) true_vals = -np.log1p(np.exp(-x)) self.assertAllClose(true_vals, self.evaluate(vals), atol=1e-3) if __name__ == '__main__': test_util.main()
37.127907
78
0.67695
8e00a0e2d2eb46bee20f22ac8df97c3147301d3a
264
py
Python
twitteruser/models.py
DeanNevins/twitterclone
e713627f352f8a7d34b493384fbc86818db841c6
[ "MIT" ]
null
null
null
twitteruser/models.py
DeanNevins/twitterclone
e713627f352f8a7d34b493384fbc86818db841c6
[ "MIT" ]
null
null
null
twitteruser/models.py
DeanNevins/twitterclone
e713627f352f8a7d34b493384fbc86818db841c6
[ "MIT" ]
null
null
null
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class TwitterUser(AbstractUser): following = models.ManyToManyField('self', symmetrical=False) def __str__(self): return self.username
20.307692
65
0.753788
dbcb97ec3a237a5ca2fa4b9ae0433549654d3eca
32,747
py
Python
archive/cl_examples_sparsity.py
DMIU-ShELL/deeprl-shell
a7845ab1c4967ba2af9486625086c3d0b176d293
[ "Apache-2.0" ]
null
null
null
archive/cl_examples_sparsity.py
DMIU-ShELL/deeprl-shell
a7845ab1c4967ba2af9486625086c3d0b176d293
[ "Apache-2.0" ]
null
null
null
archive/cl_examples_sparsity.py
DMIU-ShELL/deeprl-shell
a7845ab1c4967ba2af9486625086c3d0b176d293
[ "Apache-2.0" ]
null
null
null
####################################################################### # Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) # # Permission given to modify the code as long as you keep this # # declaration at the top # ####################################################################### ''' continual learning experiments with weight preservation (consolidation) in RL ''' import json import copy import shutil import matplotlib matplotlib.use("Pdf") from deep_rl import * import os import argparse #os.environ["CUDA_VISIBLE_DEVICES"]="0" ## ppo def ppo_ctgraph_cl(name, env_config_path=None): # no sparsity, no consolidation (pure baseline) config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'baseline' config.seed = 8379 random_seed(config.seed) exp_id = '' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 2 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True config.cl_num_tasks = 4 agent = PPOAgentBaseline(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info #tasks = [tasks[0], tasks[3]] #config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 1 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) def ppo_ctgraph_cl_l1_weights(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'baseline' config.seed = 8379 random_seed(config.seed) exp_id = '-l1-weights' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 6 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True config.reg_loss_coeff = 1e-4 config.cl_num_tasks = 4 agent = PPOAgentBaselineL1Weights(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info tasks = [tasks[0], tasks[3]] config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 3 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) def ppo_ctgraph_cl_l2_weights(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'baseline' config.seed = 8379 random_seed(config.seed) exp_id = '-l2-weights' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 6 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True config.reg_loss_coeff = 1e-4 config.cl_num_tasks = 4 agent = PPOAgentBaselineL2Weights(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info tasks = [tasks[0], tasks[3]] config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 3 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) def ppo_ctgraph_cl_l1_act(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'baseline' config.seed = 8379 random_seed(config.seed) exp_id = '-l1-act' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 6 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True config.reg_loss_coeff = 1e-4 config.cl_num_tasks = 4 agent = PPOAgentBaselineL1Act(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info #tasks = [tasks[0], tasks[3]] #config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 1 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) def ppo_ctgraph_cl_l2_act(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'baseline' config.seed = 8379 random_seed(config.seed) exp_id = '-l2-act' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 6 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True config.reg_loss_coeff = 1e-4 config.cl_num_tasks = 4 agent = PPOAgentBaselineL2Act(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info tasks = [tasks[0], tasks[3]] config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 3 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) def ppo_ctgraph_cl_group_l1_weights(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'baseline' config.seed = 8379 random_seed(config.seed) exp_id = '-group-l1-weights' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 6 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True config.reg_loss_coeff = 1e-4 config.cl_num_tasks = 4 agent = PPOAgentBaselineGroupL1Weights(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info tasks = [tasks[0], tasks[3]] config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 3 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) def ppo_ctgraph_cl_sparse_group_l1_weights(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'baseline' config.seed = 8379 random_seed(config.seed) exp_id = '-sparse-group-l1-weights' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 6 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True config.reg_loss_coeff = 1e-4 config.cl_num_tasks = 4 agent = PPOAgentBaselineSparseGroupL1Weights(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info #tasks = [tasks[0], tasks[3]] #config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 6 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) # kwinners activation sparsity, no consolidation (pure baseline) def ppo_ctgraph_cl_kwinners(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'baseline' config.seed = 8379 random_seed(config.seed) exp_id = '-kwinners' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL_KWinners(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 6 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True config.cl_num_tasks = 4 agent = PPOAgentBaseline(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info #tasks = [tasks[0], tasks[3]] #config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 1 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) def ppo_ctgraph_cl_sparse_group_l1_weights_scp(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'scp' config.seed = 8379 random_seed(config.seed) exp_id = '-sparse-group-l1-weights' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 6 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True # weight preservation parasm config.cl_alpha = 0.25 config.cl_loss_coeff = 0.5 # for scp config.cl_n_slices = 200 # regularisation param(s) config.reg_loss_coeff = 1e-4 # other parameters config.cl_num_tasks = 4 agent = PPOAgentSCPSparseGroupL1Weights(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info #tasks = [tasks[0], tasks[3]] #config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 1 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) # kwinners activation sparsity, with scp consolidation def ppo_ctgraph_cl_kwinners_scp(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'scp' config.seed = 8379 random_seed(config.seed) exp_id = '-kwinners-5percent' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL( state_dim, action_dim, label_dim, phi_body=FCBody_CL_KWinners(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL(200), critic_body=DummyBody_CL(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 2 + 1 #int(5.6e4)+1 # note, max steps per task config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True # weight preservation parasm config.cl_alpha = 0.25 config.cl_loss_coeff = 0.5 # for scp config.cl_n_slices = 200 # other parameters config.cl_num_tasks = 4 agent = PPOAgentSCP(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info #tasks = [tasks[0], tasks[3]] #config.cl_num_tasks = len(tasks) config.cl_num_learn_blocks = 1 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) # neurmodulated masking of forward pass. neuromodulated network generates masks per layer. the masks # are then applied to the weights of the target/base network during forward pass. def ppo_ctgraph_cl_nm_mask_fp(name, env_config_path=None): config = Config() config.env_name = name config.env_config_path = env_config_path config.lr = 0.00015 config.cl_preservation = 'scp' config.seed = 8379 random_seed(config.seed) exp_id = '-nm-mask-fp' log_name = name + '-ppo' + '-' + config.cl_preservation + exp_id config.log_dir = get_default_log_dir(log_name) config.num_workers = 16 assert env_config_path is not None, '`env_config_path` should be set for the CTgraph environnent' task_fn = lambda log_dir: CTgraphFlatObs(name, env_config_path=env_config_path, log_dir=log_dir) config.task_fn = lambda: ParallelizedTask(task_fn, config.num_workers, log_dir=config.log_dir) config.eval_task_fn = task_fn config.optimizer_fn = lambda params, lr: torch.optim.RMSprop(params, lr=lr) config.network_fn = lambda state_dim, action_dim, label_dim: CategoricalActorCriticNet_CL_Mask( #state_dim, action_dim, label_dim, state_dim, action_dim, None, #phi_body=FCBody_CL_Mask(state_dim, task_label_dim=label_dim, hidden_units=(200, 200, 200)), phi_body=FCBody_CL_Mask(state_dim, task_label_dim=None, hidden_units=(200, 200, 200)), actor_body=DummyBody_CL_Mask(200), critic_body=DummyBody_CL_Mask(200)) config.policy_fn = SamplePolicy config.state_normalizer = ImageNormalizer() config.discount = 0.99 config.use_gae = True config.gae_tau = 0.99 config.entropy_weight = 0.75 config.rollout_length = 7 config.optimization_epochs = 4 config.num_mini_batches = 4 config.ppo_ratio_clip = 0.1 config.iteration_log_interval = 100 config.gradient_clip = 5 config.max_steps = int(5.6e4) * 3 + 1 #int(5.6e4)+1 # note, max steps per task #config.max_steps = int(5.6e4 * 0.5) + 1 #int(5.6e4)+1 # note, max steps per task #config.max_steps = 1e3 config.evaluation_episodes = 10 config.logger = get_logger(log_dir=config.log_dir) config.cl_requires_task_label = True # weight preservation params config.cl_alpha = 0.25 config.cl_loss_coeff = 1e6 #0.5 # for scp config.cl_n_slices = 200 # regularisation param(s) config.reg_loss_coeff = 1e-4 # other parameters config.cl_num_tasks = 4 agent = PPOAgentSCPModulatedFP(config) config.agent_name = agent.__class__.__name__ tasks = agent.config.cl_tasks_info config.cl_num_learn_blocks = 1 shutil.copy(env_config_path, config.log_dir + '/env_config.json') with open('{0}/tasks_info.bin'.format(config.log_dir), 'wb') as f: pickle.dump(tasks, f) run_iterations_cl(agent, tasks) # save config with open('{0}/config.json'.format(config.log_dir), 'w') as f: dict_config = vars(config) for k in dict_config.keys(): if not isinstance(dict_config[k], int) \ and not isinstance(dict_config[k], float) and dict_config[k] is not None: dict_config[k] = str(dict_config[k]) json.dump(dict_config, f) if __name__ == '__main__': mkdir('log') set_one_thread() #random_seed(42) select_device(0) # -1 is CPU, a positive integer is the index of GPU # ctgraph experiments game = 'CTgraph-v0' env_config_path = './ctgraph.json' parser = argparse.ArgumentParser() parser.add_argument('algo', help='algorithm to run') args = parser.parse_args() if args.algo == 'baseline': ppo_ctgraph_cl(name=game, env_config_path=env_config_path) elif args.algo == 'l1_weights': ppo_ctgraph_cl_l1_weights(name=game, env_config_path=env_config_path) elif args.algo == 'l2_weights': ppo_ctgraph_cl_l2_weights(name=game, env_config_path=env_config_path) elif args.algo == 'l1_act': ppo_ctgraph_cl_l1_act(name=game, env_config_path=env_config_path) elif args.algo == 'l2_act': ppo_ctgraph_cl_l2_act(name=game, env_config_path=env_config_path) elif args.algo == 'group_l1_weights': ppo_ctgraph_cl_group_l1_weights(name=game, env_config_path=env_config_path) elif args.algo == 'sparse_group_l1_weights': ppo_ctgraph_cl_sparse_group_l1_weights(name=game, env_config_path=env_config_path) elif args.algo == 'kwinners': ppo_ctgraph_cl_kwinners(name=game, env_config_path=env_config_path) elif args.algo == 'sparse_group_l1_weights_scp': ppo_ctgraph_cl_sparse_group_l1_weights_scp(name=game, env_config_path=env_config_path) elif args.algo == 'kwinners_scp': ppo_ctgraph_cl_kwinners_scp(name=game, env_config_path=env_config_path) elif args.algo == 'nm_mask_fp': ppo_ctgraph_cl_nm_mask_fp(name=game, env_config_path=env_config_path) else: raise ValueError('not implemented')
44.858904
104
0.701194
b851a06a29f955a1b9d6a141d992dfe9cfca9b06
2,077
py
Python
pytests/bucket_collections/collection_ops_specs/volume_test_load_1_percent_dgm_lower_ops.py
bkumaran/TAF
27f39eb913fa89b55cdd88ee1c7ef0bb8c094407
[ "Apache-2.0" ]
null
null
null
pytests/bucket_collections/collection_ops_specs/volume_test_load_1_percent_dgm_lower_ops.py
bkumaran/TAF
27f39eb913fa89b55cdd88ee1c7ef0bb8c094407
[ "Apache-2.0" ]
null
null
null
pytests/bucket_collections/collection_ops_specs/volume_test_load_1_percent_dgm_lower_ops.py
bkumaran/TAF
27f39eb913fa89b55cdd88ee1c7ef0bb8c094407
[ "Apache-2.0" ]
1
2019-05-22T09:10:44.000Z
2019-05-22T09:10:44.000Z
from collections_helper.collections_spec_constants import MetaCrudParams spec = { # Scope/Collection ops params MetaCrudParams.COLLECTIONS_TO_FLUSH: 0, MetaCrudParams.COLLECTIONS_TO_DROP: 5, MetaCrudParams.SCOPES_TO_DROP: 3, MetaCrudParams.SCOPES_TO_ADD_PER_BUCKET: 0, MetaCrudParams.COLLECTIONS_TO_ADD_FOR_NEW_SCOPES: 0, MetaCrudParams.COLLECTIONS_TO_ADD_PER_BUCKET: 0, MetaCrudParams.BUCKET_CONSIDERED_FOR_OPS: "all", MetaCrudParams.SCOPES_CONSIDERED_FOR_OPS: "all", MetaCrudParams.COLLECTIONS_CONSIDERED_FOR_OPS: "all", # Doc loading params "doc_crud": { MetaCrudParams.DocCrud.COMMON_DOC_KEY: "test_collections", MetaCrudParams.DocCrud.CREATE_PERCENTAGE_PER_COLLECTION: 1, MetaCrudParams.DocCrud.READ_PERCENTAGE_PER_COLLECTION: 1, MetaCrudParams.DocCrud.UPDATE_PERCENTAGE_PER_COLLECTION: 1, MetaCrudParams.DocCrud.REPLACE_PERCENTAGE_PER_COLLECTION: 0, MetaCrudParams.DocCrud.DELETE_PERCENTAGE_PER_COLLECTION: 0, }, "subdoc_crud": { MetaCrudParams.SubDocCrud.XATTR_TEST: False, MetaCrudParams.SubDocCrud.INSERT_PER_COLLECTION: 0, MetaCrudParams.SubDocCrud.UPSERT_PER_COLLECTION: 0, MetaCrudParams.SubDocCrud.REMOVE_PER_COLLECTION: 0, MetaCrudParams.SubDocCrud.LOOKUP_PER_COLLECTION: 0, }, # Doc_loading task options MetaCrudParams.DOC_TTL: 0, MetaCrudParams.DURABILITY_LEVEL: "", MetaCrudParams.SDK_TIMEOUT: 120, # Default is 60 MetaCrudParams.SDK_TIMEOUT_UNIT: "seconds", MetaCrudParams.TARGET_VBUCKETS: "all", MetaCrudParams.SKIP_READ_ON_ERROR: True, MetaCrudParams.SUPPRESS_ERROR_TABLE: True, # The below is to skip populating success dictionary for reads MetaCrudParams.SKIP_READ_SUCCESS_RESULTS: True, # Default is False MetaCrudParams.RETRY_EXCEPTIONS: [], MetaCrudParams.IGNORE_EXCEPTIONS: [], MetaCrudParams.COLLECTIONS_CONSIDERED_FOR_CRUD: "all", MetaCrudParams.SCOPES_CONSIDERED_FOR_CRUD: "all", MetaCrudParams.BUCKETS_CONSIDERED_FOR_CRUD: "all" }
39.188679
72
0.767453