content
stringlengths
7
1.05M
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. ANY_NAMESPACE = 'json_schema_compiler::any' ANY_CLASS = ANY_NAMESPACE + '::Any' class AnyHelper(object): """A util class that generates code that uses tools/json_schema_compiler/any.cc. """ def Init(self, any_prop, src, dst): """Initialize |dst|.|any_prop| to |src|. src: Value* dst: Type* """ if any_prop.optional: return '%s->%s->Init(*%s)' % (dst, any_prop.name, src) else: return '%s->%s.Init(*%s)' % (dst, any_prop.name, src) def GetValue(self, any_prop, var): """Get |var| as a const Value&. var: Any* or Any """ if any_prop.optional: return '%s->value()' % var else: return '%s.value()' % var
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class Link: """A link""" def __init__(self, url, title): self.title = title self.url = url def __str__(self): return "<a href='%s'>%s</a>" % (self.url, self.title)
# WARNING: this uses `eval`, don't run it on untrusted inputs class Node: def __init__(self, value, parent = None): self.parent = parent self.nest = (parent.nest + 1) if parent else 0 if type(value) == list: self.pair = True self.left, self.right = map(lambda n:Node(n,self), value) elif type(value) == Node: self.pair = value.pair if self.pair: self.left, self.right = Node(value.left, self), Node(value.right, self) else: self.val = value.val else: self.val = value self.pair = False def __repr__(self): if not self.pair: return repr(self.val) return '[%s,%s]' % (self.left, self.right); def findExplode(self): if self.pair: if self.nest >= 4: return self return self.left.findExplode() or self.right.findExplode() return False def findSplit(self): if not self.pair: if self.val >= 10: return self return False return self.left.findSplit() or self.right.findSplit() def firstValL(self): if self.pair: return self.left.firstValL() return self def firstValR(self): if self.pair: return self.right.firstValR() return self @staticmethod def _findLeft(root, val): if not root: return False if root.left == val: return Node._findLeft(root.parent, root) return root.left.firstValR() def findLeft(self): return Node._findLeft(self.parent, self) @staticmethod def _findRight(root, val): if not root: return False if root.right == val: return Node._findRight(root.parent, root) return root.right.firstValL() def findRight(self): return Node._findRight(self.parent, self) def explode(self): expl = self.findExplode() if not expl: return False if fL := expl.findLeft(): fL.val += expl.left.val if fR := expl.findRight(): fR.val += expl.right.val expl.pair = False expl.val = 0 return True def split(self): splt = self.findSplit() if not splt: return False splt.pair = True splt.left = Node(splt.val // 2, splt) splt.right = Node(splt.val - splt.val // 2, splt) return True def reduce(self): action = True while action: action = self.explode() if not action: action = self.split() return self def magnitude(self): if not self.pair: return self.val return 3 * self.left.magnitude() + 2 * self.right.magnitude() def __add__(self, node2): return Node([self, node2]).reduce() nodes=[*map(Node,map(eval,open("inputday18")))] print(sum(nodes[1:],nodes[0]).magnitude(),max([(i+j).magnitude() for i in nodes for j in nodes if i!=j]))
# Laskeminen luvuilla, kerta 3 # Minkälaisia laskuja voi laskea print(5+2) # Summa print(5-2) # Erotus print(5*2) # Tulo print(5/2) # Osamäärä / jakolasku print(5//2) # Jakolaskun kokonaislukuosa print(5%2) # Jakojäännös # Laskujärjestys print(2 + 2 * 3) print((2 + 2) * 3) # Liukuluvut = desimaaliluvut luku1 = 4.0 luku2 = 1.5 tulos = luku1 - luku2 print(f"Tulos on {tulos}") print(f"{luku1} - {luku2} = {tulos}")
# -*- coding: utf-8 -*- """ Created on Mon Aug 10 22:32:41 2020 @author: Goutam Dadhich """ """ Given the mobile numeric keypad. You can only press buttons that are up, left, right or down to the current button. You are not allowed to press bottom row corner buttons (i.e. * and # ). Given a number N, find out the number of possible numbers of given length Examples: For N=1, number of possible numbers would be 10 (0, 1, 2, 3, …., 9) For N=2, number of possible numbers would be 36 Possible numbers: 00,08 11,12,14 22,21,23,25 and so on. """ def isValid(i, j): if i==3 and (j==0 or j==2): return 0 return (i<=3 and i>=0 and j>=0 and j<=3) def keyPairs_rec(N): if N==0: return 0 def keyPairs_dp(N): pass if __name__ == '__main__': N = 2 global Keypad Keypad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ['*', 0, '#']] print('-'*10+'*'*5+'-'*10) print('Using recurssion:- ') print('Possible Numbers :- ',keyPairs_rec(N)) print('-'*10+'*'*5+'-'*10) print('Using dp:- ') print('Possible Numbers :- ',keyPairs_dp(N)) print('-'*10+'*'*5+'-'*10)
HOST = "0.0.0.0" DEBUG = True PORT = 8000 WORKERS = 4
# -*- coding: utf-8 -*- # Re-partitions the feature lookup blocks to conform to a specific max. block size filename = "feature US.txt" outfilename = "frag feature US.txt" with open(outfilename, "wt") as fout: with open(filename, "rt") as fin: lookupsize = 50 lookupcount = 0 count = 0 wascontextual = False calt = False for line in fin: if calt: if count == 0: startenclose = ' lookup lu%03d useExtension{\n' % (lookupcount,) fout.write(startenclose) count += 1 if ('{' not in line) and ('}' not in line) and (';' in line): if not(wascontextual == ("'" in line)): # group contextual substitutions and ligature in respective lookup blocks wascontextual = not wascontextual endenclose = ' } lu%03d;\n\n' % (lookupcount,) fout.write(endenclose) lookupcount += 1 startenclose = ' lookup lu%03d useExtension{\n' % (lookupcount,) fout.write(startenclose) count = 0 fout.write(line) count += 1 if count == lookupsize: endenclose = ' } lu%03d;\n\n' % (lookupcount,) fout.write(endenclose) lookupcount += 1 count = 0 else: fout.write(line) if 'liga;' in line: calt = True fout.write('feature calt {\n') if count != lookupsize: endenclose = ' } lu%03d;\n\n' % (lookupcount,) fout.write(endenclose) fout.write('} calt;\n')
""" Adding Workflow Labels and Annotations --------------------------------------- .. NOTE:: Coming soon 🛠 """
class MenuItem: pass # Create an instance of the MenuItem class menu_item1 = MenuItem()
#!/usr/bin/env python # # Copyright 2007 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. # """Errors thrown by `apiproxy.MakeSyncCall`. """ class Error(Exception): """Base `APIProxy` error type.""" class RPCFailedError(Error): """Raised by `APIProxy` calls when the RPC to the application server fails.""" class CallNotFoundError(Error): """Raised by `APIProxy` calls when the requested method cannot be found.""" class ArgumentError(Error): """Raised by `APIProxy` calls if there is an error parsing the arguments.""" class DeadlineExceededError(Error): """Raised by `APIProxy` calls if the call took too long to respond. Not to be confused with `runtime.DeadlineExceededError`. That one is raised when the overall HTTP response deadline is exceeded. """ class CancelledError(Error): """Raised by `APIProxy` calls if the call was cancelled, such as when the user's request is exiting.""" class ApplicationError(Error): """Raised by `APIProxy` in the event of an application-level error.""" def __init__(self, application_error, error_detail=''): self.application_error = application_error self.error_detail = error_detail Error.__init__(self, application_error) def __str__(self): return 'ApplicationError: %d %s' % (self.application_error, self.error_detail) class OverQuotaError(Error): """Raised by `APIProxy` calls when they have been blocked due to a lack of available quota.""" class RequestTooLargeError(Error): """Raised by APIProxy calls if the request was too large.""" class ResponseTooLargeError(Error): """Raised by APIProxy calls if the response was too large.""" class CapabilityDisabledError(Error): """Raised by `APIProxy` when API calls are temporarily disabled.""" class FeatureNotEnabledError(Error): """Raised by `APIProxy` when the app must enable a feature to use this call.""" class InterruptedError(Error): """Raised by `APIProxy.Wait()` when the wait is interrupted by an uncaught exception from some callback. The callback does not necessarily associated with the RPC in question. """ def __init__(self, exception, rpc): self.args = ("The Wait() request was interrupted by an exception from " "another callback:", exception) self.__rpc = rpc self.__exception = exception @property def rpc(self): return self.__rpc @property def exception(self): return self.__exception class RpcAuthorityError(Error): """Raised by `APIProxy` when loading RPC authority from the environment."""
def canonicalize_string(val): """ Return version of string in UPPERCASE and without redundant whitespace. """ try: return " ".join(val.upper().split()) except AttributeError: # was not upper-able, so was not a string return val canonicalizable = ["address_line", "city_name", "county_na", "state_nam", "province", "place_of_performance_city"] # Some field names like 'place_of_perform_county_na' are truncated def fields_by_partial_names(model, substrings): """ For any model, all field names containing any substring from `substrings`. """ for f in model._meta.fields: for substring in substrings: if substring in f.name: yield f.name continue def canonicalize_location_dict(dct): """ Canonicalize location-related values in `dct` according to the rules in `canonicalize_string`. """ for partial_field_name in canonicalizable: for field in dct: if partial_field_name in field: dct[field] = canonicalize_string(dct[field]) return dct def canonicalize_location_instance(loc): """ Canonicalize location-related values in a model instance according to the rules in `canonicalize_string`. """ for field in fields_by_partial_names(loc, canonicalizable): current_val = getattr(loc, field) if current_val: setattr(loc, field, canonicalize_string(current_val)) loc.save()
{ "targets" : [{ "target_name" : "nof", "sources" : [ "src/nof.cc", "src/mpi/node_mpi.cc", "src/osuflow/osuflow.cc", "src/osuflow/field.cc" ], "include_dirs" : ["deps/osuflow/include"], "libraries" : [ "../deps/osuflow/lib/libOSUFlow.so", "../deps/osuflow/lib/libdiy.so" ] }] }
def compute(n: int) -> int: combinations = [1] + [0] * n for i in range(1, n): for j in range(i, n + 1): combinations[j] += combinations[j - i] return combinations[-1]
"""Example B. """ def is_match(a, b): return a is b print(is_match(1, 1))
# API email tester demo def default( server, postData = None, getData = None ): print("email tester") server.email( postData['to'], 'Test Subject', 'Test Body' ) server.respondJson( True )
"""Data pipelines allow large amounts of data to be processed without loading into memory at once.""" print("\n############# PULL PIPELINES ##############") print("\ngenerators can be used for iteration based data pipelines...") def pipeline_stage_one_a(limit): num = 0 while num <= limit: print("stage 1 yield") yield num num += 1 def pipeline_stage_two(previous_stage_generator): for value in previous_stage_generator: print("stage 2 yield") yield value * value def pipeline_stage_three(previous_stage_generator): for squared_value in previous_stage_generator: squared_value += 1 print("stage 3 yield") yield squared_value print("\ncreate a data pipeline using generators...") stage1 = pipeline_stage_one_a(limit=10) # create initial generator - returns generator object, no execution stage2 = pipeline_stage_two(stage1) # pass it to the next in the pipeline stage3 = pipeline_stage_three(stage2) # pass it to the next in the pipeline print("use iteration to pull data through pipeline") for i in stage3: print("x^2 + 1 =", i) print("\nsame can be done using generator comprehensions...") stage1 = (x for x in range(10)) # create initial generator stage2 = (x*x for x in stage1) # pass it to the next in the pipeline stage3 = (x+1 for x in stage2) # pass it to the next in the pipeline # here we use iteration to pull the data through the pipeline from the end for i in stage3: print("x^2 + 1 =", i) def pipeline_stage_one_b(limit): num = 0 while num <= limit: print("stage 1a yield") yield f"(x = {num})" num += 1 def pipeline_stage_multiplex(previous_stage_generator_a, previous_stage_generator_b): for squared_value, value_label in zip(previous_stage_generator_a, previous_stage_generator_b): squared_value += 1 print("stage 3 yield") yield f"{squared_value} {value_label}" print("\nyou can create many-to-one generators in the pipeline with zip...") stage1a = pipeline_stage_one_a(limit=10) # create first generator stage1b = pipeline_stage_one_b(limit=10) # create second generator stage2 = pipeline_stage_two(stage1a) # pass first to the next in the pipeline stage3 = pipeline_stage_multiplex(stage2, stage1b) # pass two generators to the next in the pipeline for i in stage3: print("x^2 + 1 =", i) print("\n############# PUSH PIPELINES ##############") # see http://www.dabeaz.com/coroutines/ print("\ncoroutines can be used to create producer-consumer data pipelines...") def pipeline_producer(next_stage_coroutine, limit): num = 0 _return_value = next_stage_coroutine.send(None) # prime the next stage in the pipeline while num <= limit: print("stage producer send") _return_value = next_stage_coroutine.send(num) print("return value from producer send =", _return_value) num += 1 next_stage_coroutine.close() def pipeline_stage_one(next_stage_coroutine): _return_value = next_stage_coroutine.send(None) while True: print("stage 1 yield") value = (yield _return_value) # yield back up the pipeline print("stage 1 send") _return_value = next_stage_coroutine.send(value * value) # send down the pipeline def pipeline_stage_two(next_stage_coroutine): _return_value = next_stage_coroutine.send(None) while True: print("stage 2 yield") value = (yield _return_value) print("stage 2 send") _return_value = next_stage_coroutine.send(value + 1) def pipeline_stage_consumer(prefix_string): while True: print("stage consumer yield") value = (yield 'Consumed') print(prefix_string, value) print("\ncreate a data pipeline using coroutines...") stage_consumer = pipeline_stage_consumer("x^2 + 1 =") stage2 = pipeline_stage_two(stage_consumer) stage1 = pipeline_stage_one(stage2) print("push data data through the pipeline by calling producer") pipeline_producer(stage1, 10) def pipeline_stage_broadcaster(next_stage_coroutines): for _sink in next_stage_coroutines: _sink.send(None) while True: print("stage broadcast yield") value = (yield 'Broadcasting') print("stage broadcasting") for _sink in next_stage_coroutines: _sink.send(value) print("\ncreate a data pipeline with broadcasting coroutines...") stage_consumer1 = pipeline_stage_consumer("consumer1: x^2 + 1 =") stage_consumer2 = pipeline_stage_consumer("consumer2: x^2 + 1 =") stage_broadcaster = pipeline_stage_broadcaster([stage_consumer1, stage_consumer2]) stage2 = pipeline_stage_two(stage_broadcaster) stage1 = pipeline_stage_one(stage2) print("again push data data through the pipeline by calling producer") pipeline_producer(stage1, 10)
def genhtml(sites): ############################################## html = r'''<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Passme JS</title> <style type="text/css"> fieldset { margin: 0; padding: 0.75em; background: #efe; border: solid 1px #999; border-bottom-width: 0; line-height: 1.3em; border-top-left-radius: 0.5em; -moz-border-radius-topleft: 0.5em; -webkit-border-top-left-radius: 0.5em; border-top-right-radius: 0.5em; -moz-border-radius-topright: 0.5em; -webkit-border-top-right-radius: 0.5em; } fieldset.siteinfo { line-height: 2.5em; } fieldset label { display: block; float: left; margin-right: 0.75em; } fieldset div.Field { overflow: hidden; } fieldset div.Field input { width: 100%; background: none; border: none; outline: none; -webkit-appearance: none; } input.Result { width: 98%; background: #ada; } input.Copy { width: 100%; background: #ddd; font-size: 1em; padding: 0.5em; } </style> <script type="text/javascript" src="https://caligatio.github.io/jsSHA/sha.js"></script> <script type="text/javascript"> function CopyText(arg){ element = document.getElementById(arg) element.focus(); element.setSelectionRange(0, 9999); document.execCommand("copy"); element.blur(); document.getElementById("Result").value = "Copied"; document.getElementById("master").value = ""; } function calcHash() { try { var master = document.getElementById("master"); <!-- ------------------------------------------------ Site information --------------------------- --> ''' ###################################################### html = html + \ ('site = "{0}" <!-- Default selection -->'.format(sites[0][0])) html = html + ''' var sitekey = new Object({ ''' for i in sites: site = i[0] key = [i[1]['hash'], i[1]['char'], int(i[1]['len']), i[1]['seed']] for c in i[1]['comment'].split('\n'): key.append(c) html = html + (' "{0}" : {1},\n'.format(site, key)) html = html.rstrip(',\n') ###################################################### html = html + r''' }); <!-- -------------------------------------------------------------------------------------------- --> var seed = document.getElementsByName('seed'); for (i = 0; i < seed.length; i++) { if (seed[i].checked) { site = seed[i].value; } } SiteInfo = "<fieldset class=\"siteinfo\">"; for (var key in sitekey) { if (site == key) { checked = "checked=\"checked\" "; } else { checked = ""; } SiteInfo = SiteInfo + "<input type=\"radio\" name=\"seed\" value=\"" + key + "\" " + checked + "onclick=\"calcHash()\">" + key; } SiteInfo = SiteInfo + "</fieldset>"; site = sitekey[site]; var hash = site[0]; var char = site[1]; var plen = site[2]; var seed = site[3]; if (site.length > 4) { SiteInfo = SiteInfo + "<ul>"; for (var i = 4; i < site.length; i++) { var SiteInfo = SiteInfo + "<li>" + site[i].replace(/((http:|https:)\/\/[\x21-\x26\x28-\x7e]+)/gi, "<a href='$1'>$1</a>") + "</li>"; } SiteInfo = SiteInfo + "</ul>" } hash = hash.replace("sha3_","SHA3-").replace("sha","SHA-"); <!-- convert from Python hashlib --> var Password = document.getElementById("Result"); var SiteInfoOutput = document.getElementById("SiteInfo"); var hashObj = new jsSHA(hash, "BYTES"); hashObj.update(master.value + seed); base = hashObj.getHash("B64"); switch (char) { case "base64": p = base; break; case "an": p = base.replace(/[+/=]/g,""); break; case "a": p = base.replace(/[0-9+/=]/g,""); break; case "n": p = hashObj.getHash("HEX").replace(/[a-f]/g,""); break; case "ans": symbol = "#[$-=?@]_!" p = base.replace(/=/g,""); a = p.charCodeAt(0) % symbol.length; symbol = symbol.slice(a,-1) + symbol.slice(0,a) for (var i = 0; i < symbol.length; i++) { p = p.split(p.charAt(0)).join(symbol.charAt(i)).slice(1,-1) + p.charAt(0); } break; default: p = "Error"; break; } Password.value = p.slice(0,plen); if (SiteInfo > "") {SiteInfoOutput.innerHTML = SiteInfo;} document.getElementById("master").focus(); } catch(e) { Password.value = e.message } } </script> </head> <body onload="calcHash()"> <h1>Passme JS</h1> <form action="#" method="get"> <div id="SiteInfo"></div> <fieldset id="PasswdField" onclick="document.getElementById('Passwd').focus();"> <label id="PasswdLabel" for="master">Master</label> <div class="Field"> <input type="text" name="master" id="master" onkeyup="calcHash()"> </div> </fieldset> <div> <input class="Result" type="text" name="Result" id="Result"> </div> <div> <input class="Copy" type="button" name="Copy" value="Copy" onClick="CopyText('Result');"> </div> </form> <p><a href="https://github.com/sekika/passme">Passme</a></p> </body> </html> ''' ###################################################### return html
def get_bright(r, g, b): return sum([r, g, b]) / 3
_base_ = [ '../_base_/models/hv_pointpillars_fpn_nus.py', '../_base_/datasets/nus-3d.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py', ] # Note that the order of class names should be consistent with # the following anchors' order point_cloud_range = [-50, -50, -5, 50, 50, 3] class_names = [ 'bicycle', 'motorcycle', 'pedestrian', 'traffic_cone', 'barrier', 'car', 'truck', 'trailer', 'bus', 'construction_vehicle' ] train_pipeline = [ dict(type='LoadPointsFromFile', coord_type='LIDAR', load_dim=5, use_dim=5), dict(type='LoadPointsFromMultiSweeps', sweeps_num=10), dict(type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True), dict( type='GlobalRotScaleTrans', rot_range=[-0.3925, 0.3925], scale_ratio_range=[0.95, 1.05], translation_std=[0, 0, 0]), dict( type='RandomFlip3D', sync_2d=False, flip_ratio_bev_horizontal=0.5, flip_ratio_bev_vertical=0.5), dict(type='PointsRangeFilter', point_cloud_range=point_cloud_range), dict(type='ObjectRangeFilter', point_cloud_range=point_cloud_range), dict(type='PointShuffle'), dict(type='DefaultFormatBundle3D', class_names=class_names), dict(type='Collect3D', keys=['points', 'gt_bboxes_3d', 'gt_labels_3d']) ] test_pipeline = [ dict(type='LoadPointsFromFile', coord_type='LIDAR', load_dim=5, use_dim=5), dict(type='LoadPointsFromMultiSweeps', sweeps_num=10), dict( type='MultiScaleFlipAug3D', img_scale=(1333, 800), pts_scale_ratio=1, flip=False, transforms=[ dict( type='GlobalRotScaleTrans', rot_range=[0, 0], scale_ratio_range=[1., 1.], translation_std=[0, 0, 0]), dict(type='RandomFlip3D'), dict( type='PointsRangeFilter', point_cloud_range=point_cloud_range), dict( type='DefaultFormatBundle3D', class_names=class_names, with_label=False), dict(type='Collect3D', keys=['points']) ]) ] data = dict( samples_per_gpu=2, workers_per_gpu=4, train=dict(pipeline=train_pipeline, classes=class_names), val=dict(pipeline=test_pipeline, classes=class_names), test=dict(pipeline=test_pipeline, classes=class_names)) # model settings model = dict( pts_voxel_layer=dict(max_num_points=20), pts_voxel_encoder=dict(feat_channels=[64, 64]), pts_neck=dict( _delete_=True, type='SECONDFPN', norm_cfg=dict(type='naiveSyncBN2d', eps=1e-3, momentum=0.01), in_channels=[64, 128, 256], upsample_strides=[1, 2, 4], out_channels=[128, 128, 128]), pts_bbox_head=dict( _delete_=True, type='ShapeAwareHead', num_classes=10, in_channels=384, feat_channels=384, use_direction_classifier=True, anchor_generator=dict( type='AlignedAnchor3DRangeGeneratorPerCls', ranges=[[-50, -50, -1.67339111, 50, 50, -1.67339111], [-50, -50, -1.71396371, 50, 50, -1.71396371], [-50, -50, -1.61785072, 50, 50, -1.61785072], [-50, -50, -1.80984986, 50, 50, -1.80984986], [-50, -50, -1.76396500, 50, 50, -1.76396500], [-50, -50, -1.80032795, 50, 50, -1.80032795], [-50, -50, -1.74440365, 50, 50, -1.74440365], [-50, -50, -1.68526504, 50, 50, -1.68526504], [-50, -50, -1.80673031, 50, 50, -1.80673031], [-50, -50, -1.64824291, 50, 50, -1.64824291]], sizes=[ [0.60058911, 1.68452161, 1.27192197], # bicycle [0.76279481, 2.09973778, 1.44403034], # motorcycle [0.66344886, 0.72564370, 1.75748069], # pedestrian [0.39694519, 0.40359262, 1.06232151], # traffic cone [2.49008838, 0.48578221, 0.98297065], # barrier [1.95017717, 4.60718145, 1.72270761], # car [2.45609390, 6.73778078, 2.73004906], # truck [2.87427237, 12.01320693, 3.81509561], # trailer [2.94046906, 11.1885991, 3.47030982], # bus [2.73050468, 6.38352896, 3.13312415] # construction vehicle ], custom_values=[0, 0], rotations=[0, 1.57], reshape_out=False), tasks=[ dict( num_class=2, class_names=['bicycle', 'motorcycle'], shared_conv_channels=(64, 64), shared_conv_strides=(1, 1), norm_cfg=dict(type='naiveSyncBN2d', eps=1e-3, momentum=0.01)), dict( num_class=1, class_names=['pedestrian'], shared_conv_channels=(64, 64), shared_conv_strides=(1, 1), norm_cfg=dict(type='naiveSyncBN2d', eps=1e-3, momentum=0.01)), dict( num_class=2, class_names=['traffic_cone', 'barrier'], shared_conv_channels=(64, 64), shared_conv_strides=(1, 1), norm_cfg=dict(type='naiveSyncBN2d', eps=1e-3, momentum=0.01)), dict( num_class=1, class_names=['car'], shared_conv_channels=(64, 64, 64), shared_conv_strides=(2, 1, 1), norm_cfg=dict(type='naiveSyncBN2d', eps=1e-3, momentum=0.01)), dict( num_class=4, class_names=[ 'truck', 'trailer', 'bus', 'construction_vehicle' ], shared_conv_channels=(64, 64, 64), shared_conv_strides=(2, 1, 1), norm_cfg=dict(type='naiveSyncBN2d', eps=1e-3, momentum=0.01)) ], assign_per_class=True, diff_rad_by_sin=True, dir_offset=0.7854, # pi/4 dir_limit_offset=0, bbox_coder=dict(type='DeltaXYZWLHRBBoxCoder', code_size=9), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0), loss_dir=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.2)), # model training and testing settings train_cfg=dict( _delete_=True, pts=dict( assigner=[ dict( # bicycle type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.5, neg_iou_thr=0.35, min_pos_iou=0.35, ignore_iof_thr=-1), dict( # motorcycle type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.5, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), dict( # pedestrian type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.6, neg_iou_thr=0.4, min_pos_iou=0.4, ignore_iof_thr=-1), dict( # traffic cone type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.6, neg_iou_thr=0.4, min_pos_iou=0.4, ignore_iof_thr=-1), dict( # barrier type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.55, neg_iou_thr=0.4, min_pos_iou=0.4, ignore_iof_thr=-1), dict( # car type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.6, neg_iou_thr=0.45, min_pos_iou=0.45, ignore_iof_thr=-1), dict( # truck type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.55, neg_iou_thr=0.4, min_pos_iou=0.4, ignore_iof_thr=-1), dict( # trailer type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.5, neg_iou_thr=0.35, min_pos_iou=0.35, ignore_iof_thr=-1), dict( # bus type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.55, neg_iou_thr=0.4, min_pos_iou=0.4, ignore_iof_thr=-1), dict( # construction vehicle type='MaxIoUAssigner', iou_calculator=dict(type='BboxOverlapsNearest3D'), pos_iou_thr=0.5, neg_iou_thr=0.35, min_pos_iou=0.35, ignore_iof_thr=-1) ], allowed_border=0, code_weight=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.2, 0.2], pos_weight=-1, debug=False)))
# # PySNMP MIB module ZHONE-COM-VOIP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-VOIP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:41:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion") InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType") applIndex, = mibBuilder.importSymbols("NETWORK-SERVICES-MIB", "applIndex") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup") TimeTicks, NotificationType, iso, ModuleIdentity, ObjectIdentity, Bits, Counter64, Integer32, Unsigned32, IpAddress, Gauge32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "NotificationType", "iso", "ModuleIdentity", "ObjectIdentity", "Bits", "Counter64", "Integer32", "Unsigned32", "IpAddress", "Gauge32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32") TruthValue, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "DisplayString", "TextualConvention") ZhoneCodecType, = mibBuilder.importSymbols("ZHONE-GEN-SUBSCRIBER", "ZhoneCodecType") zhoneVoice, = mibBuilder.importSymbols("Zhone", "zhoneVoice") ZhoneRowStatus, = mibBuilder.importSymbols("Zhone-TC", "ZhoneRowStatus") zhoneVoip = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4)) zhoneVoip.setRevisions(('2014-10-16 23:33', '2014-08-26 10:40', '2014-07-03 02:40', '2014-06-16 21:40', '2014-05-22 14:09', '2014-01-02 22:13', '2012-09-17 23:42', '2012-09-17 23:39', '2011-12-22 02:24', '2011-10-20 12:14', '2011-07-25 11:44', '2009-10-07 01:41', '2009-03-21 02:08', '2008-10-31 01:12', '2008-08-27 23:02', '2008-06-11 17:40', '2007-07-16 02:45', '2006-04-13 15:53', '2005-10-11 11:46', '2005-07-12 10:25', '2005-07-07 16:06', '2005-07-07 15:12', '2005-06-01 11:09', '2005-05-19 15:46', '2005-05-14 21:24', '2005-02-28 10:49', '2004-11-01 14:34', '2004-03-03 17:40', '2004-02-24 12:36', '2004-01-06 15:37', '2003-11-06 10:08', '2003-10-16 14:53', '2003-08-27 11:30', '2003-08-08 17:19', '2003-05-28 12:00', '2003-03-31 18:03', '2003-02-18 14:32',)) if mibBuilder.loadTexts: zhoneVoip.setLastUpdated('201408261040Z') if mibBuilder.loadTexts: zhoneVoip.setOrganization('Zhone Technologies.') zhoneVoipSystem = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 1)) if mibBuilder.loadTexts: zhoneVoipSystem.setStatus('deprecated') zhoneVoipSystemProtocol = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("sip", 1), ("mgcp", 2))).clone('sip')).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneVoipSystemProtocol.setStatus('deprecated') zhoneVoipSystemSendCallProceedingTone = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneVoipSystemSendCallProceedingTone.setStatus('deprecated') zhoneVoipSystemRtcpEnabled = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneVoipSystemRtcpEnabled.setStatus('deprecated') zhoneVoipSystemRtcpPacketInterval = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2500, 10000)).clone(5000)).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneVoipSystemRtcpPacketInterval.setStatus('deprecated') zhoneVoipSystemInterdigitTimeout = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 1, 5), Integer32().clone(10)).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneVoipSystemInterdigitTimeout.setStatus('deprecated') zhoneVoipSystemIpTos = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneVoipSystemIpTos.setStatus('deprecated') zhoneVoipSystemDomainName = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 1, 7), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneVoipSystemDomainName.setStatus('deprecated') zhoneVoipObjects = ObjectGroup((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 2)).setObjects(("ZHONE-COM-VOIP-MIB", "nextVoipSipDialPlanId"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialString"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialIpAddr"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialPlanRowStatus"), ("ZHONE-COM-VOIP-MIB", "nextZhoneVoipHuntGroupId"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipHuntGroupDestUri"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipHuntGroupRowStatus"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialPrefixAdd"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialPrefixStrip"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialNumOfDigits"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialDestName"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipHuntGroupPortMembers"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipHuntGroupDefaultCodec"), ("ZHONE-COM-VOIP-MIB", "nextVoipMaliciousCallerId"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipMaliciousCallerUri"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerId"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerUdpPortNumber"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerAddr"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerAddrType"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerRowStatus"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialPlanType"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerSessionTimer"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerSessionExpiration"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerSessionMinSE"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerSessionCallerReqTimer"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerSessionCalleeReqTimer"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerSessionCallerSpecifyRefresher"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerSessionCalleeSpecifyRefresher"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerExpiresInvite"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerExpiresRegister"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerHeaderMethod"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipMaliciousCallerRowStatus"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipMaliciousCallerEnable"), ("ZHONE-COM-VOIP-MIB", "zhoneVoipServerBehaviorStringOne")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): zhoneVoipObjects = zhoneVoipObjects.setStatus('current') zhoneVoipSipDialPlan = MibIdentifier((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3)) nextVoipSipDialPlanId = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nextVoipSipDialPlanId.setStatus('current') zhoneVoipSipDialPlanTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2), ) if mibBuilder.loadTexts: zhoneVoipSipDialPlanTable.setStatus('current') zhoneVoipSipDialPlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1), ).setIndexNames((0, "ZHONE-COM-VOIP-MIB", "zhoneVoipSipDialPlanId")) if mibBuilder.loadTexts: zhoneVoipSipDialPlanEntry.setStatus('current') zhoneVoipSipDialPlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: zhoneVoipSipDialPlanId.setStatus('current') zhoneVoipSipDialString = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 128))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialString.setStatus('current') zhoneVoipSipDialIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 3), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialIpAddr.setStatus('current') zhoneVoipSipDialPlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 4), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialPlanRowStatus.setStatus('current') zhoneVoipSipDialDestName = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 5), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialDestName.setStatus('current') zhoneVoipSipDialNumOfDigits = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialNumOfDigits.setStatus('current') zhoneVoipSipDialPrefixStrip = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialPrefixStrip.setStatus('current') zhoneVoipSipDialPrefixAdd = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 8), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialPrefixAdd.setStatus('current') zhoneVoipSipDialPlanType = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("normal", 1), ("callpark", 2), ("esa", 3), ("isdnsig", 4), ("intercom", 5))).clone('normal')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialPlanType.setStatus('current') zhoneVoipServerEntryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerEntryIndex.setStatus('current') zhoneVoipOverrideInterdigitTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 11), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipOverrideInterdigitTimeout.setStatus('current') zhoneVoipSipDialPlanClass = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 12), Bits().clone(namedValues=NamedValues(("emergency", 0)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSipDialPlanClass.setStatus('current') zhoneVoipSipDialPlanDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 3, 2, 1, 13), SnmpAdminString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneVoipSipDialPlanDescription.setStatus('current') zhoneVoipHuntGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4)) nextZhoneVoipHuntGroupId = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nextZhoneVoipHuntGroupId.setStatus('current') zhoneVoipHuntGroupTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4, 3), ) if mibBuilder.loadTexts: zhoneVoipHuntGroupTable.setStatus('current') zhoneVoipHuntGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4, 3, 1), ).setIndexNames((0, "ZHONE-COM-VOIP-MIB", "zhoneVoipHuntGroupId")) if mibBuilder.loadTexts: zhoneVoipHuntGroupEntry.setStatus('current') zhoneVoipHuntGroupId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: zhoneVoipHuntGroupId.setStatus('current') zhoneVoipHuntGroupDestUri = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 128))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipHuntGroupDestUri.setStatus('current') zhoneVoipHuntGroupDefaultCodec = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4, 3, 1, 3), ZhoneCodecType().clone('g711mu')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipHuntGroupDefaultCodec.setStatus('current') zhoneVoipHuntGroupPortMembers = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4, 3, 1, 4), Bits().clone(namedValues=NamedValues(("port1", 0), ("port2", 1), ("port3", 2), ("port4", 3), ("port5", 4), ("port6", 5), ("port7", 6), ("port8", 7), ("port9", 8), ("port10", 9), ("port11", 10), ("port12", 11), ("port13", 12), ("port14", 13), ("port15", 14), ("port16", 15), ("port17", 16), ("port18", 17), ("port19", 18), ("port20", 19), ("port21", 20), ("port22", 21), ("port23", 22), ("port24", 23)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipHuntGroupPortMembers.setStatus('current') zhoneVoipHuntGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 4, 3, 1, 5), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipHuntGroupRowStatus.setStatus('current') zhoneVoipMaliciousCaller = MibIdentifier((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 5)) nextVoipMaliciousCallerId = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 5, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nextVoipMaliciousCallerId.setStatus('current') zhoneVoipMaliciousCallerTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 5, 2), ) if mibBuilder.loadTexts: zhoneVoipMaliciousCallerTable.setStatus('current') zhoneVoipMaliciousCallerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 5, 2, 1), ).setIndexNames((0, "ZHONE-COM-VOIP-MIB", "zhoneVoipMaliciousCallerId")) if mibBuilder.loadTexts: zhoneVoipMaliciousCallerEntry.setStatus('current') zhoneVoipMaliciousCallerId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 5, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: zhoneVoipMaliciousCallerId.setStatus('current') zhoneVoipMaliciousCallerUri = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 5, 2, 1, 2), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipMaliciousCallerUri.setStatus('current') zhoneVoipMaliciousCallerEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 5, 2, 1, 3), TruthValue().clone('true')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipMaliciousCallerEnable.setStatus('current') zhoneVoipMaliciousCallerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 5, 2, 1, 4), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipMaliciousCallerRowStatus.setStatus('current') zhoneVoipServerCfg = MibIdentifier((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6)) zhoneVoipServerTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1), ) if mibBuilder.loadTexts: zhoneVoipServerTable.setStatus('current') zhoneVoipServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"), (0, "ZHONE-COM-VOIP-MIB", "zhoneVoipServerAddressIndex")) if mibBuilder.loadTexts: zhoneVoipServerEntry.setStatus('current') zhoneVoipServerAddressIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 1), Unsigned32()) if mibBuilder.loadTexts: zhoneVoipServerAddressIndex.setStatus('current') zhoneVoipServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 2), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerRowStatus.setStatus('current') zhoneVoipServerAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 3), InetAddressType().clone('ipv4')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerAddrType.setStatus('current') zhoneVoipServerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 4), InetAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerAddr.setStatus('current') zhoneVoipServerUdpPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(2427)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerUdpPortNumber.setStatus('current') zhoneVoipServerId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38))).clone(namedValues=NamedValues(("longboard", 1), ("asterisk", 2), ("sipexpressrouter", 3), ("metaswitch", 4), ("sylantro", 5), ("broadsoft", 6), ("ubiquity", 7), ("generalbandwidth", 8), ("tekelec-T6000", 9), ("generic", 10), ("sonus", 11), ("siemens", 12), ("tekelec-T9000", 13), ("lucent-telica", 14), ("nortel-cs2000", 15), ("nuera", 16), ("lucent-imerge", 17), ("coppercom", 18), ("newcross", 19), ("cisco-bts", 20), ("cirpack-utp", 21), ("italtel-issw", 22), ("cisco-pgw", 23), ("microtrol-msk10", 24), ("nortel-dms10", 25), ("verso-clarent-c5cm", 26), ("cedarpoint-safari", 27), ("huawei-softx3000", 28), ("nortel-cs1500", 29), ("taqua-t7000", 30), ("utstarcom-mswitch", 31), ("broadsoft-broadworks", 32), ("broadsoft-m6", 33), ("genband-g9", 34), ("netcentrex", 35), ("genband-g6", 36), ("alu-5060", 37), ("ericsson-apz60", 38))).clone('generic')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerId.setStatus('current') zhoneVoipServerProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("sip", 1), ("mgcp", 2), ("megaco", 3), ("ncs", 4))).clone('sip')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerProtocol.setStatus('current') zhoneVoipServerSendCallProceedingTone = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 8), TruthValue().clone('false')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSendCallProceedingTone.setStatus('current') zhoneVoipServerRtcpEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 9), TruthValue().clone('false')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerRtcpEnabled.setStatus('current') zhoneVoipServerRtcpPacketInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 10), Integer32().clone(5000)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerRtcpPacketInterval.setStatus('current') zhoneVoipServerInterDigitTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 11), Integer32().clone(10)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerInterDigitTimeout.setStatus('current') zhoneVoipServerIpTos = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 12), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerIpTos.setStatus('current') zhoneVoipServerDomainName = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 13), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerDomainName.setStatus('current') zhoneVoipServerExpiresInvite = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 14), Unsigned32()).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerExpiresInvite.setStatus('current') zhoneVoipServerExpiresRegister = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 15), Unsigned32()).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerExpiresRegister.setStatus('current') zhoneVoipServerHeaderMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 16), Bits().clone(namedValues=NamedValues(("invite", 0), ("register", 1)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerHeaderMethod.setStatus('current') zhoneVoipServerSessionTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 2))).clone('off')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSessionTimer.setStatus('current') zhoneVoipServerSessionExpiration = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 18), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(90, 2147483647)).clone(180)).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSessionExpiration.setStatus('current') zhoneVoipServerSessionMinSE = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 19), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(90, 2147483647)).clone(180)).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSessionMinSE.setStatus('current') zhoneVoipServerSessionCallerReqTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("yes", 1), ("no", 2))).clone('no')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSessionCallerReqTimer.setStatus('current') zhoneVoipServerSessionCalleeReqTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("yes", 1), ("no", 2))).clone('no')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSessionCalleeReqTimer.setStatus('current') zhoneVoipServerSessionCallerSpecifyRefresher = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("uac", 1), ("uas", 2), ("omit", 3))).clone('omit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSessionCallerSpecifyRefresher.setStatus('current') zhoneVoipServerSessionCalleeSpecifyRefresher = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("uac", 1), ("uas", 2))).clone('uac')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSessionCalleeSpecifyRefresher.setStatus('current') zhoneVoipServerDtmfMode = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("inband", 1), ("rfc2833", 2), ("rfc2833only", 3))).clone('rfc2833')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerDtmfMode.setStatus('current') zhoneVoipServerBehaviorStringOne = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 25), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setUnits('characters').setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneVoipServerBehaviorStringOne.setStatus('current') zhoneVoipServerRtpTermIdSyntax = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 26), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 96))).setUnits('characters').setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneVoipServerRtpTermIdSyntax.setStatus('current') zhoneVoipServerRtpDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 27), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerRtpDSCP.setStatus('current') zhoneVoipServerSignalingDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 28), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerSignalingDSCP.setStatus('current') zhoneVoipServerDtmfPayloadId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 29), Integer32().subtype(subtypeSpec=ValueRangeConstraint(96, 127)).clone(101)).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneVoipServerDtmfPayloadId.setStatus('current') zhoneVoipServerRegisterReadyTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 30), Unsigned32().clone(10)).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerRegisterReadyTimeout.setStatus('current') zhoneVoipServerMessageRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 31), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(1)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerMessageRetryCount.setStatus('current') zhoneVoipServerFeatures = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 32), Bits().clone(namedValues=NamedValues(("sip-outbound", 0), ("gruu", 1)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerFeatures.setStatus('current') zhoneVoipServerTransportProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("udp", 1), ("tcp", 2))).clone('udp')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipServerTransportProtocol.setStatus('current') zhoneVoipSigLocalPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 3, 4, 6, 1, 1, 34), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(5060)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneVoipSigLocalPortNumber.setStatus('current') mibBuilder.exportSymbols("ZHONE-COM-VOIP-MIB", nextZhoneVoipHuntGroupId=nextZhoneVoipHuntGroupId, PYSNMP_MODULE_ID=zhoneVoip, zhoneVoipHuntGroupRowStatus=zhoneVoipHuntGroupRowStatus, zhoneVoipServerSessionCalleeReqTimer=zhoneVoipServerSessionCalleeReqTimer, zhoneVoipHuntGroupEntry=zhoneVoipHuntGroupEntry, zhoneVoipHuntGroupId=zhoneVoipHuntGroupId, zhoneVoipServerDomainName=zhoneVoipServerDomainName, zhoneVoipServerSendCallProceedingTone=zhoneVoipServerSendCallProceedingTone, zhoneVoipSigLocalPortNumber=zhoneVoipSigLocalPortNumber, zhoneVoipServerTransportProtocol=zhoneVoipServerTransportProtocol, zhoneVoipServerRtcpEnabled=zhoneVoipServerRtcpEnabled, nextVoipMaliciousCallerId=nextVoipMaliciousCallerId, zhoneVoipServerDtmfPayloadId=zhoneVoipServerDtmfPayloadId, zhoneVoipServerCfg=zhoneVoipServerCfg, zhoneVoipServerRowStatus=zhoneVoipServerRowStatus, zhoneVoipSystemRtcpPacketInterval=zhoneVoipSystemRtcpPacketInterval, zhoneVoipSystemDomainName=zhoneVoipSystemDomainName, zhoneVoipSystemIpTos=zhoneVoipSystemIpTos, zhoneVoipServerSessionTimer=zhoneVoipServerSessionTimer, zhoneVoipSystemSendCallProceedingTone=zhoneVoipSystemSendCallProceedingTone, zhoneVoipHuntGroupTable=zhoneVoipHuntGroupTable, zhoneVoipServerEntryIndex=zhoneVoipServerEntryIndex, zhoneVoipServerSessionCalleeSpecifyRefresher=zhoneVoipServerSessionCalleeSpecifyRefresher, zhoneVoipServerRtpTermIdSyntax=zhoneVoipServerRtpTermIdSyntax, zhoneVoipServerFeatures=zhoneVoipServerFeatures, zhoneVoipServerRtpDSCP=zhoneVoipServerRtpDSCP, zhoneVoipServerHeaderMethod=zhoneVoipServerHeaderMethod, zhoneVoipSystem=zhoneVoipSystem, zhoneVoipServerExpiresRegister=zhoneVoipServerExpiresRegister, zhoneVoipMaliciousCallerRowStatus=zhoneVoipMaliciousCallerRowStatus, zhoneVoipServerAddrType=zhoneVoipServerAddrType, zhoneVoipSipDialPrefixStrip=zhoneVoipSipDialPrefixStrip, zhoneVoipServerAddressIndex=zhoneVoipServerAddressIndex, zhoneVoipServerId=zhoneVoipServerId, zhoneVoipSipDialPlanTable=zhoneVoipSipDialPlanTable, zhoneVoipHuntGroupDestUri=zhoneVoipHuntGroupDestUri, zhoneVoipServerSessionMinSE=zhoneVoipServerSessionMinSE, zhoneVoip=zhoneVoip, zhoneVoipOverrideInterdigitTimeout=zhoneVoipOverrideInterdigitTimeout, zhoneVoipSystemRtcpEnabled=zhoneVoipSystemRtcpEnabled, zhoneVoipSipDialIpAddr=zhoneVoipSipDialIpAddr, zhoneVoipSipDialPlanEntry=zhoneVoipSipDialPlanEntry, zhoneVoipServerMessageRetryCount=zhoneVoipServerMessageRetryCount, zhoneVoipSipDialNumOfDigits=zhoneVoipSipDialNumOfDigits, zhoneVoipServerSessionCallerReqTimer=zhoneVoipServerSessionCallerReqTimer, zhoneVoipSipDialPlanRowStatus=zhoneVoipSipDialPlanRowStatus, zhoneVoipServerRegisterReadyTimeout=zhoneVoipServerRegisterReadyTimeout, zhoneVoipServerDtmfMode=zhoneVoipServerDtmfMode, zhoneVoipServerSignalingDSCP=zhoneVoipServerSignalingDSCP, zhoneVoipMaliciousCallerUri=zhoneVoipMaliciousCallerUri, zhoneVoipServerAddr=zhoneVoipServerAddr, zhoneVoipServerSessionCallerSpecifyRefresher=zhoneVoipServerSessionCallerSpecifyRefresher, zhoneVoipSipDialPlanId=zhoneVoipSipDialPlanId, zhoneVoipServerIpTos=zhoneVoipServerIpTos, zhoneVoipSipDialDestName=zhoneVoipSipDialDestName, zhoneVoipServerUdpPortNumber=zhoneVoipServerUdpPortNumber, zhoneVoipSipDialPlanType=zhoneVoipSipDialPlanType, zhoneVoipServerBehaviorStringOne=zhoneVoipServerBehaviorStringOne, zhoneVoipHuntGroupPortMembers=zhoneVoipHuntGroupPortMembers, zhoneVoipServerRtcpPacketInterval=zhoneVoipServerRtcpPacketInterval, zhoneVoipServerInterDigitTimeout=zhoneVoipServerInterDigitTimeout, zhoneVoipSipDialPlanDescription=zhoneVoipSipDialPlanDescription, zhoneVoipServerEntry=zhoneVoipServerEntry, zhoneVoipHuntGroup=zhoneVoipHuntGroup, zhoneVoipMaliciousCallerId=zhoneVoipMaliciousCallerId, zhoneVoipSipDialPlanClass=zhoneVoipSipDialPlanClass, zhoneVoipSystemProtocol=zhoneVoipSystemProtocol, zhoneVoipMaliciousCallerTable=zhoneVoipMaliciousCallerTable, zhoneVoipServerExpiresInvite=zhoneVoipServerExpiresInvite, zhoneVoipSipDialPlan=zhoneVoipSipDialPlan, zhoneVoipObjects=zhoneVoipObjects, zhoneVoipMaliciousCallerEntry=zhoneVoipMaliciousCallerEntry, zhoneVoipHuntGroupDefaultCodec=zhoneVoipHuntGroupDefaultCodec, zhoneVoipServerSessionExpiration=zhoneVoipServerSessionExpiration, nextVoipSipDialPlanId=nextVoipSipDialPlanId, zhoneVoipServerTable=zhoneVoipServerTable, zhoneVoipMaliciousCaller=zhoneVoipMaliciousCaller, zhoneVoipSipDialPrefixAdd=zhoneVoipSipDialPrefixAdd, zhoneVoipMaliciousCallerEnable=zhoneVoipMaliciousCallerEnable, zhoneVoipSystemInterdigitTimeout=zhoneVoipSystemInterdigitTimeout, zhoneVoipServerProtocol=zhoneVoipServerProtocol, zhoneVoipSipDialString=zhoneVoipSipDialString)
''' Created on Aug 29 2015 @author: kevin.chien@94301.ca ''' class FlamesStatus(object): def __init__(self, code, key, message): self.code = code self.key = key self.message = message def __eq__(self, other): if isinstance(other, FlamesStatus): return other.code == self.code return False def __ne__(self, other): return not self.__eq__(other) # server info status code OK = FlamesStatus(0, 'common.ok', 'OK.') # server error status code UNEXPECTED_EXCEPTION = FlamesStatus(1000001, 'common.unexpected_exception', 'Unknown Error.') UNKNOWN_RESOURCE = FlamesStatus(1000002, 'common.unknown_resource', 'Unknown Resource.') PARAMETER_VALIDATED_FAILED = FlamesStatus(1000003, 'common.parameter_validated_failed', 'Parameter validated error : {messages}') AUTH_FAILED = FlamesStatus(1000004, 'common.auth_failed', "Authorization failed : {messages}") JSON_PARSING_FAILED = FlamesStatus(1000004, 'common.json_parsing_failed', 'Parsing json string failed : {message}') USER_DUPLICATE = FlamesStatus(1080001, "user_duplicate", "'{user_id}' is existed") USER_NOT_FOUND = FlamesStatus(1080002, "user_not_found", "'{user_id}' is not found")
#def ask_ok(prompt, retries=4, reminder='Please try again!'): #while True: #ok = input(prompt) #if ok in ('y', 'ye', 'yes'): #return True #if ok in ('n', 'no', 'nop', 'nope'): #return False #retries = retries - 1 #if retries < 0: #raise ValueError('invalid user response') #print(reminder) #ask_ok("overwrite file?") #------------------------------------------------------------------------------- #s = 9 #x = str(s) #z = x[::-1] #print(z) #-------------------------------------------------------------------------------- #Alps = range(1,5,1) #Rockies = range(1,5,1) #for a,b in zip(Alps,Rockies): #p = a*b #newRange = [p] #print(newRange) #---------------------------------------------------------------------------------- #def isPalin(n): # """Function tests whether a number is a palindrome or not""" # z = str(n) # creates a string from number,integer,etc. # s = z[::-1] # this reverses the order of the string # if z == s: # return "True" # else: # return "False" #----------------------------------------------------------------------------- #def isPalarray(x): # """Function returns a list of palindromes""" # palindromes = [] # while x < 100: # this loop adds palindromes to the list if it is one # if isPalin(x) == "True": # see isPalin definition # palindromes.append(x) # x = x + 1 # elif isPalin(x) == "False": # x = x + 1 # return(palindromes) #def iterate(t): # """Function iterate i and then j""" # myRange = [] # q = 1000 # limits the range for a # r = 1000 # limit the range for b # for b in range (899,q,1): # for a in range(899,r,1): # p = a*b # myRange.append(p) # adds p to the range "myRange" # myRange.sort() # sorts the range # v = [] # for l in myRange: # if l not in v: # creates a new list that takes away all the duplicates from the original list # v.append(l) # return (v) #y = 1 #ans = iterate(y) #print(ans) #x = 1 #u = isPalarray(x) #print(u) #------------------------------------------------------------------------------------------ #Range1 = [] #i = 3 #while i < 100: # i = i + 2 # Range1.append(i) #Range2 = [] #x = 2 #y = 1 #j = 2*(x*y) #while j < 100: # Range2.append(j) # x = x + 1 # y = y + 1 # j = 2*(x*y) #--------------------------------------------------------------------------------- #n = 20 #Alps = [] #while n != 0: # for b in range (1,21,1): # if n % b == 0: # print(n) # break # else: # n = n + 20 cubes = [0,1,2,3,4] letters = cubes print(letters) hi=[] pp=[] def splits(name): if name == hi: return("hi") elif name == pp: return("heya!") else: pass print(splits(pp))
# with open("status.json","w") as outf: # print('{"status":"ok"}',file=outf) with open("status.json","w") as outf: print('{"status":"updating"}',file=outf)
#Write a program that calculates how many hours an architect will need to draw projects of several construction sites. #The preparation of a project takes approximately three hours. name=input() number_of_projects=int(input()) required_hours=number_of_projects*3 print(f'The architect {name} will need {required_hours} hours to complete {number_of_projects} project/s.')
#Salvando Dados dos objetos class Base: def __init__(self): self.dados = { 'adm': {'ronaldo@adm.com': ['123', 'Ronaldo', '12345678912', 20], 'carlos@adm.com': ['321', 'Carlos', '782897392821', 25]}, 'fisica': {'joao@gmail.com': ['231', 'João', '782901635123', 13], 'andressa@gmail.com': ['12345', 'Andressa', '78782983645279', 18], 'elena@gmail.com': ['54321', 'Elena', '78938624138093', 36]}, 'juridica': {'joao@gmail.com': ['12d', 'Sepermecado Mec', '782789017278437821', 60], 'pedro@loja.com': ['@ff', 'Loja Pedro', '7872871672673928926', 25], 'trelo@trem.loja.com': ['bb', 'Loja Trelo', '78328732984759', 100]} } def getDados(self): return self.dados def gravar(self, nome, lista): self.us = nome.split('@') if self.us[1] in 'adm.com': self.dados['adm'].update({nome: lista}) elif self.us[1] in 'gmail.com': self.dados['fisica'].update({nome: lista}) else: self.dados['juridica'].update({nome: lista}) print('------------------\nAção Concluída\n------------------') '''import os import pickle def criarPasta(nome): if not os.path.isdir(nome): os.mkdir(nome) return True return False def montarCaminho(nomeArq, nomeDir=None): if not nomeDir==None: return os.path.join(nomeDir, nomeArq) return nomeArq def _salvarArquivoBin(nomeArq, conteudo, nomeDir=None): caminho_Arq = montarCaminho(nomeArq, nomeDir) arq = open(caminho_Arq, 'wb') arq.write(_serializar(conteudo)) def _serializar(conteudo): return pickle.dumps(conteudo) def criarArquivoBin(nomeArquivo, conteudo, nomeDir=None): lista = [] lista.append(conteudo) _salvarArquivoBin(nomeArquivo, lista, nomeDir)'''
with open('day17.txt') as f: lines = [line.strip() for line in f] xmin,xmax,ymin,ymax,zmin,zmax,wmin,wmax = 0,0,0,0,0,0,0,0 active = set() for row in range(len(lines)): for col in range(len(lines[0])): if lines[row][col] == '#': xmin = min(xmin, col) xmax = max(xmax, col) ymin = min(ymin, row) ymax = max(ymax, row) active.add((col, row, 0, 0)) def count_active_neighbors(x,y,z,w): count = 0 for hyper in range(w - 1, w + 2): for layer in range(z - 1, z + 2): for row in range(y - 1, y + 2): for col in range (x - 1, x + 2): if layer == z and row == y and col == x and hyper == w: continue if (col, row, layer, hyper) in active: count += 1 return count ITER = 6 for iteration in range(ITER): active_copy = set(active) for hyper in range(wmin - 1, wmax + 2): for layer in range(zmin - 1, zmax + 2): for row in range(ymin - 1, ymax + 2): for col in range(xmin - 1, xmax + 2): pos = (col, row, layer, hyper) current_is_active = pos in active active_neighbor_count = count_active_neighbors(*pos) if current_is_active and (active_neighbor_count < 2 or active_neighbor_count > 3): active_copy.remove(pos) elif not current_is_active and active_neighbor_count == 3: xmin = min(xmin, col) xmax = max(xmax, col) ymin = min(ymin, row) ymax = max(ymax, row) zmin = min(zmin, layer) zmax = max(zmax, layer) wmin = min(wmin, hyper) wmax = max(wmax, hyper) active_copy.add(pos) active = active_copy print(len(active))
# "Global" users list. users = [] while True: # Initialize a new user. This uses fromkeys as a shorthand for literally # creating a new dictionary and setting its values to None, which is fine. # But, show this to users, since it's much faster. # user = dict.fromkeys(['first_name', 'last_name', 'middle_initial', 'address','email', 'phone_number']) user = { "first_name": "", "last_name": "", "middle_initial": "", "address": "", "email": "", "phone_number": "" } # Prompt user for user's identification information... user['first_name'] = input('Please enter your first name. ') user['last_name'] = input('Please enter your last name. ') user['middle_initial'] = input('Please enter your middle initial. ') # Prompt user for user's contact information... user['address'] = input('Please enter your address. ') user['email'] = input('Please enter your email. ') user['phone_number'] = input('Please enter your phone_number. ') # Print a separator... print('-' * 18) # Print all to the console... for key, value in user.items(): print('your {0} is {1}.'.format(key, value)) # Print a separator... print('-' * 18) # Prompt for confirmation. Use lower so users can enter either Y or y. if input('Is this information correct? (Y/n) ').lower() == 'y': users.append(user) print(users) # Prompt users to add more user information. if input ('Would you like to input another user\'s information? (Y/n)').lower() == 'y': continue else: print('You\'ve entered the following user profiles:') print('-' * 18) # Print information for every user in the list. for user in users: for key, value in user.items(): print('your {0} is {1}.'.format(key, value)) print('-' * 18) break
""" Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note: Time complexity should be O(height of tree). Example: root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \ 2 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def deleteNode(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode """ # target, pre = self.searchBST(root, None, key) # if not target: # return root # if not pre: # return self.adjustTree(target) # if pre.left == target: # pre.left = self.adjustTree(target) # elif pre.right == target: # pre.right = self.adjustTree(target) # return root # # def searchBST(self, root, pre, val): # if not root: # return None, pre # if root.val == val: # return root, pre # if root.val > val: # return self.searchBST(root.left, root, val) # return self.searchBST(root.right, root, val) # # def adjustTree(self, node): # if not node.left: # return node.right # if not node.right: # return node.left # # new_root = node.left # cur = new_root # while cur.right: # cur = cur.right # cur.right = node.right # return new_root if root == None: return None if root.val == key: if root.left == None: return root.right if root.right == None: return root.left node = self.nextNode(root) root.val = node.val root.right = self.deleteNode(root.right, root.val) elif key < root.val: root.left = self.deleteNode(root.left, key) else: root.right = self.deleteNode(root.right, key) return root def nextNode(self, node): curr = node.right while curr != None and curr.left != None: curr = curr.left return curr
nome = 'Pedro Paulo Barros Correia da Silva' print(nome.upper()) print(nome.lower()) nome_sem_espaco = (nome.replace(' ','')) print(len(nome_sem_espaco))
# -*- coding: utf-8 -*- """ Created on Wed Sep 15 13:22:40 2021 @author: Victor """ annual_salary = float(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ")) monthly_salary = annual_salary/12 monthly_savings = monthly_salary * portion_saved total_cost = float(input("Enter the cost of your dream home: ")) portion_down_payment = 0.25 #25% down_payment = portion_down_payment * total_cost r = 0.04 current_savings = 0.0 number_of_months = 0 while current_savings < down_payment: current_savings += (monthly_savings + (current_savings * (r/12))) number_of_months += 1 if current_savings == down_payment: break print("Number of months:",number_of_months) #print(current_savings) - to find the current savings available
def test_passwd_file(File): passwd = File("/etc/passwd") assert passwd.contains("root") assert passwd.user == "root" assert passwd.group == "root" assert passwd.mode == 0o644 def test_nginx_is_installed(Package): nginx = Package("nginx") assert nginx.is_installed assert nginx.version.startswith("1.2") def test_nginx_running_and_enabled(Service): nginx = Service("nginx") assert nginx.is_running assert nginx.is_enabled
"""Commandline engine to do work on minecraft waypoints.""" # pylint: disable=C0301 # pylint: disable=C0103 # pylint: disable=R1723 # pylint: disable=W0703 # pylint: disable=W0104 # pylint: disable=R1720 # I realise you said no global variables, but these were a pain to try passing into every function data = [ { "name": 'spawn', "x": 0, "z": 0, "y": 72, "visible": True, "red": 255, "green": 0, "blue": 0, "uses": ['spawn'], "dimensions": {'overworld', 'end', 'nether'} }] dimFilter = {'overworld', 'end', 'nether'} useFilter = [] sections = [ { "name": 'spawn', "type": 'area', "x1": -250, "z1": -250, "x2": 250, "z2": 250 }, { "name": 'surface', "type": 'elevation', "direction": 'above', "y": 63 }] # Main command line loop while True: inp = input('-->:').casefold() command = inp.strip(r'\W').split() try: # Quit the program if command[0] == 'quit': break # Help with command syntax elif command[0] == 'help': if len(command) == 1: print('Commands:') print('‣ Quit - Quit the program') print('‣ Help - Show this list') print('‣ Create - Create a waypoint') print('‣ Filter - Filter waypoints') print('‣ List - List waypoints') print('‣ Edit - Edit values in waypoint') print('‣ View - View details about a specific waypoint') print('‣ Delete - Delete waypoints') print('Type \'help <command>\' to show more details.') elif command[1] == 'quit': print('End the program and save changes to the file.') print('Syntax: Quit') elif command[1] == 'help': print('Give details about certain commands.') print('Syntax: Help <command>') elif command[1] == 'create': print('Create a new waypoint.') print('Syntax: Create <name> <x> <y> <z> ', end='') print('<visible> <r> <g> <b> <uses> <dimensions>') print('Enter uses and dimensions as a list with a \'/\' between each item.') elif command[1] == 'filter': if len(command) == 2: print('View and edit list of active filters.') print('Subcommands:') print('‣ Clear - Clears all filters') print('‣ Add - Adds a filter') print('‣ Remove - Removes a filter') print('‣ List - Lists all filters') print('Type \'Help Filter <subcommand>\' for more information.') print('Syntax: Filter <subcommand>') elif command[2] == 'clear': print('Clear all filters.') print('Syntax: Filter Clear') elif command[2] == 'add': if len(command) == 3: print('Add a new filter.') print('Valid filters:') print('‣ Area') print('‣ Elevation') print('‣ Uses') print('‣ Dimensions') print('Type \'Help Filter Add <filter>\' for more information.') print('Syntax: Filter Add <filter>') elif command[3] == 'area': print('Create a new x/z area.') print('Syntax: Filter Add Area <name> <x1> <z1> <x2> <z2>') elif command[3] == 'elevation': print('Create a new y area.') print('Syntax: Filter Add Area <name> <above/below/at> <y>') elif command[3] == 'uses': print('Filter valid points by uses.') print('Syntax: Filter Add Uses <uses>') print('Enter uses as a list with a \'/\' separating each item.') elif command[3] == 'dimensions': print('Filter valid points by dimension.') print('Syntax: Filter Add Dimensions <dimensions>') print('Enter dimensions as a list with a \'/\' separating each item.') else: raise SyntaxError(f'Unknown command \'{command[3]}\'.') elif command[2] == 'remove': print('Remove specified filter.') print('Syntax: Filter Remove <dimensions/uses>; Filter Remove <name>') elif command[2] == 'list': print('List all active filters.') print('Syntax: Filter List') else: raise SyntaxError(f'Unknown command \'{command[2]}\'.') elif command[1] == 'list': print('List all points that match all active filters.') print('Syntax: List') elif command[1] == 'edit': print('Edit specific values in a certain point defined by \'name\'.') print('Syntax: Edit <name> <edit value> <value>') print('Enter \'dimensions\' and \'uses\' values as lists with \'/\' separating each item.') elif command[1] == 'view': print('View details about a specific waypoint.') print('Syntax: View <name>') elif command[1] == 'delete': print('Delete specific waypoints.') print('Syntax: Delete <name>') else: raise SyntaxError(f'Unknown command \'{command[1]}\'') # Create a new waypoint elif command[0] == 'create': for i in data: if i["name"] == command[1]: raise SyntaxError('A waypoint with that name already exists.') p = {} p["name"] = command[1] p["x"] = int(command[2]) p["y"] = int(command[3]) p["z"] = int(command[4]) if command[5] == 'true': p["visible"] = True elif command[5] == 'false': p["visible"] = False else: raise SyntaxError('Error in visibility bool.') if 0 <= int(command[6]) <= 255: p["red"] = int(command[6]) else: raise SyntaxError('Error in red value.') if 0 <= int(command[7]) <= 255: p["green"] = int(command[7]) else: raise SyntaxError('Error in green value.') if 0 <= int(command[8]) <= 255: p["blue"] = int(command[8]) else: raise SyntaxError('Error in blue value.') p["uses"] = command[9].split('/') p["dimensions"] = set(command[10].split('/')) for i in p["dimensions"]: if i not in ['end', 'overworld', 'nether']: raise SyntaxError('Error in dimensions.') print('Success.') data.append(p) # View and edit filters elif command[0] == 'filter': # View filters if len(command) == 1 or command[1] == 'list': if len(sections) == 0 and len(useFilter) == 0 and dimFilter == {'overworld', 'end', 'nether'}: print('There are no filters.') else: print(f'Filters:') if dimFilter != {'overworld', 'end', 'nether'}: print(f'• Dimensions: {dimFilter}') if len(useFilter) > 0: print(f'• Uses: {useFilter}') if len(sections) > 0: print('• Sections:') for i in sections: print(f' -{i["name"]}: ', end='') if i["type"] == 'area': print(f'Area from ({i["x1"]}, {i["z1"]}) to ({i["x2"]}, {i["z2"]}).') if i["type"] == 'elevation': print(f'Elevation {i["direction"]} y {i["y"]}') # Remove all filters elif command[1] == 'clear': dimFilter = {'overworld', 'end', 'nether'} useFilter = [] sections = [] print('Cleared all filters.') # remove specific filter elif command[1] == 'remove': if command[2] == 'uses': useFilter == [] print('Removed!') elif command[2] == 'dimensions': dimFilter = {'overworld', 'end', 'nether'} print('Removed!') else: for i in sections: if i["name"] == command[2]: sections.remove(i) print('Removed!') break else: raise SyntaxError('No filters with that name.') # Add new filter elif command[1] == 'add': # Create new sectioned off area NESW-wise if command[2] == 'area': for i in sections: if i == command[3]: raise SyntaxError('A section with this name already exists.') sections.append({ "name":command[3], "type":'area', "x1":command[4], "z1":command[5], "x2":command[6], "z2":command[7]}) print('Success.') # create new secioned off area hightwise elif command[2] == 'elevation': for i in sections: if i == command[3]: raise SyntaxError('A section with this name already exists.') if command[4] in ['above', 'below', 'at']: sections.append({ "name":command[3], "type":'elevation', "direction":command[4], "y":command[5]}) print('Success.') # Create new uses filter(which actually just edits the existing one) elif command[2] == 'uses': useFilter = command[2].split() # Create new Dimensions filter(which actually just edits the existing one) elif command[3] == 'dimensions': dim = command[3].split('/') if len(dim) > 3: raise SyntaxError('Too many dimensions. There should be nore more than 3.') elif len(dim) < 1: raise SyntaxError('There must be at least one dimension.') else: for i in dim: if i not in {'overworld', 'nether', 'end'}: raise SyntaxError('Dimensions invalid') dimFilter = dim # List all waypoints elif command[0] == 'list': showData = data # Apply filters to the data. for i in data: # Dimension filter for x in i["dimensions"]: if x not in dimFilter: showData.remove(i) # Uses filter if len(useFilter) > 0: for x in i["uses"]: if x not in useFilter: showData.remove(i) # Sectioned off area filters if len(sections) > 0: for filt in sections: if filt["type"] == 'perimiter': if filt["x1"] > i["x"] > filt["x2"]: showData.remove(i) if filt["type"] == 'altitude': if filt["direction"] == 'above': if i["y"] < filt["y"]: showData.remove(i) elif filt["direction"] == 'below': if i["y"] > filt["y"]: showData.remove(i) elif filt["direction"] == 'at': if i["y"] != filt["y"]: showData.remove(i) # Print the filtered data if len(showData) > 0: print("Matching points:") for i in showData: print(f'» {i["name"]}') else: print("No points match filters.") # Edit values in waypoint elif command[0] == 'edit': for i, d in enumerate(data): if d["name"] == command[1]: if command[2] in ['dimensions', 'uses']: d[command[2]] = command[3].split('/') else: d[command[2]] = command[3] break else: raise SyntaxError('No point has that name.') # View details about a specific waypoint elif command[0] == 'view': for i in data: if i["name"] == command[1]: print(f'Name: {i["name"]}') print(f'Coords: {i["x"]}, {i["y"]}, {i["z"]}') print(f'Visible: {i["visible"]}') print(f'Color: {i["red"]}, {i["green"]}, {i["blue"]}') print(f'Uses: {i["uses"]}') print(f'Dimensions: {i["dimensions"]}') elif command[0] == 'delete': for i in data: if i["name"] == command[1]: data.remove(i) else: raise SyntaxError(f'Unknown command \'{command[0]}\'') # Takes care of my predicted errors except SyntaxError as err: print('Syntax Error:') print(err) # Takes care of errors where not enough data entered in command except IndexError: print('Syntax Error:') print('Not enough information entered.') # takes care of any unpredicted errors except Exception: print(err)
#!/usr/bin/python3.5 print('Running ETL For Riders') # Brings data using the Cloudstitch API # into staging tables for further processing by other parts # of the process
# # PySNMP MIB module Juniper-PPP-Profile-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-PPP-Profile-CONF # Produced by pysmi-0.3.4 at Mon Apr 29 19:53:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion") juniProfileAgents, = mibBuilder.importSymbols("Juniper-Agents", "juniProfileAgents") AgentCapabilities, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "NotificationGroup", "ModuleCompliance") ModuleIdentity, Counter64, NotificationType, ObjectIdentity, Counter32, Bits, IpAddress, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Unsigned32, Gauge32, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Counter64", "NotificationType", "ObjectIdentity", "Counter32", "Bits", "IpAddress", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Unsigned32", "Gauge32", "TimeTicks", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") juniPppProfileAgent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3)) juniPppProfileAgent.setRevisions(('2009-09-18 07:24', '2009-08-10 14:23', '2007-07-12 12:15', '2005-10-19 16:26', '2003-11-03 21:32', '2003-03-13 16:47', '2002-09-06 16:54', '2002-09-03 22:38', '2002-01-25 14:10', '2002-01-16 17:58', '2002-01-08 19:43', '2001-10-17 17:10',)) if mibBuilder.loadTexts: juniPppProfileAgent.setLastUpdated('200909180724Z') if mibBuilder.loadTexts: juniPppProfileAgent.setOrganization('Juniper Networks, Inc.') juniPppProfileAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV1 = juniPppProfileAgentV1.setProductRelease('Version 1 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component was supported in JUNOSe 3.0 through\n 3.2 system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV1 = juniPppProfileAgentV1.setStatus('obsolete') juniPppProfileAgentV2 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 2)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV2 = juniPppProfileAgentV2.setProductRelease('Version 2 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component was supported in JUNOSe 3.3 system\n release.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV2 = juniPppProfileAgentV2.setStatus('obsolete') juniPppProfileAgentV3 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 3)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV3 = juniPppProfileAgentV3.setProductRelease('Version 3 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component was supported in JUNOSe 3.4 and\n subsequent 3.x system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV3 = juniPppProfileAgentV3.setStatus('obsolete') juniPppProfileAgentV4 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 4)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV4 = juniPppProfileAgentV4.setProductRelease('Version 4 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component was supported in JUNOSe 4.0 system\n releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV4 = juniPppProfileAgentV4.setStatus('obsolete') juniPppProfileAgentV5 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 5)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV5 = juniPppProfileAgentV5.setProductRelease('Version 5 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component was supported in JUNOSe 4.1 through\n 5.0 system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV5 = juniPppProfileAgentV5.setStatus('obsolete') juniPppProfileAgentV6 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 6)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV6 = juniPppProfileAgentV6.setProductRelease('Version 6 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component was supported in JUNOSe 5.1 and 5.2\n system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV6 = juniPppProfileAgentV6.setStatus('obsolete') juniPppProfileAgentV7 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 7)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV7 = juniPppProfileAgentV7.setProductRelease('Version 7 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component is supported in JUNOSe 5.3 through\n 7.2 system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV7 = juniPppProfileAgentV7.setStatus('obsolete') juniPppProfileAgentV8 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 8)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV8 = juniPppProfileAgentV8.setProductRelease('Version 8 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component is supported in JUNOSe 7.2 system\n releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV8 = juniPppProfileAgentV8.setStatus('obsolete') juniPppProfileAgentV9 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 9)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV9 = juniPppProfileAgentV9.setProductRelease('Version 9 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component is supported in JUNOSe 7.3 and\n subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV9 = juniPppProfileAgentV9.setStatus('obsolete') juniPppProfileAgentV10 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 10)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV10 = juniPppProfileAgentV10.setProductRelease('Version 10 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component is supported in JUNOSe 11.0 and\n subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV10 = juniPppProfileAgentV10.setStatus('obsolete') juniPppProfileAgentV11 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 3, 11)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV11 = juniPppProfileAgentV11.setProductRelease('Version 11 of the PPP Profile component of the JUNOSe SNMP agent. This\n version of the PPP Profile component is supported in JUNOSe 11.1 and\n subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniPppProfileAgentV11 = juniPppProfileAgentV11.setStatus('current') mibBuilder.exportSymbols("Juniper-PPP-Profile-CONF", juniPppProfileAgentV9=juniPppProfileAgentV9, juniPppProfileAgentV10=juniPppProfileAgentV10, juniPppProfileAgentV2=juniPppProfileAgentV2, juniPppProfileAgentV11=juniPppProfileAgentV11, juniPppProfileAgentV7=juniPppProfileAgentV7, juniPppProfileAgentV5=juniPppProfileAgentV5, juniPppProfileAgentV8=juniPppProfileAgentV8, juniPppProfileAgentV1=juniPppProfileAgentV1, PYSNMP_MODULE_ID=juniPppProfileAgent, juniPppProfileAgentV3=juniPppProfileAgentV3, juniPppProfileAgent=juniPppProfileAgent, juniPppProfileAgentV4=juniPppProfileAgentV4, juniPppProfileAgentV6=juniPppProfileAgentV6)
load( "@com_activestate_rules_vendor//private:dependencies.bzl", _vendor_dependencies = "vendor_dependencies" ) load( "@com_activestate_rules_vendor//private:generate.bzl", _vendor_generate = "vendor_generate" ) vendor_dependencies = _vendor_dependencies vendor_generate = _vendor_generate
# OpenWeatherMap API Key weather_api_key = "532f8d0abc1e638795cea2ce10729a26" # Google API Key g_key = "AIzaSyBIgvIa9rZosgo9uoIOjJL9Cgdz5ZIdj9Q"
# x는 글로벌 변수이다. # foo 함수 내에서 x는 자유 변수이다. x = 1 def foo(): print(x) # outer_func는 지역변수 n이 있다. # inner_func 에는 지역변수 m 과 n 이 있다. def outer_func(): n = 1 def inner_func(): m = 2 print(n) print(m) return inner_func func = outer_func() print(func.__code__.co_freevars)
class Solution: def isAnagram(self, s: str, t: str) -> bool: if s == t: return True if len(s) != len(t) or len(s) == 0 or len(t) == 0: return False pre_map = {} for i in s: if pre_map.__contains__(i): pre_map[i] += 1 else: pre_map[i] = 1 for j in t: if not pre_map.__contains__(j): return False pre_map[j] -= 1 if pre_map[j] == 0: del pre_map[j] if len(pre_map) == 0: return True else: return False slu = Solution() print(slu.isAnagram("anagram", "nagaram"))
class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: n = len(nums) if n < 2: return n length, cnt = [1] * n, [1] * n for idx, _ in enumerate(nums): for j in range(idx): if nums[j] < _: if length[idx] == length[j]: length[idx] += 1 cnt[idx] = cnt[j] elif length[idx] == length[j] + 1: cnt[idx] += cnt[j] longest = max(length) return sum([x[1] for x in enumerate(cnt) if length[x[0]] == longest]) ''' l = 1 cnt = 0 def helper(idx, tmp): nonlocal cnt, l if len(tmp) == l: cnt += 1 elif len(tmp) > l: l = len(tmp) cnt = 1 for i in range(idx, len(nums)): if tmp == []: helper(i + 1, [nums[i]]) else: if nums[i] > tmp[-1]: helper(i + 1, tmp + [nums[i]]) helper(0, []) return cnt '''
# Finding Bridges in Undirected Graph def computeBridges(l): id = 0 n = len(l) # No of vertices in graph low = [0] * n visited = [False] * n def dfs(at, parent, bridges, id): visited[at] = True low[at] = id id += 1 for to in l[at]: if to == parent: pass elif not visited[to]: dfs(to, at, bridges, id) low[at] = min(low[at], low[to]) if at < low[to]: bridges.append([at, to]) else: # This edge is a back edge and cannot be a bridge low[at] = min(low[at], to) bridges = [] for i in range(n): if not visited[i]: dfs(i, -1, bridges, id) print(bridges) l = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } computeBridges(l)
class BaseError(Exception): pass class ResourceNotFoundError(BaseError): name = "ResourceNotFoundError" status = 404 def __init__(self, message=None): self.body = { "message": message or "Resource not found" } class BadParametersError(BaseError): name = "BadParametersError" status = 400 def __init__(self, message=None): self.body = { "message": message or "Bad Parameters" } class MissingParameterError(BaseError): name = "MissingParameterError" status = 400 def __init__(self, message=None, missing_params=None): self.body = { "message": message or "Missing Parameters Error", "missing_params": missing_params } class MissingRequiredHeader(BaseError): name = "MissingRequiredHeader" status = 400 body = {"message": "Missing Required Header"} def __init__(self, message=None): self.body = { "message": message or "Missing Required Header" } class ForbiddenError(BaseError): name = "ForbiddenError" status = 403 def __init__(self, message=None): self.body = { "message": message or "Forbidden error" } class ConflictError(BaseError): name = "ConflictError" status = 409 body = {"message": "Resource Conflict"} class UnauthorizedError(BaseError): name = "UnauthorizedError" status = 401 def __init__(self, message=None): self.body = { "message": message or "Unauthorized Error" } class RemoteAPIError(BaseError): name = "RemoteAPIError" status = 502 def __init__(self, message=None, remote_error=None, remote_message=None, sent_params={}): self.body = { "message": message or "Remote API Error", "remote_error": remote_error, "remote_message": remote_message, "sent_params": sent_params } class UnknownError(BaseError): name = "UnknownError" status = 500 def __init__(self, message=None): self.body = { "message": message or "UnknownError", }
class Antibiotico: def __init__(self, nombre, tipoAnimal, dosis, precio): self.__nombre = nombre self.__tipoAnimal = tipoAnimal self.__dosis = dosis self.__precio = precio @property def nombre(self): return self.__nombre @property def tipoAnimal(self): return self.__tipoAnimal @property def dosis(self): return self.__dosis @property def precio(self): return self.__precio
""" BIAflows problem classes """ CLASS_OBJSEG = "ObjSeg" CLASS_SPTCNT = "SptCnt" CLASS_PIXCLA = "PixCla" CLASS_TRETRC = "TreTrc" CLASS_LOOTRC = "LooTrc" CLASS_OBJDET = "ObjDet" CLASS_PRTTRK = "PrtTrk" CLASS_OBJTRK = "ObjTrk" CLASS_LNDDET = "LndDet"
#%% def cal_iou(box1, box2): """ :param box1: = [xmin1, ymin1, xmax1, ymax1] :param box2: = [xmin2, ymin2, xmax2, ymax2] :return: """ xmin1, ymin1, xmax1, ymax1 = box1 xmin2, ymin2, xmax2, ymax2 = box2 # 计算每个矩形的面积 s1 = (xmax1 - xmin1) * (ymax1 - ymin1) # C的面积 s2 = (xmax2 - xmin2) * (ymax2 - ymin2) # G的面积 # 计算相交矩形 xmin = max(xmin1, xmin2) ymin = max(ymin1, ymin2) xmax = min(xmax1, xmax2) ymax = min(ymax1, ymax2) w = max(0, xmax - xmin) h = max(0, ymax - ymin) area = w * h # C∩G的面积 iou = area / (s1 + s2 - area) return iou box1 = [ 70.376625, 113.337105, 330.46487, 379.46274 ] box2 = [ 54.44469, 133.12114, 303.55597, 363.3416 ] cal_iou(box1, box2)
{ "targets": [ { "target_name": "unidecode", "sources": [ "src/addon.cxx" ], "include_dirs" : [ "<!(node -e \"require('nan')\")" ], "cflags": ["-g"], 'cflags_cc!': [ '-fno-exceptions' ], 'conditions': [ ['OS=="mac"', { 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' } }] ] }, { "target_name": "action_after_build", "type": "none", "dependencies": [ "<(module_name)" ], "copies": [ { "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], "destination": "<(module_path)" } ] } ] }
#!/usr/bin/python # not_kwd.py grades = ["A", "B", "C", "D", "E", "F"] grade = "L" if grade not in grades: print ("Unknown grade")
def setup(bot): return DISCORD_EPOCH = 1420070400000 def ReadableTime(first, last): readTime = int(last-first) weeks = int(readTime/604800) days = int((readTime-(weeks*604800))/86400) hours = int((readTime-(days*86400 + weeks*604800))/3600) minutes = int((readTime-(hours*3600 + days*86400 + weeks*604800))/60) seconds = int(readTime-(minutes*60 + hours*3600 + days*86400 + weeks*604800)) msg = '' if weeks > 0: msg += '1 week, ' if weeks == 1 else '{:,} weeks, '.format(weeks) if weeks > 0: msg += "1 week, " if weeks == 1 else "{:,} weeks, ".format(weeks) if days > 0: msg += "1 day, " if days == 1 else "{:,} days, ".format(days) if hours > 0: msg += "1 hour, " if hours == 1 else "{:,} hours, ".format(hours) if minutes > 0: msg += "1 minute, " if minutes == 1 else "{:,} minutes, ".format(minutes) if seconds > 0: msg += "1 second, " if seconds == 1 else "{:,} seconds, ".format(seconds) if msg == "": return "0 seconds" else: return msg[:-2]
EXAMPLES1 = ( ('09-exemple1.txt', 15), ) EXAMPLES2 = ( ('09-exemple1.txt', 1134), ) INPUT = '09.txt' def read_data(fn): data = list() with open(fn) as f: for line in f: line = line.strip() data.append(line) return data def neighbours(data, i, j): neigh = ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)) return [x for x in neigh if 0 <= x[0] < len(data) and 0 <= x[1] < len(data[0])] def low_points(data): points = list() for i, line in enumerate(data): for j, c in enumerate(line): if all(data[i2][j2] > c for i2, j2 in neighbours(data, i, j)): points.append((i, j)) return points def code1(data): score = 0 for i, j in low_points(data): score += int(data[i][j]) + 1 return score def make_bassin(data, bassin, i, j): for i2, j2 in neighbours(data, i, j): if (i2, j2) in bassin or data[i2][j2] == '9': pass else: bassin.add((i2, j2)) bassin = make_bassin(data, bassin, i2, j2) return bassin def code2(data): size_bassins = list() for i, j in low_points(data): bassin = set() bassin.add((i, j)) bassin = make_bassin(data, bassin, i, j) size_bassins.append(len(bassin)) x, y, z = sorted(size_bassins, reverse=True)[:3] return x * y * z def test(n, code, examples, myinput): for fn, result in examples: data = read_data(fn) assert result is None or code(data) == result, (data, result, code(data)) print(f'{n}>', code(read_data(myinput))) test(1, code1, EXAMPLES1, INPUT) test(2, code2, EXAMPLES2, INPUT)
# Selecting Indices # Explain in simple terms what idxmin and idxmax do in the short program below. # When would you use these methods? data = pd.read_csv('../../data/gapminder_gdp_europe.csv', index_col='country') print(data.idxmin()) print(data.idxmax())
# status: testado com exemplos da prova if __name__ == '__main__': char = input() all_words = input().split() words = [word for word in all_words if char in word] print("{0:.1f}".format(len(words) / len(all_words) * 100))
#! /usr/bin/env python model0.initialize() model1.initialize() time = model0.get_current_time() end_time = model0.get_end_time() while time < end_time: has_converged = False while has_converged is False: state1 = model1.get_value("some_state_variable") model0.set_value("some_state_variable", state1) model0.solve() state0 = model0.get_value("boundary_flows") model1.set_value("boundary_flows", state0) model1.solve() has_converged = check_convergence(model0, model1, convergence_criteria) model1.update() model0.update() time = model0.get_current_time()
class LinkedListNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.num_elements = 0 self.head = None def push(self, data): new_node = LinkedListNode(data) if self.head is None: self.head = new_node else: new_node.next = self.head self.head = new_node self.num_elements += 1 def pop(self): if self.is_empty(): return None temp = self.head.data self.head = self.head.next self.num_elements -= 1 return temp def top(self): if self.head is None: return None return self.head.data def size(self): return self.num_elements def is_empty(self): return self.num_elements == 0 def evaluate_post_fix(input_list): stack = Stack() for element in input_list: if element == '*': second = stack.pop() first = stack.pop() output = first * second stack.push(output) elif element == '/': second = stack.pop() first = stack.pop() output = int(first / second) stack.push(output) elif element == '+': second = stack.pop() first = stack.pop() output = first + second stack.push(output) elif element == '-': second = stack.pop() first = stack.pop() output = first - second stack.push(output) else: stack.push(int(element)) return stack.pop() def test_function(test_case): output = evaluate_post_fix(test_case[0]) print(output) if output == test_case[1]: print("Pass") else: print("Fail") test_case_1 = [["3", "1", "+", "4", "*"], 16] test_function(test_case_1) test_case_2 = [["4", "13", "5", "/", "+"], 6] test_function(test_case_2) test_case_3 = [["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"], 22] test_function(test_case_3)
# Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. # Example 1: # Input: "Hello" # Output: "hello" # Example 2: # Input: "here" # Output: "here" # Example 3: # Input: "LOVELY" # Output: "lovely" class Solution: def toLowerCase(self, str: str) -> str: for i in range (0, len(str)): asc = ord(str[i]) if 65 <= asc <= 90: str = str[:i] + chr(asc + 32) + str[i + 1 :] return str
""" Project Euler Problem 6: Sum square difference """ # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum MAXINT = 100 sumsq = 0 sqsum = (MAXINT*(MAXINT+1)//2)**2 # Calculate the sum of squares for i in range(1,MAXINT+1): sumsq += i**2 print(sqsum-sumsq)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Helper methods used in notebooks """ def _dataframe_highlight_4d_no_altitude_dim(x, bg_color='#ffcccc'): #copy df to new - original data are not changed df = x.copy() #set by condition m1 = df['Dim'] == 4 m2 = 'altitude' not in df['Dim names'] mask = m1 * m2 df.loc[mask, :] = 'background-color: {}'.format(bg_color) df.loc[~mask,:] = 'background-color: ""' return df
class Graph(object): def __init__(self,*args,**kwargs): self.node_neighbors = {} # Define vertex and adjacent vertex set as dictionary structure self.visited = {} # Define the visited vertex set as a dictionary structure def add_nodes(self,nodelist): for node in nodelist: self.add_node(node) def add_node(self,node): if not node in self.nodes(): self.node_neighbors[node] = [] def add_edge(self,edge): u,v = edge if(v not in self.node_neighbors[u]) and ( u not in self.node_neighbors[v]): # Here you can add your own side pointing to yourself self.node_neighbors[u].append(v) if(u!=v): self.node_neighbors[v].append(u) def nodes(self): return self.node_neighbors.keys() def breadth_first_search(self,root=None): # Breadth first requires the queue structure queue = [] order = [] def bfs(): while len(queue)> 0: node = queue.pop(0) self.visited[node] = True self.node_neighbors[node].sort() for n in self.node_neighbors[node]: if (not n in self.visited) and (not n in queue): queue.append(n) order.append(n) if root: queue.append(root) order.append(root) bfs() for node in self.nodes(): if not node in self.visited: queue.append(node) order.append(node) bfs() # print(order) return order def bfs(graph, S, D): queue = [(S, [S])] while queue: (vertex, path) = queue.pop(0) for next in graph[vertex] - set(path): if next == D: yield path + [next] else: queue.append((next, path + [next])) def shortest(graph, S, D): try: return next(bfs(graph, S, D)) except StopIteration: return None if __name__ == '__main__': g = Graph() n = int(input()) g.add_nodes([i+1 for i in range( n )]) for i in range( n - 1 ): g.add_edge(tuple(input().split())) print(g.node_neighbors) # print(shortest(g, '1', '5'))
"""Write a function that returns the largest element in a list.""" def largest_element(a): return max(a) mylist = [1, 4, 5, 100, 2, 1, -1, -7] max = largest_element(mylist) print("The largest value is ", max)
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. { 'includes': [ 'common_settings.gypi', ], 'targets': [ # Auto test - command line test for all platforms { 'target_name': 'voe_auto_test', 'type': 'executable', 'dependencies': [ 'voice_engine/main/source/voice_engine_core.gyp:voice_engine_core', 'system_wrappers/source/system_wrappers.gyp:system_wrappers', ], 'include_dirs': [ 'voice_engine/main/test/auto_test', ], 'sources': [ 'voice_engine/main/test/auto_test/voe_cpu_test.cc', 'voice_engine/main/test/auto_test/voe_cpu_test.h', 'voice_engine/main/test/auto_test/voe_extended_test.cc', 'voice_engine/main/test/auto_test/voe_extended_test.h', 'voice_engine/main/test/auto_test/voe_standard_test.cc', 'voice_engine/main/test/auto_test/voe_standard_test.h', 'voice_engine/main/test/auto_test/voe_stress_test.cc', 'voice_engine/main/test/auto_test/voe_stress_test.h', 'voice_engine/main/test/auto_test/voe_test_defines.h', 'voice_engine/main/test/auto_test/voe_test_interface.h', 'voice_engine/main/test/auto_test/voe_unit_test.cc', 'voice_engine/main/test/auto_test/voe_unit_test.h', ], 'conditions': [ ['OS=="linux" or OS=="mac"', { 'actions': [ { 'action_name': 'copy audio file', 'inputs': [ 'voice_engine/main/test/auto_test/audio_long16.pcm', ], 'outputs': [ '/tmp/audio_long16.pcm', ], 'action': [ '/bin/sh', '-c', 'cp -f voice_engine/main/test/auto_test/audio_* /tmp/;'\ 'cp -f voice_engine/main/test/auto_test/audio_short16.pcm /tmp/;', ], }, ], }], ['OS=="win"', { 'dependencies': [ 'voice_engine.gyp:voe_ui_win_test', ], }], ['OS=="win"', { 'actions': [ { 'action_name': 'copy audio file', 'inputs': [ 'voice_engine/main/test/auto_test/audio_long16.pcm', ], 'outputs': [ '/tmp/audio_long16.pcm', ], 'action': [ 'cmd', '/c', 'xcopy /Y /R .\\voice_engine\\main\\test\\auto_test\\audio_* \\tmp', ], }, { 'action_name': 'copy audio audio_short16.pcm', 'inputs': [ 'voice_engine/main/test/auto_test/audio_short16.pcm', ], 'outputs': [ '/tmp/audio_short16.pcm', ], 'action': [ 'cmd', '/c', 'xcopy /Y /R .\\voice_engine\\main\\test\\auto_test\\audio_short16.pcm \\tmp', ], }, ], }], ], }, { # command line test that should work on linux/mac/win 'target_name': 'voe_cmd_test', 'type': 'executable', 'dependencies': [ 'voice_engine/main/source/voice_engine_core.gyp:voice_engine_core', 'system_wrappers/source/system_wrappers.gyp:system_wrappers', ], 'sources': [ 'voice_engine/main/test/cmd_test/voe_cmd_test.cc', ], }, ], 'conditions': [ ['OS=="win"', { 'targets': [ # WinTest - GUI test for Windows { 'target_name': 'voe_ui_win_test', 'type': 'executable', 'dependencies': [ 'voice_engine/main/source/voice_engine_core.gyp:voice_engine_core', 'system_wrappers/source/system_wrappers.gyp:system_wrappers', ], 'include_dirs': [ 'voice_engine/main/test/win_test', ], 'sources': [ 'voice_engine/main/test/win_test/Resource.h', 'voice_engine/main/test/win_test/WinTest.cpp', 'voice_engine/main/test/win_test/WinTest.h', 'voice_engine/main/test/win_test/WinTest.rc', 'voice_engine/main/test/win_test/WinTestDlg.cpp', 'voice_engine/main/test/win_test/WinTestDlg.h', 'voice_engine/main/test/win_test/res/WinTest.ico', 'voice_engine/main/test/win_test/res/WinTest.rc2', 'voice_engine/main/test/win_test/stdafx.cpp', 'voice_engine/main/test/win_test/stdafx.h', ], 'actions': [ { 'action_name': 'copy audio file', 'inputs': [ 'voice_engine/main/test/win_test/audio_tiny11.wav', ], 'outputs': [ '/tmp/audio_tiny11.wav', ], 'action': [ 'cmd', '/c', 'xcopy /Y /R .\\voice_engine\\main\\test\\win_test\\audio_* \\tmp', ], }, { 'action_name': 'copy audio audio_short16.pcm', 'inputs': [ 'voice_engine/main/test/win_test/audio_short16.pcm', ], 'outputs': [ '/tmp/audio_short16.pcm', ], 'action': [ 'cmd', '/c', 'xcopy /Y /R .\\voice_engine\\main\\test\\win_test\\audio_short16.pcm \\tmp', ], }, { 'action_name': 'copy audio_long16noise.pcm', 'inputs': [ 'voice_engine/main/test/win_test/audio_long16noise.pcm', ], 'outputs': [ '/tmp/audio_long16noise.pcm', ], 'action': [ 'cmd', '/c', 'xcopy /Y /R .\\voice_engine\\main\\test\\win_test\\audio_long16noise.pcm \\tmp', ], }, ], 'configurations': { 'Common_Base': { 'msvs_configuration_attributes': { 'conditions': [ ['component=="shared_library"', { 'UseOfMFC': '2', # Shared DLL },{ 'UseOfMFC': '1', # Static }], ], }, }, }, 'msvs_settings': { 'VCLinkerTool': { 'SubSystem': '2', # Windows }, }, }, ], }], ], } # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:
sample_rate=16000 #Provided in the paper n_mels = 80 frame_rate = 80 #Provided in the paper frame_length = 0.05 hop_length = int(sample_rate/frame_rate) win_length = int(sample_rate*frame_length) scaling_factor = 4 min_db_level = -100 bce_weights = 7 embed_dims = 512 hidden_dims = 256 heads = 4 forward_expansion = 4 num_layers = 4 dropout = 0.15 max_len = 1024 pad_idx = 0 Metadata = 'input/LJSpeech-1.1/metadata.csv' Audio_file_path = 'input/LJSpeech-1.1/wavs/' Model_Path = 'model/model.bin' checkpoint = 'model/checkpoint.bin' Batch_Size = 2 Epochs = 40 LR = 3e-4 warmup_steps = 0.2
# Classes are blueprints that make instances of a class # emp_1 = Employee() # emp_2 = Employee() # These two things become independant objects or 'instances' """ emp_1.first = 'Corey' emp_1.last = 'Schafer' emp_1.email = 'Corey.Schafer@company.com' emp_1.pay = 50000 emp_2.first = 'Corey' emp_2.last = 'Schafer' emp_2.email = 'Corey.Schafer@company.com' emp_2.pay = 50000 """ # these are the same details for different instances # and can be performed with a class class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return('{} {}'.format(self.first, self.last)) emp_1 = Employee('Corey', 'Schafer', 50000) emp_2 = Employee('Test', 'Employee', 60000) print(Employee.fullname(emp_1))
class node: def __init__(self, x): self.value = x self.next = None class LinkedList: def __init__(self, y): self.head = node(y)
class Genre: """ Entidad que representa géneros de un manga. Attributes ---------- name : str Nombre del manga. generos : list of String Lista de géneros que puede tener el manga. """ def __init__(self) -> None: """ Constructor de la entidad """ self.generos=["SHONEN","SEINEN","SHOJO","JOSEI","KODOMO","ISEKAI","CYBERPUNK","YAOI","YURI","ECCHI","HENTAI","SPOKON","MAGICAL_GIRLS","MECHAS"] # Ponderación de los géneros ponderacion = {"SHONEN": 7, "SEINEN": 5, "SHOJO": 7, "JOSEI": 10, "KODOMO": 4, "ISEKAI": 7, "CYBERPUNK": 8, "YAOI": 9, "YURI": 9, "ECCHI": 9, "HENTAI": 10, "SPOKON": 3, "MAGICAL_GIRLS": 6, "MECHAS": 6}
class Message(object): def __init__(self, args, kwargs=None, start_timestamp=None): ''' The Nomad Message type which is passed around clients. :param args: list of args for the next operator :type args: list :param kwargs: dict of kwargs for the next operator :type kwargs: dict ''' # if not isinstance(args, list): # args = [args] self.args = args if kwargs is None: self.kwargs = {} else: self.kwargs = kwargs self.start_timestamp = start_timestamp def get_args(self): return self.args def __str__(self): return str(self.args) + "_" + str(self.start_timestamp)
def subwaysFilter(dimension): def _filter(poi): if poi["id"] == "subways/" + dimension: return poi return _filter
'''Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são suas vogais.''' palavra = '' tupla = ('APRENDER', 'PROGRAMAR', 'LINGUAGEM', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCADO', 'PROGRAMADOR', 'FUTURO') for pos in tupla: print(f'\nNa palavra {pos} temos ', end='') for letra in pos: if letra.lower() in 'aeiou': print(letra, end=' ') '''for pos in range(0, len(tupla)): palavra = tupla[pos] print(f'\nNa palavra {tupla[pos]} temos as vogais ', end='') for c in range(0, len(palavra)): if palavra[c] == 'A': print('a', end=' ') if palavra[c] == 'E': print('e', end=' ') if palavra[c] == 'I': print('i', end=' ') if palavra[c] == 'O': print('o', end=' ') if palavra[c] == 'U': print('u', end=' ')'''
''' TOTAL PATHS FROM (0, 0) to (m, n) The task is to calculate total possible moves we can make to reach (m, n) in a matrix, starting from origin, given that we can only take 1 step towards right or up in a single move. ''' def totalPaths(m, n): total = [] for i in range(0, m): temp = [] for j in range(0, n): temp.append(0) total.append(temp) for i in range(0, max(m, n)): if i < m: total[i][0] = 1 if i < n: total[0][i] = 1 for i in range(1, m): for j in range(1, n): total[i][j] = total[i - 1][j] + total[i][j - 1] return total[m-1][n-1] m = int(input()) n = int(input()) print("The total paths are", totalPaths(m, n)) ''' INPUT : n = 6 m = 5 OUTPUT : The total paths are 126 '''
def combo_breaker_part1(data: str) -> int: key1, key2 = tuple(map(int, data.splitlines(keepends=False))) subject = 7 found = False loop_size = None loop_count = 1 while not found: loop_count += 1 subject = transform(subject) if subject == key2: loop_size = loop_count found = True working = 1 for n in range(loop_size): working = transform(working, key1) return working def transform(key: int, subject: int = 7) -> int: return (key * subject) % 20201227 # def combo_breaker_part2(data: str) -> int: # pass if __name__ == '__main__': test_text = """5764801 17807724""" assert combo_breaker_part1(test_text) == 14897079 # assert combo_breaker_part2(test_text) == 0 with open('input.txt') as in_file: in_text = in_file.read() part1 = combo_breaker_part1(in_text) print(f'Part1: {part1}') # part2 = combo_breaker_part2(in_text) # print(f'Part2: {part2}') # Part1: 448851
with open("mystery.png", "rb") as f: buf1 = f.read()[-0x10:] with open("mystery2.png", "rb") as f: buf2 = f.read()[-2:] with open("mystery3.png", "rb") as f: buf3 = f.read()[-8:] flag = [0 for i in range(0x1a)] flag[1] = buf3[0] flag[0] = buf2[0] - ((0x2a + (0x2a >> 7)) >> 1) flag[2] = buf3[1] flag[4] = buf1[0] flag[5] = buf3[2] for i in range(4): flag[6 + i] = buf1[1 + i] flag[3] = buf2[1] - 4 for i in range(5): flag[0x0a + i] = buf3[3 + i] for i in range(0xf, 0x1a): flag[i] = buf1[1 + 4 + i - 0xf] for c in flag: print(chr(c), end="")
# Input exmaple and variable value assignment print('Yo nerd, waddup?') print('Tell me your name:') myName = input() # Assigns whatever you type to the myName variable print('Nice to meet you, ' + myName + '!') # Print text with a variable name print('Your name consists of this many characters: ') print(len(myName)) # len() counts the characters in the myName variable print('Now then, tell me your age in years: ') myAge = input() # A stupid dad-joke to show how arithmetic works. # Note the int() - This makes sure you can calculate a value # The calculation takes place inside a str() # - since we are trying to print a string, it should be a str() print("Well, " + myName + "... You will be " + str(int(myAge) + 1) + " in a year.." )
class Solution: def isRectangleCover(self, rectangles: List[List[int]]) -> bool: points={} for r in rectangles: vs=[tuple(r[:2]), (r[2],r[1]), tuple(r[2:]), (r[0],r[3])] for i in range(len(vs)): v=vs[i] if v not in points: points[v]=[False]*4 if points[v][i]: return False points[v][i]=True singleDirection=0 for k,v in points.items(): quadrant=sum(x for x in v if x==True) if quadrant==1: singleDirection+=1 elif quadrant==2 and v[0]==v[2]: return False elif quadrant==3: return False if singleDirection==4: return True return False
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ nums = sorted(nums1 + nums2) n = len(nums) middle = n // 2 if n % 2 == 0: return (nums[middle - 1] + nums[middle]) / 2.0 else: return nums[middle]
def complement(num): """ Find the non-zero padded binary compelement. """ if not num: return 1 i = 1 while i <= num: num ^= i i = i << 1 return num
hugehairypants = ['огромные', 'волосатые', 'штаны'] for i in hugehairypants: print(i) print(i) input()
aUser = input("Please enter the first integer: ") bUser = input("Please enter the second integer: ") cUser = input("Please enter the third integer: ") # Compare Inputs def compareInput(aUser, bUser, cUser): aUser = integerCheck(aUser) bUser = integerCheck(bUser) cUser = integerCheck(cUser) if aUser >= bUser and bUser >= cUser: inputSorted = str(cUser) + " " + str(bUser) + " " + str(aUser) elif aUser >= cUser and cUser >= bUser: inputSorted = str(bUser) + " " + str(cUser) + " " + str(aUser) elif bUser >= aUser and aUser >= cUser: inputSorted = str(cUser) + " " + str(aUser) + " " + str(bUser) elif bUser >= cUser and cUser >= aUser: inputSorted = str(aUser) + " " + str(cUser) + " " + str(bUser) elif cUser >= bUser and bUser >= aUser: inputSorted = str(aUser) + " " + str(bUser) + " " + str(cUser) elif cUser >= aUser and aUser >= bUser: inputSorted = str(bUser) + " " + str(aUser) + " " + str(cUser) return inputSorted # Error Check def integerCheck(value): try: return int(value) except Exception: print("Please input a valid Integer!") quit() def printResults(inputSorted): print("Input three integer numbers in ascending order:\n" + inputSorted) inputSorted = compareInput(aUser, bUser, cUser) printResults(inputSorted)
""" File that contains exceptions for molecules that need to have different multiplicity/spin or symmetry configurations than the defaults set by Gaussian or other Quantum Chemistry programs Ex: CH2 radical, O2, OH radical """ # species # 320320000000000000001 = O2 # 140260020000000000001 = CH2 # 170170000000000000002 = OH # 320000000000000000001 = S def get_spin(chemid, spin): # spin as defined in molpro = 2S if chemid == '320320000000000000001': spin = 2 elif chemid == '140260020000000000001': spin = 2 elif chemid == '170170000000000000002': spin == 2 else: spin = spin return spin def get_multiplicity(chemid, mult): # 2S+1 if chemid == '320320000000000000001': mult = 3 elif chemid == '140260020000000000001': mult = 3 elif chemid == '170170000000000000002': mult = 3 else: mult = mult return mult def get_symm(chemid, symm): # molpro symm defined by point group if chemid == '320320000000000000001': symm = 1 # used Ag state, label = 1 for molpro elif chemid == '140260020000000000001': symm = 2 # B1 state, C2V symmetry, label = 2 for molpro elif chemid == '170170000000000000002': symm = 2 # 2Pi state ~ using B state = 2 for molpro else: symm = symm return symm
class MgraphConnectoSiteMixin: def get_root_site(self): return self.get('/sites/root') def get_site(self, site_id): return self.get(f'/sites/{site_id}') def get_site_drive(self, site_id): return self.get(f'/sites/{site_id}/drive') def get_site_drives(self, site_id): res = self.get(f'/sites/{site_id}/drives') if 'value' in res: return res['value'] return [] def search_sites(self, site_name): res = self.get(f'/sites?search={site_name}') if 'value' in res: return res['value'] return [] def get_subsites(self, site_id): return self.get(f'/sites/{site_id}/sites') def walk_sites(self, site=None): # FIXME make this a generator if site is None: site = self.get_root_site() self.sites = {} self.sites[site['id']] = site subsites = self.get_subsites(site['id']) # jdump(subsites, caller=__file__) if 'value' in subsites: for subsite in subsites['value']: self.sites[subsite['id']] = subsite self.walk_sites(site=subsite) return self.sites
dictionary = { "1": "一,one", "2": "丨,line", "3": "丶,dot", "4": "丿,slash", "5": "乙,second", "6": "亅,hook", "7": "二,two", "8": "亠,lid", "9": "人,man", "10": "儿,son, legs", "11": "入,enter", "12": "八,eight", "13": "冂,wide", "14": "冖,cloth cover", "15": "冫,ice", "16": "几,table", "17": "凵,receptacle", "18": "刀,knife", "19": "力,power", "20": "勹,wrap", "21": "匕,spoon", "22": "匚,box", "23": "匸,hiding enclosure", "24": "十,ten", "25": "卜,divination", "26": "卩,seal (device)", "27": "厂,cliff", "28": "厶,private", "29": "又,again", "30": "口,mouth", "31": "囗,enclosure", "32": "土,earth", "33": "士,scholar", "34": "夂,go", "35": "夊,go slowly", "36": "夕,evening", "37": "大,big", "38": "女,woman", "39": "子,child", "40": "宀,roof", "41": "寸,inch", "42": "小,small", "43": "尢,lame", "44": "尸,corpse", "45": "屮,sprout", "46": "山,mountain", "47": "巛,river", "48": "工,work", "49": "己,oneself", "50": "巾,turban", "51": "干,dry", "52": "幺,short thread", "53": "广,dotted cliff", "54": "廴,long stride", "55": "廾,arch", "56": "弋,shoot", "57": "弓,bow", "58": "彐,snout", "59": "彡,bristle", "60": "彳,step", "61": "心,heart", "62": "戈,halberd", "63": "戶,door", "64": "手,hand", "65": "支,branch", "66": "攴,rap, tap", "67": "文,script", "68": "斗,dipper", "69": "斤,axe", "70": "方,square", "71": "无,not", "72": "日,sun", "73": "曰,say", "74": "月,moon", "75": "木,tree", "76": "欠,lack", "77": "止,stop", "78": "歹,death", "79": "殳,weapon", "80": "毋,do not", "81": "比,compare", "82": "毛,fur", "83": "氏,clan", "84": "气,steam", "85": "水,water", "86": "火,fire", "87": "爪,claw", "88": "父,father", "89": "爻,Trigrams", "90": "爿,split wood", "91": "片,slice", "92": "牙,fang", "93": "牛,cow", "94": "犬,dog", "95": "玄,profound", "96": "玉,jade", "97": "瓜,melon", "98": "瓦,tile", "99": "甘,sweet", "100": "生,life", "101": "用,use", "102": "田,field", "103": "疋,bolt of cloth", "104": "疒,sickness", "105": "癶,footsteps", "106": "白,white", "107": "皮,skin", "108": "皿,dish", "109": "目,eye", "110": "矛,spear", "111": "矢,arrow", "112": "石,stone", "113": "示,spirit", "114": "禸,track", "115": "禾,grain", "116": "穴,cave", "117": "立,stand", "118": "竹,bamboo", "119": "米,rice", "120": "糸,silk", "121": "缶,jar", "122": "网,net", "123": "羊,sheep", "124": "羽,feather", "125": "老,old", "126": "而,and", "127": "耒,plow", "128": "耳,ear", "129": "聿,brush", "130": "肉,meat", "131": "臣,minister", "132": "自,self", "133": "至,arrive", "134": "臼,mortar", "135": "舌,tongue", "136": "舛,oppose", "137": "舟,boat", "138": "艮,stopping", "139": "色,color", "140": "艸,grass", "141": "虍,tiger", "142": "虫,insect", "143": "血,blood", "144": "行,walk enclosure", "145": "衣,clothes", "146": "襾,cover", "147": "見,see", "148": "角,horn", "149": "言,speech", "150": "谷,valley", "151": "豆,bean", "152": "豕,pig", "153": "豸,badger", "154": "貝,shell", "155": "赤,red", "156": "走,run", "157": "足,foot", "158": "身,body", "159": "車,cart", "160": "辛,bitter", "161": "辰,morning", "162": "辵,walk", "163": "邑,city", "164": "酉,wine", "165": "釆,distinguish", "166": "里,village", "167": "金,gold", "168": "長,long", "169": "門,gate", "170": "阜,mound", "171": "隶,slave", "172": "隹,short-tailed bird", "173": "雨,rain", "174": "靑,blue", "175": "非,wrong", "176": "面,face", "177": "革,leather", "178": "韋,tanned leather", "179": "韭,leek", "180": "音,sound", "181": "頁,leaf", "182": "風,wind", "183": "飛,fly", "184": "食,eat", "185": "首,head", "186": "香,fragrant", "187": "馬,horse", "188": "骨,bone", "189": "高,tall", "190": "髟,hair", "191": "鬥,fight", "192": "鬯,sacrificial wine", "193": "鬲,cauldron", "194": "鬼,ghost", "195": "魚,fish", "196": "鳥,bird", "197": "鹵,salt", "198": "鹿,deer", "199": "麥,wheat", "200": "麻,hemp", "201": "黃,yellow", "202": "黍,millet", "203": "黑,black", "204": "黹,embroidery", "205": "黽,frog", "206": "鼎,tripod", "207": "鼓,drum", "208": "鼠,rat", "209": "鼻,nose", "210": "齊,even", "211": "齒,tooth", "212": "龍,dragon", "213": "龜,turtle", "214": "龠,flute", }
game = { 'columns': 8, 'rows': 8, 'fps': 30, 'countdown': 5, 'interval': 800, 'score_increment': 1, 'level_increment': 8, 'interval_increment': 50 }
''' Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. Follow up: Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? Example: Input: nums = [1,2,1,3,2,5] Output: [3,5] Explanation: [5, 3] is also a valid answer. Example: Input: nums = [-1,0] Output: [-1,0] Example: Input: nums = [0,1] Output: [1,0] Constraints: - 2 <= nums.length <= 3 * 10^4 - -2^31 <= nums[i] <= 2^31 - 1 - Each integer in nums will appear twice, only two integers will appear once. ''' #Difficulty: Medium #32 / 32 test cases passed. #Runtime: 56 ms #Memory Usage: 16.2 MB #Runtime: 56 ms, faster than 82.01% of Python3 online submissions for Single Number III. #Memory Usage: 16.2 MB, less than 21.37% of Python3 online submissions for Single Number III. class Solution: def singleNumber(self, nums: List[int]) -> List[int]: single = set() for num in nums: if num not in single: single.add(num) else: single.remove(num) return single
# Write a method to replace all spaces in a string s with '%20'. # You my assume that the string has sufficient space at the end to hold # the additional characters, and that you are given the "true" # length of the string. # Naive Solution (In this case the less beautiful solution) # Runtime O(n) def naiveURLify(s): outputString = "" for character in s: if character == " ": outputString += "%20" else: outputString += character return outputString # Efficient # Runtime O(n) def efficientUrlify(s): return s.replace(" ", "%20") inputString = "Hello world! How are we doing?" print(naiveURLify(inputString)) print(efficientUrlify(inputString))
StampManifestProvider = provider(fields = ["stamp_enabled"]) def _impl(ctx): return StampManifestProvider(stamp_enabled = ctx.build_setting_value) stamp_manifest = rule( implementation = _impl, build_setting = config.bool(flag = True), )
#first line opening when chat starts def chat_opening(): """Prints an opening line and checks if user returns proper response to determine if the chatbot should be started.""" msg = input("Would you like to learn about how animals migrate throughout and across the world? [Y/N]\nINPUT: ") msg = msg.lower() possible_replies = ['yes', 'y', 'sure', 'okay', 'yeah'] for reply in possible_replies: if msg == reply: return True return False #main menu that includes only animal categories def print_menu(): """Prints main categories of animals""" animal_menu = {'1': 'Fish', '2': 'Birds', '3': 'Mammals', '4': 'Insects', '5': 'Exit'} print('Learn about Animal Migration Patterns!!\nChoose a category...') for key in animal_menu: print(key + ". " + animal_menu[key]) def menu_choice(): """Checks what category user wants and sets a variable equal to a list of animals for that specific category. Returns True if user selects an animal category and continues asking if something other than numbers isn't inputted""" loop = chat_opening() if loop == False: return [None, None, False] while loop: print_menu() choice = input('INPUT: ') #choice needs to equate to a string because input takes string and not int if choice == '1': fish.print_intro() animal = 'fish' animal_set = fish_set return [animal, animal_set, True] break elif choice == '2': bird.print_intro() animal = 'bird' animal_set = bird_set return [animal, animal_set, True] break elif choice == '3': mammal.print_intro() animal = 'mammal' animal_set = mammal_set return [animal, animal_set, True] break elif choice == '4': insect.print_intro() animal = 'insect' animal_set = insect_set return [animal, animal_set, True] break elif choice == '5': print('Exiting. Thanks for visiting!') return [None, None, False] break else: print('Invalid selection. Enter any new key to continue: ') #secondary menu once animal category is chosen def category_menu(animal, animal_set): """Prints the secondary menu and returns the number for the specific animal chosen so that instance can be indexed.""" print_category_menu(animal, animal_set) animal_number = input() animal_number = remove_punctuation(animal_number) return animal_number #specific secondary menu function which takes in the list of animals for the respective category def print_category_menu(animal, animal_set): """General function to print secondary menu which takes in the animal list returned in menu_choice""" print('Which specific ' + animal + ' would you like learn about?\n') counter = 1 for each in animal_set: counter = str(counter) print(counter + ". " + each.name) counter = int(counter) + 1
class Solution: """ @param x: a double @return: the square root of x """ def sqrt(self, x): # write your code here start = 1 end = x if x < 1: start = x end = 1 while (end - start > 1e-10): mid = start + (end - start) / 2 if (mid * mid < x): start = mid elif (mid * mid > x): end = mid else: break return start
nono = int(input('Digite um número: ')) cont = contn = 0 while not nono == 101: cont += 1 contn += nono nono = int(input('Digite um número: ')) print(f'Você digitou {cont} vezes.') print(f'A soma dos números digitados é de {contn}')
# -*- coding: utf-8 -*- # ------------- Comparaciones ------------- print (7 < 5) # Falso print (7 > 5) # Verdadero print ((11 * 3) + 2 == 36 - 1) # Verdadero print ((11 * 3) + 2 >= 36) # Falso print ("curso" != "CuRsO") # Verdadero print (5 and 4) #Operacion en binario print (5 or 4) print (not(4 > 3)) print (True) print (False)
# -*- coding: utf-8 -*- # Hpo terms represents data from the hpo web hpo_term = dict( _id = str, # Same as hpo_id hpo_id = str, # Required aliases = list, # List of aliases description = str, genes = list, # List with integers that are hgnc_ids ) # Disease terms represent diseases collected from omim, orphanet and decipher. # Collected from OMIM disease_term = dict( _id = str, # Same as disease_id disease_id = str, # required, like OMIM:600233 disase_nr = int, # The disease nr description = str, # required source = str, # required genes = list, # List with integers that are hgnc_ids ) # phenotype_term is a special object to hold information on case level # This one might be deprecated when we skip mongoengine phenotype_term = dict( phenotype_id = str, # Can be omim_id hpo_id feature = str, disease_models = list, # list of strings )
# pylint: skip-file # flake8: noqa # pylint: disable=too-many-instance-attributes class OCEnv(OpenShiftCLI): ''' Class to wrap the oc command line tools ''' container_path = {"pod": "spec.containers[0].env", "dc": "spec.template.spec.containers[0].env", "rc": "spec.template.spec.containers[0].env", } # pylint allows 5. we need 6 # pylint: disable=too-many-arguments def __init__(self, namespace, kind, env_vars, resource_name=None, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False): ''' Constructor for OpenshiftOC ''' super(OCEnv, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose) self.kind = kind self.name = resource_name self.env_vars = env_vars self._resource = None @property def resource(self): ''' property function for resource var''' if not self._resource: self.get() return self._resource @resource.setter def resource(self, data): ''' setter function for resource var''' self._resource = data def key_value_exists(self, key, value): ''' return whether a key, value pair exists ''' return self.resource.exists_env_value(key, value) def key_exists(self, key): ''' return whether a key exists ''' return self.resource.exists_env_key(key) def get(self): '''return environment variables ''' result = self._get(self.kind, self.name) if result['returncode'] == 0: if self.kind == 'dc': self.resource = DeploymentConfig(content=result['results'][0]) result['results'] = self.resource.get(OCEnv.container_path[self.kind]) or [] return result def delete(self): ''' delete environment variables ''' if self.resource.delete_env_var(self.env_vars.keys()): return self._replace_content(self.kind, self.name, self.resource.yaml_dict) return {'returncode': 0, 'changed': False} def put(self): '''place env vars into dc ''' for update_key, update_value in self.env_vars.items(): self.resource.update_env_var(update_key, update_value) return self._replace_content(self.kind, self.name, self.resource.yaml_dict) # pylint: disable=too-many-return-statements @staticmethod def run_ansible(params, check_mode): '''run the oc_env module''' ocenv = OCEnv(params['namespace'], params['kind'], params['env_vars'], resource_name=params['name'], kubeconfig=params['kubeconfig'], verbose=params['debug']) state = params['state'] api_rval = ocenv.get() ##### # Get ##### if state == 'list': return {'changed': False, 'results': api_rval['results'], 'state': "list"} ######## # Delete ######## if state == 'absent': for key in params.get('env_vars', {}).keys(): if ocenv.resource.exists_env_key(key): if check_mode: return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a delete.'} api_rval = ocenv.delete() return {'changed': True, 'state': 'absent'} return {'changed': False, 'state': 'absent'} if state == 'present': ######## # Create ######## for key, value in params.get('env_vars', {}).items(): if not ocenv.key_value_exists(key, value): if check_mode: return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a create.'} # Create it here api_rval = ocenv.put() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} # return the created object api_rval = ocenv.get() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} return {'changed': True, 'results': api_rval['results'], 'state': 'present'} return {'changed': False, 'results': api_rval['results'], 'state': 'present'} return {'failed': True, 'changed': False, 'msg': 'Unknown state passed. %s' % state}
class node: def __init__(self,key): self.left = None self.right = None self.val = key def PreOrder(root): if root: print(root.val, end = " ") PreOrder(root.left) PreOrder(root.right) root = node(1) root.left = node(2) root.right = node(3) root.left.left = node(4) root.left.right = node(5) root.right.left = node(6) root.right.right = node(7) print("Pre Order traversal of tree is", end = " ") PreOrder(root) ''' Output Pre Order traversal of tree is 1 2 4 5 3 6 7 '''
# O(N) time, N -> no. of people in the orgChart # O(d) time, d -> depth of the OrgChart/orgTree def getLowestCommonManager(topManager, reportOne, reportTwo): # Write your code here. return getOrgInfo(topManager, reportOne, reportTwo).lowestCommonManager def getOrgInfo(manager, reportOne, reportTwo): numberImpReports = 0 for directReport in manager.directReports: print(manager.name, directReport.name) orgInfo = getOrgInfo(directReport, reportOne, reportTwo) if orgInfo.lowestCommonManager is not None: # if this is our lowestCommonManager, then we return return orgInfo numberImpReports += orgInfo.numberImpReports # if we, as a manager, have any of the direct reports, then we increase the count since we have it if manager == reportOne or manager == reportTwo: # it is possible that the manager was one of the imp reports numberImpReports+=1 lowestCommonManager = manager if numberImpReports == 2 else None return OrgInfo(lowestCommonManager, numberImpReports) # pass this count to its parent/manager class OrgInfo: def __init__(self, lowestCommonManager, numberImpReports): self.lowestCommonManager = lowestCommonManager self.numberImpReports = numberImpReports # This is an input class. Do not edit. class OrgChart: def __init__(self, name): self.name = name self.directReports = []
def method1(ll: list, n: int) -> int: s = set() ans = 0 for ele in ll: s.add(ele) for i in range(n): if (ll[i] - 1) not in s: j = ll[i] while j in s: j += 1 ans = max(ans, j - ll[i]) return ans if __name__ == "__main__": """ from timeit import timeit n = 7 ll = [1, 9, 3, 10, 4, 20, 2] print(timeit(lambda: method1(ll, n), number=10000)) # 0.021972083995933644 """
class Endpoint: RESOURCE_MANAGEMENT = "https://management.azure.com" RESOURCE_LOG_API = "https://api.loganalytics.io" GET_AUTH_TOKEN = "https://login.microsoftonline.com/{}/oauth2/token" # nosec GET_SHARED_KEY = ( RESOURCE_MANAGEMENT + "/subscriptions/{}/resourcegroups/{}/providers/Microsoft.OperationalInsights/workspaces/{}/sharedKeys?api-version={}" ) GET_WORKSPACE_ID = ( RESOURCE_MANAGEMENT + "/subscriptions/{}/resourcegroups/{}/providers/Microsoft.OperationalInsights/workspaces/{}?api-version={}" ) SEND_LOG_DATA = "https://{}.ods.opinsights.azure.com/api/logs?api-version={}" GET_LOG_DATA = RESOURCE_LOG_API + "/{}/workspaces/{}/query"
class ContactHelper: def __init__(self, app): self.app = app def open_home_page(self): wd = self.app.wd self.app.open_home_page() def open_add_contact(self): wd = self.app.wd # open add contact page wd.find_element_by_link_text("add new").click() def create_new_contact(self, add_contact): wd = self.app.wd self.open_add_contact() # fill up new contact form wd.find_element_by_name("firstname").click() wd.find_element_by_name("firstname").clear() wd.find_element_by_name("firstname").send_keys(add_contact.name) wd.find_element_by_name("middlename").click() wd.find_element_by_name("middlename").clear() wd.find_element_by_name("middlename").send_keys("O") wd.find_element_by_name("lastname").click() wd.find_element_by_name("lastname").clear() wd.find_element_by_name("lastname").send_keys(add_contact.lastname) wd.find_element_by_name("nickname").click() wd.find_element_by_name("nickname").clear() wd.find_element_by_name("nickname").send_keys("Alex") wd.find_element_by_name("title").click() wd.find_element_by_name("title").clear() wd.find_element_by_name("title").send_keys("mr") wd.find_element_by_name("company").click() wd.find_element_by_name("company").clear() wd.find_element_by_name("company").send_keys("GS") wd.find_element_by_name("address").click() wd.find_element_by_name("address").clear() wd.find_element_by_name("address").send_keys(add_contact.address) wd.find_element_by_name("home").click() wd.find_element_by_name("home").clear() wd.find_element_by_name("home").send_keys("98347974824") wd.find_element_by_name("mobile").click() wd.find_element_by_name("mobile").clear() wd.find_element_by_name("mobile").send_keys("3498374328") wd.find_element_by_name("work").click() wd.find_element_by_name("work").clear() wd.find_element_by_name("work").send_keys("23649873289") wd.find_element_by_name("fax").click() wd.find_element_by_name("fax").clear() wd.find_element_by_name("fax").send_keys("3487932874832") wd.find_element_by_name("email").click() wd.find_element_by_name("email").clear() wd.find_element_by_name("email").send_keys("alex@mail.ru") wd.find_element_by_name("email2").click() wd.find_element_by_name("email2").clear() wd.find_element_by_name("email2").send_keys("alex1@mail.ru") wd.find_element_by_name("email3").click() wd.find_element_by_name("email3").clear() wd.find_element_by_name("email3").send_keys("alex3@mail.ru") wd.find_element_by_name("homepage").click() wd.find_element_by_name("homepage").clear() wd.find_element_by_name("homepage").send_keys("alex1.site.com") wd.find_element_by_name("bday").click() #Select(wd.find_element_by_name("bday")).select_by_visible_text("15") #wd.find_element_by_xpath("//option[@value='15']").click() #wd.find_element_by_name("bmonth").click() #Select(wd.find_element_by_name("bmonth")).select_by_visible_text("June") #wd.find_element_by_xpath("//option[@value='June']").click() #wd.find_element_by_name("byear").click() #wd.find_element_by_name("byear").clear() #wd.find_element_by_name("byear").send_keys("1969") #wd.find_element_by_name("aday").click() #Select(wd.find_element_by_name("aday")).select_by_visible_text("10") #wd.find_element_by_xpath("(//option[@value='10'])[2]").click() #wd.find_element_by_name("amonth").click() #Select(wd.find_element_by_name("amonth")).select_by_visible_text("November") #wd.find_element_by_xpath("(//option[@value='November'])[2]").click() wd.find_element_by_name("ayear").click() wd.find_element_by_name("ayear").clear() wd.find_element_by_name("ayear").send_keys("1970") wd.find_element_by_name("address2").click() wd.find_element_by_name("address2").clear() wd.find_element_by_name("address2").send_keys("12 road") wd.find_element_by_name("notes").click() wd.find_element_by_name("notes").clear() wd.find_element_by_name("notes").send_keys("notes 123") # submit contact creation wd.find_element_by_xpath("(//input[@name='submit'])[2]").click() def delete_first_contact(self): wd = self.app.wd self.open_home_page() # select first contact wd.find_element_by_name("selected[]").click() # submit deletion #wd.find_element_by_name("Delete").click() wd.find_element_by_xpath("//input[@value='Delete']").click() wd.switch_to_alert().accept() self.return_to_home_page() def return_to_home_page(self): wd = self.app.wd wd.find_element_by_link_text("groups").click()
""" categories: Types,list description: List delete with step != 1 not implemented cause: Unknown workaround: Use explicit loop for this rare operation. """ l = [1, 2, 3, 4] del l[0:4:2] print(l)
def makeString(): fo = open(r"C:\Users\Owner\Tales-of-Destiny-DC\dictionary\kanji.txt", "r", encoding="utf8") Lines = fo.readlines() for line in Lines: print(createString(line[0:4], line[6])) def createString(one, two): return """ elif(Hex[i] + Hex[i+1] + \" \" + Hex[i+3] + Hex[i+4] == \"""" + one[0:2] + " " + one[2:] + """\"): List.append(\"""" + two + """\")""" makeString()
# -*- coding: utf-8 -*- """ shellstreaming.scheduler.master_sched_firstnode ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :synopsis: Schedules all jobs to first worker in list (for testing purpose) """ def calc_job_placement(job_graph, worker_hosts, prev_jobs_placement): next_jobs_placement = prev_jobs_placement.copy() for job_id in job_graph.nodes_iter(): # start not started & finished job if not prev_jobs_placement.is_started(job_id) and not prev_jobs_placement.is_finished(job_id): # fixed job fixed_workers = prev_jobs_placement.fixed_to(job_id) if fixed_workers is not None: map(lambda w: next_jobs_placement.assign(job_id, w), fixed_workers) continue # normal job next_jobs_placement.assign(job_id, worker_hosts[0]) return next_jobs_placement
'''Escreva um programa que pergunte o sálario de um funcionario e calcule o valor do seu aumento. Para salarios superiores a R$1.250,00, calcule um aumento de 10%. Para os inferiores ou iguais. o aumento é de 15%.''' salario = float(input("Digite o salario do funcionario: R$")) if salario <= 1250: novosalario = salario + (salario * 0.15) if salario > 1250: novosalario = salario + (salario * 0.10) print(f"O aumento do salario do funcionario sera de R$\033[1;32m{novosalario:,.2f}\033[m")
""" This is helper file to print out strings in different colours """ def style(value, styling): return styling + value + '\033[0m' def green(value): return style(value, '\033[92m') def blue(value): return style(value, '\033[94m') def yellow(value): return style(value, '\033[93m') def red(value): return style(value, '\033[91m') def pink(value): return style(value, '\033[95m') def bold(value): return style(value, '\033[1m') def underline(value): return style(value, '\033[4m')
#******************************************************************************* # # Sentence pattern definitions # #******************************************************************************* sentencePatterns = [ [ 'nMass is the driver of nMass.', 'nMass is the nTheXOf of nMass, and of us.', 'You and I are nPersonPlural of the nCosmos.', 'We exist as fixedNP.', 'We viPerson, we viPerson, we are reborn.', 'Nothing is impossible.', 'This life is nothing short of a ing nOf of adj nMass.', 'Consciousness consists of fixedNP of quantum energy. "Quantum" means a ing of the adj.', 'The goal of fixedNP is to plant the seeds of nMass rather than nMassBad.', 'nMass is a constant.', 'By ing, we viPerson.', 'The nCosmos is adjWith fixedNP.', 'To vTraverse the nPath is to become one with it.', 'Today, science tells us that the essence of nature is nMass.', 'nMass requires exploration.' ], [ 'We can no longer afford to live with nMassBad.', 'Without nMass, one cannot viPerson.', 'Only a nPerson of the nCosmos may vtMass this nOf of nMass.', 'You must take a stand against nMassBad.', 'Yes, it is possible to vtDestroy the things that can vtDestroy us, but not without nMass on our side.', 'nMassBad is the antithesis of nMass.', 'You may be ruled by nMassBad without realizing it. Do not let it vtDestroy the nTheXOf of your nPath.', 'The complexity of the present time seems to demand a ing of our nOurPlural if we are going to survive.', 'nMassBad is born in the gap where nMass has been excluded.', 'Where there is nMassBad, nMass cannot thrive.' ], [ 'Soon there will be a ing of nMass the likes of which the nCosmos has never seen.', 'It is time to take nMass to the next level.', 'Imagine a ing of what could be.', 'Eons from now, we nPersonPlural will viPerson like never before as we are ppPerson by the nCosmos.', 'It is a sign of things to come.', 'The future will be a adj ing of nMass.', 'This nPath never ends.', 'We must learn how to lead adj lives in the face of nMassBad.', 'We must vtPerson ourselves and vtPerson others.', 'The nOf of nMass is now happening worldwide.', 'We are being called to explore the nCosmos itself as an interface between nMass and nMass.', 'It is in ing that we are ppPerson.', 'The nCosmos is approaching a tipping point.', 'nameOfGod will vOpenUp adj nMass.' ], [ 'Although you may not realize it, you are adj.', 'nPerson, look within and vtPerson yourself.', 'Have you found your nPath?', 'How should you navigate this adj nCosmos?', 'It can be difficult to know where to begin.', 'If you have never experienced this nOf fixedAdvP, it can be difficult to viPerson.', 'The nCosmos is calling to you via fixedNP. Can you hear it?' ], [ 'Throughout history, humans have been interacting with the nCosmos via fixedNP.', 'Reality has always been adjWith nPersonPlural whose nOurPlural are ppThingPrep nMass.', 'Our conversations with other nPersonPlural have led to a ing of adjPrefix adj consciousness.', 'Humankind has nothing to lose.', 'We are in the midst of a adj ing of nMass that will vOpenUp the nCosmos itself.', 'Who are we? Where on the great nPath will we be ppPerson?', 'We are at a crossroads of nMass and nMassBad.' ], [ 'Through nSubject, our nOurPlural are ppThingPrep nMass.', 'nSubject may be the solution to what\'s holding you back from a adjBig nOf of nMass.', 'You will soon be ppPerson by a power deep within yourself - a power that is adj, adj.', 'As you viPerson, you will enter into infinite nMass that transcends understanding.', 'This is the vision behind our 100% adjProduct, adjProduct nProduct.', 'With our adjProduct nProduct, nBenefits is only the beginning.' ] ]
''' URL: https://leetcode.com/problems/count-largest-group/ Difficulty: Easy Description: Count Largest Group Given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return how many groups have the largest size. Example 1: Input: n = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: [1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with largest size. Example 2: Input: n = 2 Output: 2 Explanation: There are 2 groups [1], [2] of size 1. Example 3: Input: n = 15 Output: 6 Example 4: Input: n = 24 Output: 5 Constraints: 1 <= n <= 10^4 ''' class Solution: def sumOfDigits(self, n): sum = 0 while n > 0: sum += n % 10 n = n // 10 return sum def countLargestGroup(self, n): counts = {} for i in range(1, n+1): # sum of the digits of n sum = self.sumOfDigits(i) if sum in counts: counts[sum].append(i) else: # if sum is not in dict # store in format # key: sum # value: [ All the elements that sum to that size ] counts[sum] = [i] largestGroupSize = -float('inf') largestGroupCount = 0 for group in counts.values(): size = len(group) if size > largestGroupSize: largestGroupSize = size largestGroupCount = 1 elif size == largestGroupSize: largestGroupCount += 1 return largestGroupCount
class ResponseCodeError(Exception): """请求返回 code 不为 0""" def __init__(self, code: int, msg: str, data: dict): self.code = code self.msg = msg self.data = data def __repr__(self) -> str: return f"错误码: {self.code}, 信息: {self.msg}" def __str__(self) -> str: return self.__repr__() class AuthParamError(Exception): """缺少必要鉴权参数""" def __init__(self, *params: str): self.params = params def __repr__(self) -> str: return f"缺少鉴权参数 {', '.join(self.params)}" def __str__(self) -> str: return self.__repr__() class AuthTypeError(Exception): """鉴权类型错误""" def __init__(self, auth_type: str): self.auth_type = auth_type def __repr__(self) -> str: return f"'{self.auth_type}' 是当前不支持的鉴权类型" def __str__(self) -> str: return self.__repr__() if __name__ == "__main__": raise ValueError("test") raise AuthParamError("hehe", "heihei", "233")