content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
c.NbServer.base_url = '/paws-public/' c.NbServer.bind_ip = '0.0.0.0' c.NbServer.bind_port = 8000 c.NbServer.publisher_class = 'paws.PAWSPublisher' c.NbServer.register_proxy = False c.PAWSPublisher.base_path = '/data/project/paws/userhomes'
c.NbServer.base_url = '/paws-public/' c.NbServer.bind_ip = '0.0.0.0' c.NbServer.bind_port = 8000 c.NbServer.publisher_class = 'paws.PAWSPublisher' c.NbServer.register_proxy = False c.PAWSPublisher.base_path = '/data/project/paws/userhomes'
del_items(0x800A0E14) SetType(0x800A0E14, "char StrDate[12]") del_items(0x800A0E20) SetType(0x800A0E20, "char StrTime[9]") del_items(0x800A0E2C) SetType(0x800A0E2C, "char *Words[118]") del_items(0x800A1004) SetType(0x800A1004, "struct MONTH_DAYS MonDays[12]")
del_items(2148142612) set_type(2148142612, 'char StrDate[12]') del_items(2148142624) set_type(2148142624, 'char StrTime[9]') del_items(2148142636) set_type(2148142636, 'char *Words[118]') del_items(2148143108) set_type(2148143108, 'struct MONTH_DAYS MonDays[12]')
# Excel Column Number # https://www.interviewbit.com/problems/excel-column-number/ # # Given a column title as appears in an Excel sheet, return its corresponding # column number. # # Example: # # A -> 1 # # B -> 2 # # C -> 3 # # ... # # Z -> 26 # # AA -> 27 # # AB -> 28 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # class Solution: # @param A : string # @return an integer def titleToNumber(self, A): res = 0 for char in A: diff = ord(char) - ord('A') + 1 res = res * 26 + diff return res # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if __name__ == "__main__": s = Solution() print(s.titleToNumber('AA')) print(s.titleToNumber('A'))
class Solution: def title_to_number(self, A): res = 0 for char in A: diff = ord(char) - ord('A') + 1 res = res * 26 + diff return res if __name__ == '__main__': s = solution() print(s.titleToNumber('AA')) print(s.titleToNumber('A'))
ENV = 'testing' DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/flask_example_test' SQLALCHEMY_TRACK_MODIFICATIONS = False ERROR_404_HELP = False
env = 'testing' debug = True testing = True sqlalchemy_database_uri = 'postgresql://localhost/flask_example_test' sqlalchemy_track_modifications = False error_404_help = False
""" Implementation of a labeled property graph. """ # =================================== # TODO: Number of relationships a node has # TODO: Number of nodes that have a given relationship # TODO: Number of nodes with a relationship # TODO: Number of nodes with a label # TODO: Traversals: # - Depth first # - Breadth-first # - Dijkstra's # - A* # TODO: Need __repr__ for the lpg class itself # =================================== class Node: """Node object that will have a relationship to other nodes.""" def __init__(self, name): """Initialized nodes contain properties and methods to view them.""" self.name = name self.properties = {} self.labels = [] def __getitem__(self, key): """Get node properties.""" return self.properties[key] def add_property(self, property_, value): """Method to add a property to a node.""" if property_ in self.properties: raise KeyError("Property already exists, use change_property()" "to alter property value") self.properties[property_] = value def change_property(self, property_, value): """Method to alter a value on a property.""" if property_ not in self.properties: raise AttributeError("Property does not exist, use add_property()" "to add a property") self.properties[property_] = value def remove_property(self, property_): """Method to remove a property from a node.""" if property_ not in self.properties: raise AttributeError("Node does not contain that property") del self.properties[property_] def add_label(self, label): """Adds a label to the node.""" if label in self.labels: raise ValueError('Label already set on node.') self.labels.append(label) def remove_label(self, label): """Removes a label from a node.""" self.labels.remove(label) def __repr__(self): """Show the properties of the node.""" props = "Name: {}\nProperties:".format(self.name) for key, value in self.properties.items(): props += '\r{}: {}'.format(key, value) return props class Relationship: """Relationship object that will be able to have properties as well.""" def __init__(self, name): """Initialize relationships as to contain properites like nodes.""" self.name = name self.properties = {} self.labels = [] def add_property(self, property_, value): """Method to add a property to a node.""" if property_ in self.properties: raise KeyError("Property already exists, use change_property()" "to alter property value") self.properties[property_] = value def change_property(self, property_, value): """Method to alter a value on a property.""" if property_ not in self.properties: raise AttributeError("Property does not exist, use add_property()" "to add a property") self.properties[property_] = value def remove_property(self, property_): """Method to remove a property from a node.""" if property_ not in self.properties: raise AttributeError("Node does not contain that property") del self.properties[property_] def add_label(self, label): """Adds a label to the node.""" if label in self.labels: raise ValueError('Label already set on node.') self.labels.append(label) def remove_label(self, label): """Removes a label from a node.""" self.labels.remove(label) def __repr__(self): """Show the properties of the node.""" props = "Name: {}\nProperties:" for key, value in self.properties.items(): props += '\r{}: {}'.format(key, value) return props class LabeledPropertyGraph: """Define a labeled property graph as dictionary composition.""" def __init__(self): """Initialize the graph as a dictionary.""" self._graph = {} self._nodes = {} self._relationships = {} def __getitem__(self, key): """Return _graphat key.""" return self._nodes[key] # Consider property decorator def nodes(self): """Return a list of nodes in the graph.""" return [node for node in self._nodes.keys()] def unique_relationships(self): """Return list of unique relationships.""" # This will likely not return what I'm looking for. return [relationship for relationship in self._relationships.keys()] def add_node(self, name): """Add a node and pass the name to the node.name.""" if name in self.nodes(): raise KeyError('Node already exists in graph') node = Node(name) self._graph[name] = {} self._nodes[name] = node def add_relationship(self, name, node_a, node_b, both_ways=False): """Refactored add_relationship for EAFP.""" if node_a == node_b: raise ValueError("Node should not have a relationship with itself.") nodes = self.nodes() if node_a not in nodes or node_b not in nodes: raise KeyError('A node is not present in this graph') def add(rel, a, b): """Local function to perform operation.""" try: if self._relationships[rel][a].get(b): raise ValueError('{} -> {} relationship' 'already exists'.format(a, b)) self._relationships[rel][a][b] = Relationship(rel) except KeyError as key_errors: key = key_errors.args[0] if key == rel: self._relationships[rel] = { a: {b: Relationship(rel)}} elif key == a: self._relationships[rel][a] = { b: Relationship(rel)} try: self._graph[a][b].append(rel) except KeyError: self._graph[a][b] = [rel] add(name, node_a, node_b) if both_ways: add(name, node_b, node_a) def remove_relationship(self, name, node_a, node_b): """Remove a relationship between two nodes.""" del self._relationships[name][node_a][node_b] self._graph[node_a][node_b].remove(name) def remove_node(self, name): """Remove a node and all of its relationships.""" for relationship in self._relationships: for node in self._relationships[relationship]: try: del self._relationships[relationship][node][name] except KeyError: continue try: del self._relationships[relationship][name] except KeyError: continue del self._graph[name] for node in self._graph: try: del self._graph[node][name] except KeyError: continue def get_relationships(self, node_a, node_b): """Return all relationships between two nodes.""" return self._graph[node_a][node_b] def nodes_with_relationship(self, name): """Return all nodes with a given relationship.""" return list(self._relationships[name].keys()) def get_neighbors(self, node): """Return all nodes node has relationships with.""" return list(self._graph[node].keys()) def is_neighbor_to(self, node): """Return node that node is a neighbor to, but not vice versa.""" return [vertex for vertex, rels in self._graph.items() if node in rels] def get_relationship_properties(self, name, node_a, node_b): """Return properties of a relationship between two nodes.""" return self._relationships[name][node_a][node_b].properties def get_node_properties(self, name): """Return properties of a node.""" return self._nodes[name].properties def has_neighbor(self, node_a, node_b): """Return boolean whether a node has a certain neighbor.""" try: return node_b in self._graph[node_a] except KeyError: raise KeyError('{} not in graph'.format(node_a)) def has_relationship(self, node_a, node_b, relationship, both_ways=False): """Return whether node_a has a given rel to node_b or vice_versa.""" if both_ways: return relationship in self._graph[node_a][node_b] \ and relationship in self._graph[node_b][node_a] return relationship in self._graph[node_a][node_b] def change_node_prop(self, node, property_, value): """Change the property of a node.""" self._nodes[node].change_property(property_, value) def change_rel_prop(self, rel, node_a, node_b, prop, val): """Change the property of a relationship.""" self._relationships[rel][node_a][node_b].change_property(prop, val) def remove_node_prop(self, node, property_): """Remove node property.""" self._nodes[node].remove_property(property_) def remove_rel_prop(self, rel, node_a, node_b, prop): """Remove rel property.""" self._relationships[rel][node_a][node_b].remove_property(prop) def add_node_props(self, node, **kwargs): """Add properties to a node with values.""" for key, value in kwargs.items(): self._nodes[node].add_property(key, value) def add_rel_props(self, rel, node_a, node_b, **kwargs): """Add relationship props with values.""" for key, value in kwargs.items(): self._relationships[rel][node_a][node_b].add_property(key, value)
""" Implementation of a labeled property graph. """ class Node: """Node object that will have a relationship to other nodes.""" def __init__(self, name): """Initialized nodes contain properties and methods to view them.""" self.name = name self.properties = {} self.labels = [] def __getitem__(self, key): """Get node properties.""" return self.properties[key] def add_property(self, property_, value): """Method to add a property to a node.""" if property_ in self.properties: raise key_error('Property already exists, use change_property()to alter property value') self.properties[property_] = value def change_property(self, property_, value): """Method to alter a value on a property.""" if property_ not in self.properties: raise attribute_error('Property does not exist, use add_property()to add a property') self.properties[property_] = value def remove_property(self, property_): """Method to remove a property from a node.""" if property_ not in self.properties: raise attribute_error('Node does not contain that property') del self.properties[property_] def add_label(self, label): """Adds a label to the node.""" if label in self.labels: raise value_error('Label already set on node.') self.labels.append(label) def remove_label(self, label): """Removes a label from a node.""" self.labels.remove(label) def __repr__(self): """Show the properties of the node.""" props = 'Name: {}\nProperties:'.format(self.name) for (key, value) in self.properties.items(): props += '\r{}: {}'.format(key, value) return props class Relationship: """Relationship object that will be able to have properties as well.""" def __init__(self, name): """Initialize relationships as to contain properites like nodes.""" self.name = name self.properties = {} self.labels = [] def add_property(self, property_, value): """Method to add a property to a node.""" if property_ in self.properties: raise key_error('Property already exists, use change_property()to alter property value') self.properties[property_] = value def change_property(self, property_, value): """Method to alter a value on a property.""" if property_ not in self.properties: raise attribute_error('Property does not exist, use add_property()to add a property') self.properties[property_] = value def remove_property(self, property_): """Method to remove a property from a node.""" if property_ not in self.properties: raise attribute_error('Node does not contain that property') del self.properties[property_] def add_label(self, label): """Adds a label to the node.""" if label in self.labels: raise value_error('Label already set on node.') self.labels.append(label) def remove_label(self, label): """Removes a label from a node.""" self.labels.remove(label) def __repr__(self): """Show the properties of the node.""" props = 'Name: {}\nProperties:' for (key, value) in self.properties.items(): props += '\r{}: {}'.format(key, value) return props class Labeledpropertygraph: """Define a labeled property graph as dictionary composition.""" def __init__(self): """Initialize the graph as a dictionary.""" self._graph = {} self._nodes = {} self._relationships = {} def __getitem__(self, key): """Return _graphat key.""" return self._nodes[key] def nodes(self): """Return a list of nodes in the graph.""" return [node for node in self._nodes.keys()] def unique_relationships(self): """Return list of unique relationships.""" return [relationship for relationship in self._relationships.keys()] def add_node(self, name): """Add a node and pass the name to the node.name.""" if name in self.nodes(): raise key_error('Node already exists in graph') node = node(name) self._graph[name] = {} self._nodes[name] = node def add_relationship(self, name, node_a, node_b, both_ways=False): """Refactored add_relationship for EAFP.""" if node_a == node_b: raise value_error('Node should not have a relationship with itself.') nodes = self.nodes() if node_a not in nodes or node_b not in nodes: raise key_error('A node is not present in this graph') def add(rel, a, b): """Local function to perform operation.""" try: if self._relationships[rel][a].get(b): raise value_error('{} -> {} relationshipalready exists'.format(a, b)) self._relationships[rel][a][b] = relationship(rel) except KeyError as key_errors: key = key_errors.args[0] if key == rel: self._relationships[rel] = {a: {b: relationship(rel)}} elif key == a: self._relationships[rel][a] = {b: relationship(rel)} try: self._graph[a][b].append(rel) except KeyError: self._graph[a][b] = [rel] add(name, node_a, node_b) if both_ways: add(name, node_b, node_a) def remove_relationship(self, name, node_a, node_b): """Remove a relationship between two nodes.""" del self._relationships[name][node_a][node_b] self._graph[node_a][node_b].remove(name) def remove_node(self, name): """Remove a node and all of its relationships.""" for relationship in self._relationships: for node in self._relationships[relationship]: try: del self._relationships[relationship][node][name] except KeyError: continue try: del self._relationships[relationship][name] except KeyError: continue del self._graph[name] for node in self._graph: try: del self._graph[node][name] except KeyError: continue def get_relationships(self, node_a, node_b): """Return all relationships between two nodes.""" return self._graph[node_a][node_b] def nodes_with_relationship(self, name): """Return all nodes with a given relationship.""" return list(self._relationships[name].keys()) def get_neighbors(self, node): """Return all nodes node has relationships with.""" return list(self._graph[node].keys()) def is_neighbor_to(self, node): """Return node that node is a neighbor to, but not vice versa.""" return [vertex for (vertex, rels) in self._graph.items() if node in rels] def get_relationship_properties(self, name, node_a, node_b): """Return properties of a relationship between two nodes.""" return self._relationships[name][node_a][node_b].properties def get_node_properties(self, name): """Return properties of a node.""" return self._nodes[name].properties def has_neighbor(self, node_a, node_b): """Return boolean whether a node has a certain neighbor.""" try: return node_b in self._graph[node_a] except KeyError: raise key_error('{} not in graph'.format(node_a)) def has_relationship(self, node_a, node_b, relationship, both_ways=False): """Return whether node_a has a given rel to node_b or vice_versa.""" if both_ways: return relationship in self._graph[node_a][node_b] and relationship in self._graph[node_b][node_a] return relationship in self._graph[node_a][node_b] def change_node_prop(self, node, property_, value): """Change the property of a node.""" self._nodes[node].change_property(property_, value) def change_rel_prop(self, rel, node_a, node_b, prop, val): """Change the property of a relationship.""" self._relationships[rel][node_a][node_b].change_property(prop, val) def remove_node_prop(self, node, property_): """Remove node property.""" self._nodes[node].remove_property(property_) def remove_rel_prop(self, rel, node_a, node_b, prop): """Remove rel property.""" self._relationships[rel][node_a][node_b].remove_property(prop) def add_node_props(self, node, **kwargs): """Add properties to a node with values.""" for (key, value) in kwargs.items(): self._nodes[node].add_property(key, value) def add_rel_props(self, rel, node_a, node_b, **kwargs): """Add relationship props with values.""" for (key, value) in kwargs.items(): self._relationships[rel][node_a][node_b].add_property(key, value)
#!/usr/bin/env python3 """ Normal distriution """ class Normal: """ Normal distribution class """ def __init__(self, data=None, mean=0., stddev=1.): if data is None: self.mean = float(mean) if stddev <= 0: raise ValueError("stddev must be a positive value") self.stddev = float(stddev) else: if type(data) != list: raise TypeError("data must be a list") if len(data) < 2: raise ValueError("data must contain multiple values") self.mean = sum(data) / len(data) std = 0 for i in data: std += (i - self.mean) ** 2 std = std / len(data) self.stddev = std ** (1/2) def z_score(self, x): """ z_score of x """ return (x - self.mean) / self.stddev def x_value(self, z): """ calculate the x value of z_score """ return (z * self.stddev) + self.mean def root(self, n): """ return square root of n """ return n ** (1/2) def pdf(self, x): """ probability density function """ pi = 3.1415926536 e = 2.7182818285 s = self.stddev return e ** ((-1/2) * self.z_score(x) ** 2) / (s * self.root(2 * pi)) def cdf(self, x): """ comulative distribution function """ return (1 + self.erf(self.z_score(x) / self.root(2))) / 2 def erf(self, x): """ error """ pi = 3.1415926536 one = x two = (x ** 3) / 3 three = (x ** 5) / 10 four = (x ** 7) / 42 five = (x ** 9) / 216 return 2 * (one - two + three - four + five) / self.root(pi)
""" Normal distriution """ class Normal: """ Normal distribution class """ def __init__(self, data=None, mean=0.0, stddev=1.0): if data is None: self.mean = float(mean) if stddev <= 0: raise value_error('stddev must be a positive value') self.stddev = float(stddev) else: if type(data) != list: raise type_error('data must be a list') if len(data) < 2: raise value_error('data must contain multiple values') self.mean = sum(data) / len(data) std = 0 for i in data: std += (i - self.mean) ** 2 std = std / len(data) self.stddev = std ** (1 / 2) def z_score(self, x): """ z_score of x """ return (x - self.mean) / self.stddev def x_value(self, z): """ calculate the x value of z_score """ return z * self.stddev + self.mean def root(self, n): """ return square root of n """ return n ** (1 / 2) def pdf(self, x): """ probability density function """ pi = 3.1415926536 e = 2.7182818285 s = self.stddev return e ** (-1 / 2 * self.z_score(x) ** 2) / (s * self.root(2 * pi)) def cdf(self, x): """ comulative distribution function """ return (1 + self.erf(self.z_score(x) / self.root(2))) / 2 def erf(self, x): """ error """ pi = 3.1415926536 one = x two = x ** 3 / 3 three = x ** 5 / 10 four = x ** 7 / 42 five = x ** 9 / 216 return 2 * (one - two + three - four + five) / self.root(pi)
# Copyright 2018 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. def ChangeToStr(change): """Turn a pinpoint change dict into a string id.""" change_id = ','.join( '{repository}@{git_hash}'.format(**commit) for commit in change['commits']) if 'patch' in change: change_id += '+' + change['patch']['url'] return change_id def IterTestOutputIsolates(job, only_differences=False): """Iterate over test execution results for all changes tested in the job. Args: job: A pinpoint job dict with state. Yields: (change_id, isolate_hash) pairs for each completed test execution found in the job. """ quests = job['quests'] for change_state in job['state']: if only_differences and not any( v == 'different' for v in change_state['comparisons'].itervalues()): continue change_id = ChangeToStr(change_state['change']) for attempt in change_state['attempts']: executions = dict(zip(quests, attempt['executions'])) if 'Test' not in executions: continue test_run = executions['Test'] if not test_run['completed']: continue try: isolate_hash = next( d['value'] for d in test_run['details'] if d['key'] == 'isolate') except StopIteration: continue yield change_id, isolate_hash
def change_to_str(change): """Turn a pinpoint change dict into a string id.""" change_id = ','.join(('{repository}@{git_hash}'.format(**commit) for commit in change['commits'])) if 'patch' in change: change_id += '+' + change['patch']['url'] return change_id def iter_test_output_isolates(job, only_differences=False): """Iterate over test execution results for all changes tested in the job. Args: job: A pinpoint job dict with state. Yields: (change_id, isolate_hash) pairs for each completed test execution found in the job. """ quests = job['quests'] for change_state in job['state']: if only_differences and (not any((v == 'different' for v in change_state['comparisons'].itervalues()))): continue change_id = change_to_str(change_state['change']) for attempt in change_state['attempts']: executions = dict(zip(quests, attempt['executions'])) if 'Test' not in executions: continue test_run = executions['Test'] if not test_run['completed']: continue try: isolate_hash = next((d['value'] for d in test_run['details'] if d['key'] == 'isolate')) except StopIteration: continue yield (change_id, isolate_hash)
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This is needed due to https://github.com/bazelbuild/bazel/issues/914 load("//tools/build/rules:cc.bzl", "cc_stripped_binary") def _symbol_exports(name, exports): # Creates an assembly file that references all the exported symbols, so the linker won't trim them. native.genrule( name = name + "_syms", srcs = [exports], outs = [name + "_syms.S"], cmd = "cat $< | awk '{print \".global\",$$0}' > $@", ) # Creates a linker script to export the public symbols/hide the rest. native.genrule( name = name + "_ldscript", srcs = [exports], outs = [name + ".ldscript"], cmd = "(" + ";".join([ "echo '{ global:'", "cat $< | awk '{print $$0\";\"}'", "echo 'local: *;};'", "echo", ]) + ") > $@", ) # Creates a OSX linker script to export the public symbols/hide the rest. native.genrule( name = name + "_osx_ldscript", srcs = [exports], outs = [name + "_osx.ldscript"], cmd = "cat $< | awk '{print \"_\"$$0}' > $@", ) def cc_dynamic_library(name, exports = "", visibility = ["//visibility:private"], deps = [], linkopts = [], **kwargs): _symbol_exports(name, exports) # All but one of these will fail, but the select in the filegroup # will pick up the correct one. cc_stripped_binary( name = name + ".so", srcs = [":" + name + "_syms"], deps = deps + [name + ".ldscript"], linkopts = linkopts + ["-Wl,--version-script", "$(location " + name + ".ldscript)"], linkshared = 1, visibility = ["//visibility:private"], **kwargs ) cc_stripped_binary( name = name + ".dylib", deps = deps + [name + "_osx.ldscript"], linkopts = linkopts + [ "-Wl,-exported_symbols_list", "$(location " + name + "_osx.ldscript)", "-Wl,-dead_strip", ], linkshared = 1, visibility = ["//visibility:private"], **kwargs ) cc_stripped_binary( name = name + ".dll", srcs = [":" + name + "_syms"], deps = deps + [name + ".ldscript"], linkopts = linkopts + ["-Wl,--version-script", "$(location " + name + ".ldscript)"], linkshared = 1, visibility = ["//visibility:private"], **kwargs ) native.filegroup( name = name, visibility = visibility, srcs = select({ "//tools/build:linux": [":" + name + ".so"], "//tools/build:darwin": [":" + name + ".dylib"], "//tools/build:windows": [":" + name + ".dll"], # Android "//conditions:default": [":" + name + ".so"], }) ) def android_dynamic_library(name, exports = "", deps = [], linkopts = [], **kwargs): _symbol_exports(name, exports) # This doesn't actually create a dynamic library, but sets up the linking # correctly for when the android_binary actually creates the .so. native.cc_library( name = name, deps = deps + [name + ".ldscript"], linkopts = linkopts + [ "-Wl,--version-script", "$(location " + name + ".ldscript)", "-Wl,--unresolved-symbols=report-all", "-Wl,--gc-sections", "-Wl,--exclude-libs,libgcc.a", "-Wl,-z,noexecstack,-z,relro,-z,now,-z,nocopyreloc", ], **kwargs )
load('//tools/build/rules:cc.bzl', 'cc_stripped_binary') def _symbol_exports(name, exports): native.genrule(name=name + '_syms', srcs=[exports], outs=[name + '_syms.S'], cmd='cat $< | awk \'{print ".global",$$0}\' > $@') native.genrule(name=name + '_ldscript', srcs=[exports], outs=[name + '.ldscript'], cmd='(' + ';'.join(["echo '{ global:'", 'cat $< | awk \'{print $$0";"}\'', "echo 'local: *;};'", 'echo']) + ') > $@') native.genrule(name=name + '_osx_ldscript', srcs=[exports], outs=[name + '_osx.ldscript'], cmd='cat $< | awk \'{print "_"$$0}\' > $@') def cc_dynamic_library(name, exports='', visibility=['//visibility:private'], deps=[], linkopts=[], **kwargs): _symbol_exports(name, exports) cc_stripped_binary(name=name + '.so', srcs=[':' + name + '_syms'], deps=deps + [name + '.ldscript'], linkopts=linkopts + ['-Wl,--version-script', '$(location ' + name + '.ldscript)'], linkshared=1, visibility=['//visibility:private'], **kwargs) cc_stripped_binary(name=name + '.dylib', deps=deps + [name + '_osx.ldscript'], linkopts=linkopts + ['-Wl,-exported_symbols_list', '$(location ' + name + '_osx.ldscript)', '-Wl,-dead_strip'], linkshared=1, visibility=['//visibility:private'], **kwargs) cc_stripped_binary(name=name + '.dll', srcs=[':' + name + '_syms'], deps=deps + [name + '.ldscript'], linkopts=linkopts + ['-Wl,--version-script', '$(location ' + name + '.ldscript)'], linkshared=1, visibility=['//visibility:private'], **kwargs) native.filegroup(name=name, visibility=visibility, srcs=select({'//tools/build:linux': [':' + name + '.so'], '//tools/build:darwin': [':' + name + '.dylib'], '//tools/build:windows': [':' + name + '.dll'], '//conditions:default': [':' + name + '.so']})) def android_dynamic_library(name, exports='', deps=[], linkopts=[], **kwargs): _symbol_exports(name, exports) native.cc_library(name=name, deps=deps + [name + '.ldscript'], linkopts=linkopts + ['-Wl,--version-script', '$(location ' + name + '.ldscript)', '-Wl,--unresolved-symbols=report-all', '-Wl,--gc-sections', '-Wl,--exclude-libs,libgcc.a', '-Wl,-z,noexecstack,-z,relro,-z,now,-z,nocopyreloc'], **kwargs)
class TwythonError(Exception): @property def msg(self) -> str: ... class TwythonRateLimitError(TwythonError): @property def retry_after(self) -> int: ... class TwythonAuthError(TwythonError): ...
class Twythonerror(Exception): @property def msg(self) -> str: ... class Twythonratelimiterror(TwythonError): @property def retry_after(self) -> int: ... class Twythonautherror(TwythonError): ...
try: sc = input("Enter your score between 0.0 and 1.0: ") #sc = 0.85 score = float(sc) except: if score > 1.0 or score < 0.0: print("Error, input should be between 0.0 and 1.0") quit() if score >= 0.9: print('A') elif score >= 0.8: print('B') elif score >= 0.7: print('C') elif score < 0.6: print('F') #Write a program to prompt for a score between 0.0 and 1.0. # If the score is out of range, print an error. # If the score is between 0.0 and 1.0, print a grade using the following table: #Score Grade #>= 0.9 A #>= 0.8 B #>= 0.7 C #>= 0.6 D #< 0.6 F #If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
try: sc = input('Enter your score between 0.0 and 1.0: ') score = float(sc) except: if score > 1.0 or score < 0.0: print('Error, input should be between 0.0 and 1.0') quit() if score >= 0.9: print('A') elif score >= 0.8: print('B') elif score >= 0.7: print('C') elif score < 0.6: print('F')
passw = input() def Is_Valid(password): valid_length = False two_digits = False only = True digit = 0 let_dig = 0 if len(password) >= 6 and len(password) <= 10: valid_length = True else: print('Password must be between 6 and 10 characters') for i in password: if ((ord(i) >= 48 and ord(i) <= 57) or (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i) <= 122)): let_dig +=1 if let_dig != len(password): only = False if not only: print('Password must consist only of letters and digits') for i in password: if ord(i) >= 48 and ord(i) <= 57: digit += 1 if digit >= 2: two_digits = True else: print('Password must have at least 2 digits') if valid_length and two_digits and only: print('Password is valid.') Is_Valid(passw)
passw = input() def is__valid(password): valid_length = False two_digits = False only = True digit = 0 let_dig = 0 if len(password) >= 6 and len(password) <= 10: valid_length = True else: print('Password must be between 6 and 10 characters') for i in password: if ord(i) >= 48 and ord(i) <= 57 or (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i) <= 122): let_dig += 1 if let_dig != len(password): only = False if not only: print('Password must consist only of letters and digits') for i in password: if ord(i) >= 48 and ord(i) <= 57: digit += 1 if digit >= 2: two_digits = True else: print('Password must have at least 2 digits') if valid_length and two_digits and only: print('Password is valid.') is__valid(passw)
# Algebraic-only implementation of two's complement in pure Python # # Written by: Patrizia Favaron def raw_to_compl2(iRaw, iNumBits): # Establish minimum and maximum possible raw values iMinRaw = 0 iMaxRaw = 2**iNumBits - 1 # Clip value arithmetically if iRaw < iMinRaw: iRaw = iMinRaw if iRaw > iMaxRaw: iRaw = iMaxRaw # Set useful two's complement value(s) iMaxValue = 2**(iNumBits-1) - 1 # Check cases and act accordingly if iRaw <= iMaxValue: iValue = iRaw else: iValue = iRaw - 2**iNumBits return iValue def compl2_to_raw(iCompl2, iNumBits): # Set minimum and maximum two's complement values iMinValue = -2**(iNumBits-1) iMaxValue = 2**(iNumBits-1) - 1 # Clip value arithmetically if iCompl2 < iMinValue: iCompl2 = iMinValue if iCompl2 > iMaxValue: iCompl2 = iMaxValue # Check cases and set accordingly if iCompl2 >= 0: iRaw = iCompl2 else: iRaw = iCompl2 + 2**iNumBits return iRaw if __name__ == "__main__": iRaw = 0 print(iRaw) print(raw_to_compl2(iRaw,16)) print() iRaw = 32767 print(iRaw) print(raw_to_compl2(iRaw,16)) print() iRaw = 32768 print(iRaw) print(raw_to_compl2(iRaw,16)) print() iRaw = 65535 print(iRaw) print(raw_to_compl2(iRaw,16)) print() iCompl2 = -1 print(iCompl2) print(compl2_to_raw(iCompl2,10)) print() iCompl2 = -2**9 print(iCompl2) print(compl2_to_raw(iCompl2,10)) print() iCompl2 = -2**9 + 1 print(iCompl2) print(compl2_to_raw(iCompl2,10)) print()
def raw_to_compl2(iRaw, iNumBits): i_min_raw = 0 i_max_raw = 2 ** iNumBits - 1 if iRaw < iMinRaw: i_raw = iMinRaw if iRaw > iMaxRaw: i_raw = iMaxRaw i_max_value = 2 ** (iNumBits - 1) - 1 if iRaw <= iMaxValue: i_value = iRaw else: i_value = iRaw - 2 ** iNumBits return iValue def compl2_to_raw(iCompl2, iNumBits): i_min_value = -2 ** (iNumBits - 1) i_max_value = 2 ** (iNumBits - 1) - 1 if iCompl2 < iMinValue: i_compl2 = iMinValue if iCompl2 > iMaxValue: i_compl2 = iMaxValue if iCompl2 >= 0: i_raw = iCompl2 else: i_raw = iCompl2 + 2 ** iNumBits return iRaw if __name__ == '__main__': i_raw = 0 print(iRaw) print(raw_to_compl2(iRaw, 16)) print() i_raw = 32767 print(iRaw) print(raw_to_compl2(iRaw, 16)) print() i_raw = 32768 print(iRaw) print(raw_to_compl2(iRaw, 16)) print() i_raw = 65535 print(iRaw) print(raw_to_compl2(iRaw, 16)) print() i_compl2 = -1 print(iCompl2) print(compl2_to_raw(iCompl2, 10)) print() i_compl2 = -2 ** 9 print(iCompl2) print(compl2_to_raw(iCompl2, 10)) print() i_compl2 = -2 ** 9 + 1 print(iCompl2) print(compl2_to_raw(iCompl2, 10)) print()
"""The base command.""" class Base(object): """A base command.""" def __init__(self, options, *args, **kwargs): self.args = args self.kwargs = kwargs self.configuration = self.get_configuration( options=options ) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!' ) def get_configuration(self, options=None): raise NotImplementedError( 'You must implement the get_configuration() method yourself!' )
"""The base command.""" class Base(object): """A base command.""" def __init__(self, options, *args, **kwargs): self.args = args self.kwargs = kwargs self.configuration = self.get_configuration(options=options) def run(self): raise not_implemented_error('You must implement the run() method yourself!') def get_configuration(self, options=None): raise not_implemented_error('You must implement the get_configuration() method yourself!')
with open('./input.txt') as input: hits = {} for line in input: (x1, y1), (x2, y2) = [ map(int, point.split(',')) for point in line.strip().split(' -> ')] if x1 == x2: for y in range(min(y1, y2), max(y1, y2) + 1): if (x1, y) in hits: hits[(x1, y)] += 1 else: hits[(x1, y)] = 1 if y1 == y2: for x in range(min(x1, x2), max(x1, x2) + 1): if (x, y1) in hits: hits[(x, y1)] += 1 else: hits[(x, y1)] = 1 print(len([val for val in hits.values() if val > 1])) # 5147
with open('./input.txt') as input: hits = {} for line in input: ((x1, y1), (x2, y2)) = [map(int, point.split(',')) for point in line.strip().split(' -> ')] if x1 == x2: for y in range(min(y1, y2), max(y1, y2) + 1): if (x1, y) in hits: hits[x1, y] += 1 else: hits[x1, y] = 1 if y1 == y2: for x in range(min(x1, x2), max(x1, x2) + 1): if (x, y1) in hits: hits[x, y1] += 1 else: hits[x, y1] = 1 print(len([val for val in hits.values() if val > 1]))
def get_cat_vars_dict(df, categorical_cols, feature_names, target_name): cat_vars_dict = {} for col in [ col for col in categorical_cols if col != target_name]: cat_vars_dict[feature_names.index(col)] = len(df[col].unique()) return cat_vars_dict
def get_cat_vars_dict(df, categorical_cols, feature_names, target_name): cat_vars_dict = {} for col in [col for col in categorical_cols if col != target_name]: cat_vars_dict[feature_names.index(col)] = len(df[col].unique()) return cat_vars_dict
class RestApi(object): def __init__(self, app): self.app = app self.frefix_url = self.app.config.get("API_URL_PREFIX") or "" self.views = [] def register_api(self, bleuprint, view, endpoint, url): view_func = view.as_view(endpoint) links = {} # detail_url = "{}<{}:{}>".format(url, pk_type, pk) links['self'] = url view.links = links # if 'GET' in view.allowed_methods: # bleuprint.add_url_rule(url, defaults={pk: None}, # view_func=view_func, methods=['GET',]) # if 'POST' in view.allowed_methods: # bleuprint.add_url_rule(url, view_func=view_func, methods=['POST',]) methods = [method for method in view.allowed_methods if method != 'POST'] bleuprint.add_url_rule(url, view_func=view_func, methods=view.allowed_methods) self.views.append({"view_func": view_func, "endpoint": endpoint}) def register_blueprint(self, blueprint): self.app.register_blueprint(blueprint, url_prefix=self.frefix_url)
class Restapi(object): def __init__(self, app): self.app = app self.frefix_url = self.app.config.get('API_URL_PREFIX') or '' self.views = [] def register_api(self, bleuprint, view, endpoint, url): view_func = view.as_view(endpoint) links = {} links['self'] = url view.links = links methods = [method for method in view.allowed_methods if method != 'POST'] bleuprint.add_url_rule(url, view_func=view_func, methods=view.allowed_methods) self.views.append({'view_func': view_func, 'endpoint': endpoint}) def register_blueprint(self, blueprint): self.app.register_blueprint(blueprint, url_prefix=self.frefix_url)
class Kanji(): def __init__(self): self.kanji = None self.strokes = 0 self.pronunciation = None self.definition = "" self.kanji_shinjitai = None self.strokes_shinjitai = 0 def __unicode__(self): if self.kanji_shinjitai: ks = " (%s)" % self.kanji_shinjitai if self.strokes_shinjitai: ss = " (%s)" % self.strokes_shinjitai return u"<kanji: %s%s, strokes: %s%s, pronunciation: %s, definition: %s>" % (self.kanji, ks, self.strokes, ss, self.pronunciation, self.definition)
class Kanji: def __init__(self): self.kanji = None self.strokes = 0 self.pronunciation = None self.definition = '' self.kanji_shinjitai = None self.strokes_shinjitai = 0 def __unicode__(self): if self.kanji_shinjitai: ks = ' (%s)' % self.kanji_shinjitai if self.strokes_shinjitai: ss = ' (%s)' % self.strokes_shinjitai return u'<kanji: %s%s, strokes: %s%s, pronunciation: %s, definition: %s>' % (self.kanji, ks, self.strokes, ss, self.pronunciation, self.definition)
def p_error( p ): print print( "SYNTAX ERROR %s" % str( p ) ) print raise Exception
def p_error(p): print print('SYNTAX ERROR %s' % str(p)) print raise Exception
numeros = [] par = [] impar = [] while True: n = (int(input('Digite um numero: '))) numeros.append(n) if n % 2 == 0: par.append(n) else: impar.append(n) resp = str(input('Deseja continuar [S/N]: ')).strip().upper()[0] while resp not in 'SN': resp = str(input('Tente novamente, Deseja continuar [S/N]: ')).strip().upper()[0] if resp == 'N': break if resp == 'N': break print('=-' * 30) print('Os nomeros digtados foram: ', numeros) par.sort() print(f'Numeros pares {par}') impar.sort() print(f'Nomeros impares {impar}')
numeros = [] par = [] impar = [] while True: n = int(input('Digite um numero: ')) numeros.append(n) if n % 2 == 0: par.append(n) else: impar.append(n) resp = str(input('Deseja continuar [S/N]: ')).strip().upper()[0] while resp not in 'SN': resp = str(input('Tente novamente, Deseja continuar [S/N]: ')).strip().upper()[0] if resp == 'N': break if resp == 'N': break print('=-' * 30) print('Os nomeros digtados foram: ', numeros) par.sort() print(f'Numeros pares {par}') impar.sort() print(f'Nomeros impares {impar}')
def get_label_dict(dataset_name): label_dict = None if dataset_name == 'PASCAL': label_dict = { 'back_ground': 0, 'aeroplane': 1, 'bicycle': 2, 'bird': 3, 'boat': 4, 'bottle': 5, 'bus': 6, 'car': 7, 'cat': 8, 'chair': 9, 'cow': 10, 'diningtable': 11, 'dog': 12, 'horse': 13, 'motorbike': 14, 'person': 15, 'pottedplant': 16, 'sheep': 17, 'sofa': 18, 'train': 19, 'tvmonitor': 20 } elif dataset_name == 'COCO': pass elif dataset_name == 'ROOF': label_dict = { 'back_ground': 0, 'flatroof': 1, 'solarpanel_slope': 2, 'solarpanel_flat': 3, 'parkinglot': 4, 'facility': 5, 'rooftop': 6, 'heliport_r': 7, 'heliport_h': 8 } return label_dict
def get_label_dict(dataset_name): label_dict = None if dataset_name == 'PASCAL': label_dict = {'back_ground': 0, 'aeroplane': 1, 'bicycle': 2, 'bird': 3, 'boat': 4, 'bottle': 5, 'bus': 6, 'car': 7, 'cat': 8, 'chair': 9, 'cow': 10, 'diningtable': 11, 'dog': 12, 'horse': 13, 'motorbike': 14, 'person': 15, 'pottedplant': 16, 'sheep': 17, 'sofa': 18, 'train': 19, 'tvmonitor': 20} elif dataset_name == 'COCO': pass elif dataset_name == 'ROOF': label_dict = {'back_ground': 0, 'flatroof': 1, 'solarpanel_slope': 2, 'solarpanel_flat': 3, 'parkinglot': 4, 'facility': 5, 'rooftop': 6, 'heliport_r': 7, 'heliport_h': 8} return label_dict
class BatchRunner: def __init__(self,model,iter_n): self.model = model self.iter_n = iter_n def run_model(self,start,end): """ Runs the model """ for i in range(start,end): self.model.reset(i) self.model.episode() print("The iteration {} is completed.".format(i))
class Batchrunner: def __init__(self, model, iter_n): self.model = model self.iter_n = iter_n def run_model(self, start, end): """ Runs the model """ for i in range(start, end): self.model.reset(i) self.model.episode() print('The iteration {} is completed.'.format(i))
start = 0 end = 1781 instance = 0 for i in range(150): f = open(f"ec2files/ec2file{i}.py", "w") f.write(f"from scraper import * \ns = Scraper(start={start}, end={end}, max_iter=30, scraper_instance={instance}) \ns.scrape_letterboxd()") start = end + 1 end = start + 1781 instance += 1 f.close()
start = 0 end = 1781 instance = 0 for i in range(150): f = open(f'ec2files/ec2file{i}.py', 'w') f.write(f'from scraper import * \ns = Scraper(start={start}, end={end}, max_iter=30, scraper_instance={instance}) \ns.scrape_letterboxd()') start = end + 1 end = start + 1781 instance += 1 f.close()
# # Copyright (C) 2020 Arm Mbed. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # """Utility scripts to abstract and assist with scripts run in the CI."""
"""Utility scripts to abstract and assist with scripts run in the CI."""
class Vector2D: def __init__(self, v): """ :type v: List[List[int]] """ self.iter = itertools.chain.from_iterable(v) self.cnt = sum(len(lst) for lst in v) def next(self): """ :rtype: int """ self.cnt -= 1 return next(self.iter) def hasNext(self): """ :rtype: bool """ return self.cnt > 0 # Your Vector2D object will be instantiated and called as such: # obj = Vector2D(v) # param_1 = obj.next() # param_2 = obj.hasNext()
class Vector2D: def __init__(self, v): """ :type v: List[List[int]] """ self.iter = itertools.chain.from_iterable(v) self.cnt = sum((len(lst) for lst in v)) def next(self): """ :rtype: int """ self.cnt -= 1 return next(self.iter) def has_next(self): """ :rtype: bool """ return self.cnt > 0
class Config(object): SECRET_KEY = "aaaaaaa" debug = False class Production(Config): debug = True CSRF_ENABLED = False SQLALCHEMY_DATABASE_URI = "mysql://username:password@127.0.0.1/DBname" migration_directory = "migrations"
class Config(object): secret_key = 'aaaaaaa' debug = False class Production(Config): debug = True csrf_enabled = False sqlalchemy_database_uri = 'mysql://username:password@127.0.0.1/DBname' migration_directory = 'migrations'
# This program creates an object of the pet class # and asks the user to enter the name, type, and age of pet. # The program retrieves the pet's name, type, and age and # displays the data. class Pet: def __init__(self, name, animal_type, age): # Gets the pets name self.__name = name # Gets the animal type self.__animal_type = animal_type # Gets the animals age self.__age = age def set_name(self, name): self.__name = name def set_type(self, animal_type): self.__animal_type = animal_type def set_age(self, age): self.__age = age # Displays the pets name def get_name(self): return self.__name # Displays the animal type def get_animal_type(self): return self.__animal_type # Displays the pets age def get_age(self): return self.__age # The main function def main(): # Get the pets name name = input('What is the name of the pet? ') # Get the animal type animal_type = input('What type of animal is it? ') # Get the animals age age = int(input('How old is the pet? ')) pets = Pet(name, animal_type, age) # Display the inputs print('This information will be added to our records.') print('Here is the data you entered: ') print('------------------------------') print('Pet Name:', pets.get_name()) print('Animal Type:', pets.get_animal_type()) print('Age:', pets.get_age()) # Call the main function main()
class Pet: def __init__(self, name, animal_type, age): self.__name = name self.__animal_type = animal_type self.__age = age def set_name(self, name): self.__name = name def set_type(self, animal_type): self.__animal_type = animal_type def set_age(self, age): self.__age = age def get_name(self): return self.__name def get_animal_type(self): return self.__animal_type def get_age(self): return self.__age def main(): name = input('What is the name of the pet? ') animal_type = input('What type of animal is it? ') age = int(input('How old is the pet? ')) pets = pet(name, animal_type, age) print('This information will be added to our records.') print('Here is the data you entered: ') print('------------------------------') print('Pet Name:', pets.get_name()) print('Animal Type:', pets.get_animal_type()) print('Age:', pets.get_age()) main()
# # PySNMP MIB module SCSPATMARP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCSPATMARP-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:01:23 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint") AtmConnKind, AtmAddr = mibBuilder.importSymbols("ATM-TC-MIB", "AtmConnKind", "AtmAddr") scspLSID, ScspHFSMStateType, scspServerGroupPID, SCSPVCIInteger, SCSPVPIInteger, scspServerGroupID, scspDCSID = mibBuilder.importSymbols("SCSP-MIB", "scspLSID", "ScspHFSMStateType", "scspServerGroupPID", "SCSPVCIInteger", "SCSPVPIInteger", "scspServerGroupID", "scspDCSID") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ModuleIdentity, TimeTicks, Counter32, Counter64, NotificationType, Unsigned32, experimental, iso, Bits, MibIdentifier, Integer32, Gauge32, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "TimeTicks", "Counter32", "Counter64", "NotificationType", "Unsigned32", "experimental", "iso", "Bits", "MibIdentifier", "Integer32", "Gauge32", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity") DisplayString, RowStatus, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention") scspAtmarpMIB = ModuleIdentity((1, 3, 6, 1, 3, 2002)) if mibBuilder.loadTexts: scspAtmarpMIB.setLastUpdated('9808020000Z') if mibBuilder.loadTexts: scspAtmarpMIB.setOrganization('IETF Internetworking Over NBMA Working Group (ion)') if mibBuilder.loadTexts: scspAtmarpMIB.setContactInfo('Jim Luciani (jliciani@BayNetworks.com Bay Networks Cliff X. Wang (cliff_wang@vnet.ibm.com) Colin Verrilli (verrilli@vnet.ibm.com) IBM Corp.') if mibBuilder.loadTexts: scspAtmarpMIB.setDescription('This module defines a portion of the management information base (MIB) for managing Server Cache Synchronizatio protocol applied to ATMARP servers.') scspAtmarpObjects = MibIdentifier((1, 3, 6, 1, 3, 2002, 1)) scspAtmarpNotifications = MibIdentifier((1, 3, 6, 1, 3, 2002, 2)) scspAtmarpConformance = MibIdentifier((1, 3, 6, 1, 3, 2002, 3)) scspAtmarpServerGroupTable = MibTable((1, 3, 6, 1, 3, 2002, 1, 1), ) if mibBuilder.loadTexts: scspAtmarpServerGroupTable.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupTable.setDescription('The objects defined in this table are used to for the management of SCSP server groups with application to IP over ATM operation (Classic IP). These objects SHOULD be used along with the protocol independent part objects to support the management of the SCSP protocol applied to synchronizing the atmarp servers in a LIS. There is one entry in this table for each server group. In the case of IP over ATM, each server group corresponds to a Logical IP Subnet.') scspAtmarpServerGroupEntry = MibTableRow((1, 3, 6, 1, 3, 2002, 1, 1, 1), ).setIndexNames((0, "SCSP-MIB", "scspServerGroupID"), (0, "SCSP-MIB", "scspServerGroupPID")) if mibBuilder.loadTexts: scspAtmarpServerGroupEntry.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupEntry.setDescription('Information about SCSP server group running IP over ATM operation. This table is indexed by scspServerGroupID and scspServerGroupPID. The two indeces point to a corresponding entry in the scspServerGroupTable.') scspAtmarpServerGroupNetMask = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 1, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpServerGroupNetMask.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupNetMask.setDescription('The subnet mask associated with this Server Group.') scspAtmarpServerGroupSubnetAddr = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 1, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpServerGroupSubnetAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupSubnetAddr.setDescription('The IP subnet address associated with this Server Group.') scspAtmarpServerGroupRowStatus = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 1, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: scspAtmarpServerGroupRowStatus.setReference("RFC 1903, 'Textual Conventions for version 2 of the Simple Network Management Protocol (SNMPv2).'") if mibBuilder.loadTexts: scspAtmarpServerGroupRowStatus.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupRowStatus.setDescription('This object allows Atmarp Server Group Table entries to be created and deleted from the scspAtmarpServerGroupTable. Note that scspAtmarpServerGroupTable entry creation and deletion is coupled with scspServerGroupTable entry creation and deletion. A scspAtmarpServerGroupTable entry cannot be created until its corresponding scspServerGroupTable entry is created. When a scspServerGroupTable entry is deleted, it also removes the corresponding scspAtmarpServerGroupTable entry.') scspAtmarpLSTable = MibTable((1, 3, 6, 1, 3, 2002, 1, 2), ) if mibBuilder.loadTexts: scspAtmarpLSTable.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSTable.setDescription('The objects defined in this table are used to for the management of the Atmarp Local server in a SCSP server group for IP over ATM operation. These objects SHOULD be used along with the protocol independent part objects to support the management of the SCSP protocol applied to synchronizing the IP over ATM servers.') scspAtmarpLSEntry = MibTableRow((1, 3, 6, 1, 3, 2002, 1, 2, 1), ).setIndexNames((0, "SCSP-MIB", "scspServerGroupID"), (0, "SCSP-MIB", "scspServerGroupPID"), (0, "SCSP-MIB", "scspLSID")) if mibBuilder.loadTexts: scspAtmarpLSEntry.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSEntry.setDescription('Information about Atmarp Local Server in a SCSP server group. This table is indexed by scspServerGroupID, scspServerGroupPID, and scspLSID. The three indeces point to a corresponding entry in the scspLSTable.') scspAtmarpLSLSIPAddr = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 2, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpLSLSIPAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSLSIPAddr.setDescription('The IP address of the Atmarp Local Server. Since an Atmarp server does not have to be assigned an IP address, this object is optional.') scspAtmarpLSLSAtmAddr = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 2, 1, 2), AtmAddr()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpLSLSAtmAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSLSAtmAddr.setDescription('The ATM address of the Atmarp Local Server.') scspAtmarpLSRowStatus = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: scspAtmarpLSRowStatus.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSRowStatus.setDescription('This object allows Atmarp Local Server Table entries to be created and deleted from the scspAtmarpLSTable. Note that scspAtmarpLSTable entry creation and deletion is coupled with scspLSTable entry creation and deletion. A scspAtmarpLSTable entry cannot be created until its corresponding scspLSTable entry is created. When a scspLSTable entry is deleted, it also removes the corresponding scspAtmarpLSTable entry.') scspAtmarpPeerTable = MibTable((1, 3, 6, 1, 3, 2002, 1, 3), ) if mibBuilder.loadTexts: scspAtmarpPeerTable.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerTable.setDescription('The objects defined in this table are used to for the management of the ATMARP sever peers.') scspAtmarpPeerEntry = MibTableRow((1, 3, 6, 1, 3, 2002, 1, 3, 1), ).setIndexNames((0, "SCSP-MIB", "scspServerGroupID"), (0, "SCSP-MIB", "scspServerGroupPID"), (0, "SCSPATMARP-MIB", "scspAtmarpPeerIndex")) if mibBuilder.loadTexts: scspAtmarpPeerEntry.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerEntry.setDescription('Information about each peer ATMARP server participated in the scsp Server group. The table is indexed by scspServerGroupID, scspServerGroupPID, and scspAtmarpPeerIndex.') scspAtmarpPeerIndex = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpPeerIndex.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerIndex.setDescription('The table index of the peer Atmarp server table.') scspAtmarpPeerIPAddr = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 3, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpPeerIPAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerIPAddr.setDescription('The IP address of the peer Atmarp server. Since an Atmarp server does not have to be assigned an IP address, this object is optional.') scspAtmarpPeerAtmAddr = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 3, 1, 3), AtmAddr()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpPeerAtmAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerAtmAddr.setDescription("The ATM address of the Peer. If SVC is used between LS and Peer, Peer's ATM address should be valid. However, if PVC is used instead SVC, the Peer's ATM address may be a Null OCTET STRING.") scspAtmarpPeerVCType = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 3, 1, 4), AtmConnKind()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpPeerVCType.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerVCType.setDescription('The type of the virtual circuit between LS and Peer.') scspAtmarpPeerVPI = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 3, 1, 5), SCSPVPIInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpPeerVPI.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerVPI.setDescription('The VPI value for the virtual circuit between LS and Peer.') scspAtmarpPeerVCI = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 3, 1, 6), SCSPVCIInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpPeerVCI.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerVCI.setDescription('The VCI value for the virtual circuit between LS and Peer.') scspAtmarpPeerDCSID = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 3, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 63))).setMaxAccess("readonly") if mibBuilder.loadTexts: scspAtmarpPeerDCSID.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerDCSID.setDescription('The DCS ID for this peer. When the peer tabel is created, DCS ID may not have been discovered. Tt is set to a Null string. It will be update when the DCS ID associated with this peer (ATM address) is discovered.') scspAtmarpPeerRowStatus = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 3, 1, 8), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: scspAtmarpPeerRowStatus.setReference("RFC 1903, 'Textual Conventions for version 2 of the Simple Network Management Protocol (SNMPv2).'") if mibBuilder.loadTexts: scspAtmarpPeerRowStatus.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerRowStatus.setDescription('This object allows Atmarp Peer table entries to be created and deleted from the scspAtmarpPeerTable. Note that scspAtmarpPeerTable entry is created when a peer is configured loaclly or when a peer not previously configured connects to LS.') scspAtmarpHFSMTable = MibTable((1, 3, 6, 1, 3, 2002, 1, 4), ) if mibBuilder.loadTexts: scspAtmarpHFSMTable.setStatus('current') if mibBuilder.loadTexts: scspAtmarpHFSMTable.setDescription('The objects defined in this table are used to for the management of the HFSM between the LS and the DCS.') scspAtmarpHFSMEntry = MibTableRow((1, 3, 6, 1, 3, 2002, 1, 4, 1), ).setIndexNames((0, "SCSP-MIB", "scspServerGroupID"), (0, "SCSP-MIB", "scspServerGroupPID"), (0, "SCSPATMARP-MIB", "scspAtmarpPeerIndex")) if mibBuilder.loadTexts: scspAtmarpHFSMEntry.setStatus('current') if mibBuilder.loadTexts: scspAtmarpHFSMEntry.setDescription('Information about SCSP HFSM session between the LS and its HFSMs. The table is indexed by scspServerGroupID, scspServerGroupPID, and scspAtmarpPeerIndex.') scspHFSMHFSMState = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 4, 1, 1), ScspHFSMStateType()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspHFSMHFSMState.setReference('SCSP draft, Section 2.1') if mibBuilder.loadTexts: scspHFSMHFSMState.setStatus('current') if mibBuilder.loadTexts: scspHFSMHFSMState.setDescription('The current state of the Hello Finite State Machine. The allowable states are: down(1), waiting(2), uniConn(3), biConn(4).') scspHFSMHelloIn = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 4, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspHFSMHelloIn.setStatus('current') if mibBuilder.loadTexts: scspHFSMHelloIn.setDescription("The number of 'Hello' messages received from this HFSM.") scspHFSMHelloOut = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 4, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspHFSMHelloOut.setStatus('current') if mibBuilder.loadTexts: scspHFSMHelloOut.setDescription("The number of 'Hello' messages sent from LS to this HFSM.") scspHFSMHelloInvalidIn = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 4, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: scspHFSMHelloInvalidIn.setStatus('current') if mibBuilder.loadTexts: scspHFSMHelloInvalidIn.setDescription("The number of invalid 'Hello' messages received from this HFSM. Possible message errors include: Hello message when the HFSM is in 'Down' state; Hello message is too short to contain the number of Receiver ID records specified in the header, etc. Other common errors include failed authentication if applicable, errors in the message fields, etc.") scspHFSMHelloInterval = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: scspHFSMHelloInterval.setStatus('current') if mibBuilder.loadTexts: scspHFSMHelloInterval.setDescription('This object contains the value for HelloInterval with the associated HFSM. It is the time (in seconds) between sending of consecutive Hello messages from the HFSM.') scspHFSMDeadFactor = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 4, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: scspHFSMDeadFactor.setStatus('current') if mibBuilder.loadTexts: scspHFSMDeadFactor.setDescription("This object contains the value for DeadFactor with this associated server. The DeadFactor along with HelloInterval are contained in 'Hello' messages sent from this HFSM. If 'Hello' messages are not received from this HFSM within the time out interval 'HelloInterval*DeadFactor' (in seconds), then the HFSM MUST be considered to be stalled.") scspHFSMFamilyID = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 4, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: scspHFSMFamilyID.setReference('SCSP draft, Sec.2 and Sec. B.2.5') if mibBuilder.loadTexts: scspHFSMFamilyID.setStatus('current') if mibBuilder.loadTexts: scspHFSMFamilyID.setDescription('The family ID is used to refer an aggregate of Protocol ID/SGID pairs. Only a single HFSM is run for all Protocol ID/SGID pairs assigned to a Family ID. When the HFSM is not shared by an aggregate of Protocol ID/SGID pairs, this object should be set to 0.') scspAtmarpHFSMRowStatus = MibTableColumn((1, 3, 6, 1, 3, 2002, 1, 4, 1, 8), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: scspAtmarpHFSMRowStatus.setReference("RFC 1903, 'Textual Conventions for version 2 of the Simple Network Management Protocol (SNMPv2).'") if mibBuilder.loadTexts: scspAtmarpHFSMRowStatus.setStatus('current') if mibBuilder.loadTexts: scspAtmarpHFSMRowStatus.setDescription('This object allows Atmarp HFSM table entries to be created and deleted from the scspAtmarpHFSMTable. Note that scspAtmarpHFSMTable entry creation and deletion is closely coupled with scspHFSMTable entry creation. A scspAtmarpHFSMTable entry cannot be created until its corresponding scspHFSMTable entry is created. When a scspHFSMTable entry is deleted, it also removes the corresponding scspAtmarpHFSMTable entry.') scspHFSMDown = NotificationType((1, 3, 6, 1, 3, 2002, 2, 1)).setObjects(("SCSP-MIB", "scspServerGroupID"), ("SCSP-MIB", "scspServerGroupPID"), ("SCSPATMARP-MIB", "scspAtmarpPeerIndex")) if mibBuilder.loadTexts: scspHFSMDown.setStatus('current') if mibBuilder.loadTexts: scspHFSMDown.setDescription("The Hello Finite State Machine associated with this LS/DCS pair enters 'Down' state.") scspHFSMWaiting = NotificationType((1, 3, 6, 1, 3, 2002, 2, 2)).setObjects(("SCSP-MIB", "scspServerGroupID"), ("SCSP-MIB", "scspServerGroupPID"), ("SCSPATMARP-MIB", "scspAtmarpPeerIndex")) if mibBuilder.loadTexts: scspHFSMWaiting.setStatus('current') if mibBuilder.loadTexts: scspHFSMWaiting.setDescription("The Hello Finite State Machine associated with this LS/DCS pair enters 'Waiting' state.") scspHFSMBiConn = NotificationType((1, 3, 6, 1, 3, 2002, 2, 3)).setObjects(("SCSP-MIB", "scspServerGroupID"), ("SCSP-MIB", "scspServerGroupPID"), ("SCSPATMARP-MIB", "scspAtmarpPeerIndex")) if mibBuilder.loadTexts: scspHFSMBiConn.setStatus('current') if mibBuilder.loadTexts: scspHFSMBiConn.setDescription("The Hello Finite State Machine associated with this LS/DCS pair enters 'Bidirectional connection' state.") scspAtmarpCompliances = MibIdentifier((1, 3, 6, 1, 3, 2002, 3, 1)) scspAtmarpGroups = MibIdentifier((1, 3, 6, 1, 3, 2002, 3, 2)) scspAtmarpCompliance = ModuleCompliance((1, 3, 6, 1, 3, 2002, 3, 1, 1)).setObjects(("SCSPATMARP-MIB", "scspAtmarpGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): scspAtmarpCompliance = scspAtmarpCompliance.setStatus('current') if mibBuilder.loadTexts: scspAtmarpCompliance.setDescription('The compliance statement for entities that are required for the management of SCSP when applied to ATMARP servers.') scspAtmarpGroup = ObjectGroup((1, 3, 6, 1, 3, 2002, 3, 2, 1)).setObjects(("SCSPATMARP-MIB", "scspAtmarpServerGroupNetMask"), ("SCSPATMARP-MIB", "scspAtmarpServerGroupSubnetAddr"), ("SCSPATMARP-MIB", "scspAtmarpLSLSIPAddr"), ("SCSPATMARP-MIB", "scspAtmarpLSLSAtmAddr"), ("SCSPATMARP-MIB", "scspAtmarpPeerIndex"), ("SCSPATMARP-MIB", "scspAtmarpPeerAtmAddr"), ("SCSPATMARP-MIB", "scspAtmarpPeerVCType"), ("SCSPATMARP-MIB", "scspAtmarpPeerVPI"), ("SCSPATMARP-MIB", "scspAtmarpPeerVCI"), ("SCSPATMARP-MIB", "scspAtmarpPeerDCSID"), ("SCSPATMARP-MIB", "scspHFSMHFSMState"), ("SCSPATMARP-MIB", "scspHFSMHelloIn"), ("SCSPATMARP-MIB", "scspHFSMHelloOut"), ("SCSPATMARP-MIB", "scspHFSMHelloInvalidIn"), ("SCSPATMARP-MIB", "scspHFSMHelloInterval"), ("SCSPATMARP-MIB", "scspHFSMDeadFactor"), ("SCSPATMARP-MIB", "scspHFSMFamilyID")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): scspAtmarpGroup = scspAtmarpGroup.setStatus('current') if mibBuilder.loadTexts: scspAtmarpGroup.setDescription('This group is mandatory when Atmarp is the client/server protocol running SCSP.') mibBuilder.exportSymbols("SCSPATMARP-MIB", scspAtmarpObjects=scspAtmarpObjects, scspHFSMHelloOut=scspHFSMHelloOut, scspHFSMWaiting=scspHFSMWaiting, scspAtmarpGroups=scspAtmarpGroups, scspAtmarpPeerVCI=scspAtmarpPeerVCI, scspAtmarpCompliance=scspAtmarpCompliance, scspAtmarpConformance=scspAtmarpConformance, scspAtmarpLSRowStatus=scspAtmarpLSRowStatus, scspAtmarpServerGroupNetMask=scspAtmarpServerGroupNetMask, scspAtmarpPeerRowStatus=scspAtmarpPeerRowStatus, scspAtmarpHFSMTable=scspAtmarpHFSMTable, scspAtmarpPeerDCSID=scspAtmarpPeerDCSID, scspAtmarpServerGroupEntry=scspAtmarpServerGroupEntry, scspAtmarpPeerTable=scspAtmarpPeerTable, scspAtmarpLSLSAtmAddr=scspAtmarpLSLSAtmAddr, scspHFSMFamilyID=scspHFSMFamilyID, scspAtmarpServerGroupTable=scspAtmarpServerGroupTable, scspAtmarpLSTable=scspAtmarpLSTable, scspHFSMDeadFactor=scspHFSMDeadFactor, scspHFSMHelloInterval=scspHFSMHelloInterval, scspAtmarpLSEntry=scspAtmarpLSEntry, scspAtmarpPeerEntry=scspAtmarpPeerEntry, scspHFSMHFSMState=scspHFSMHFSMState, scspAtmarpLSLSIPAddr=scspAtmarpLSLSIPAddr, scspAtmarpPeerAtmAddr=scspAtmarpPeerAtmAddr, scspHFSMHelloIn=scspHFSMHelloIn, scspAtmarpGroup=scspAtmarpGroup, scspAtmarpNotifications=scspAtmarpNotifications, scspAtmarpServerGroupRowStatus=scspAtmarpServerGroupRowStatus, scspAtmarpMIB=scspAtmarpMIB, scspAtmarpHFSMEntry=scspAtmarpHFSMEntry, scspAtmarpPeerIndex=scspAtmarpPeerIndex, PYSNMP_MODULE_ID=scspAtmarpMIB, scspAtmarpServerGroupSubnetAddr=scspAtmarpServerGroupSubnetAddr, scspHFSMHelloInvalidIn=scspHFSMHelloInvalidIn, scspHFSMBiConn=scspHFSMBiConn, scspAtmarpHFSMRowStatus=scspAtmarpHFSMRowStatus, scspAtmarpPeerVCType=scspAtmarpPeerVCType, scspAtmarpPeerIPAddr=scspAtmarpPeerIPAddr, scspAtmarpCompliances=scspAtmarpCompliances, scspHFSMDown=scspHFSMDown, scspAtmarpPeerVPI=scspAtmarpPeerVPI)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint') (atm_conn_kind, atm_addr) = mibBuilder.importSymbols('ATM-TC-MIB', 'AtmConnKind', 'AtmAddr') (scsp_lsid, scsp_hfsm_state_type, scsp_server_group_pid, scspvci_integer, scspvpi_integer, scsp_server_group_id, scsp_dcsid) = mibBuilder.importSymbols('SCSP-MIB', 'scspLSID', 'ScspHFSMStateType', 'scspServerGroupPID', 'SCSPVCIInteger', 'SCSPVPIInteger', 'scspServerGroupID', 'scspDCSID') (module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup') (module_identity, time_ticks, counter32, counter64, notification_type, unsigned32, experimental, iso, bits, mib_identifier, integer32, gauge32, ip_address, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'TimeTicks', 'Counter32', 'Counter64', 'NotificationType', 'Unsigned32', 'experimental', 'iso', 'Bits', 'MibIdentifier', 'Integer32', 'Gauge32', 'IpAddress', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity') (display_string, row_status, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'RowStatus', 'TextualConvention') scsp_atmarp_mib = module_identity((1, 3, 6, 1, 3, 2002)) if mibBuilder.loadTexts: scspAtmarpMIB.setLastUpdated('9808020000Z') if mibBuilder.loadTexts: scspAtmarpMIB.setOrganization('IETF Internetworking Over NBMA Working Group (ion)') if mibBuilder.loadTexts: scspAtmarpMIB.setContactInfo('Jim Luciani (jliciani@BayNetworks.com Bay Networks Cliff X. Wang (cliff_wang@vnet.ibm.com) Colin Verrilli (verrilli@vnet.ibm.com) IBM Corp.') if mibBuilder.loadTexts: scspAtmarpMIB.setDescription('This module defines a portion of the management information base (MIB) for managing Server Cache Synchronizatio protocol applied to ATMARP servers.') scsp_atmarp_objects = mib_identifier((1, 3, 6, 1, 3, 2002, 1)) scsp_atmarp_notifications = mib_identifier((1, 3, 6, 1, 3, 2002, 2)) scsp_atmarp_conformance = mib_identifier((1, 3, 6, 1, 3, 2002, 3)) scsp_atmarp_server_group_table = mib_table((1, 3, 6, 1, 3, 2002, 1, 1)) if mibBuilder.loadTexts: scspAtmarpServerGroupTable.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupTable.setDescription('The objects defined in this table are used to for the management of SCSP server groups with application to IP over ATM operation (Classic IP). These objects SHOULD be used along with the protocol independent part objects to support the management of the SCSP protocol applied to synchronizing the atmarp servers in a LIS. There is one entry in this table for each server group. In the case of IP over ATM, each server group corresponds to a Logical IP Subnet.') scsp_atmarp_server_group_entry = mib_table_row((1, 3, 6, 1, 3, 2002, 1, 1, 1)).setIndexNames((0, 'SCSP-MIB', 'scspServerGroupID'), (0, 'SCSP-MIB', 'scspServerGroupPID')) if mibBuilder.loadTexts: scspAtmarpServerGroupEntry.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupEntry.setDescription('Information about SCSP server group running IP over ATM operation. This table is indexed by scspServerGroupID and scspServerGroupPID. The two indeces point to a corresponding entry in the scspServerGroupTable.') scsp_atmarp_server_group_net_mask = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 1, 1, 1), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpServerGroupNetMask.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupNetMask.setDescription('The subnet mask associated with this Server Group.') scsp_atmarp_server_group_subnet_addr = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 1, 1, 2), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpServerGroupSubnetAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupSubnetAddr.setDescription('The IP subnet address associated with this Server Group.') scsp_atmarp_server_group_row_status = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 1, 1, 3), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: scspAtmarpServerGroupRowStatus.setReference("RFC 1903, 'Textual Conventions for version 2 of the Simple Network Management Protocol (SNMPv2).'") if mibBuilder.loadTexts: scspAtmarpServerGroupRowStatus.setStatus('current') if mibBuilder.loadTexts: scspAtmarpServerGroupRowStatus.setDescription('This object allows Atmarp Server Group Table entries to be created and deleted from the scspAtmarpServerGroupTable. Note that scspAtmarpServerGroupTable entry creation and deletion is coupled with scspServerGroupTable entry creation and deletion. A scspAtmarpServerGroupTable entry cannot be created until its corresponding scspServerGroupTable entry is created. When a scspServerGroupTable entry is deleted, it also removes the corresponding scspAtmarpServerGroupTable entry.') scsp_atmarp_ls_table = mib_table((1, 3, 6, 1, 3, 2002, 1, 2)) if mibBuilder.loadTexts: scspAtmarpLSTable.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSTable.setDescription('The objects defined in this table are used to for the management of the Atmarp Local server in a SCSP server group for IP over ATM operation. These objects SHOULD be used along with the protocol independent part objects to support the management of the SCSP protocol applied to synchronizing the IP over ATM servers.') scsp_atmarp_ls_entry = mib_table_row((1, 3, 6, 1, 3, 2002, 1, 2, 1)).setIndexNames((0, 'SCSP-MIB', 'scspServerGroupID'), (0, 'SCSP-MIB', 'scspServerGroupPID'), (0, 'SCSP-MIB', 'scspLSID')) if mibBuilder.loadTexts: scspAtmarpLSEntry.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSEntry.setDescription('Information about Atmarp Local Server in a SCSP server group. This table is indexed by scspServerGroupID, scspServerGroupPID, and scspLSID. The three indeces point to a corresponding entry in the scspLSTable.') scsp_atmarp_lslsip_addr = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 2, 1, 1), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpLSLSIPAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSLSIPAddr.setDescription('The IP address of the Atmarp Local Server. Since an Atmarp server does not have to be assigned an IP address, this object is optional.') scsp_atmarp_lsls_atm_addr = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 2, 1, 2), atm_addr()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpLSLSAtmAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSLSAtmAddr.setDescription('The ATM address of the Atmarp Local Server.') scsp_atmarp_ls_row_status = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 2, 1, 3), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: scspAtmarpLSRowStatus.setStatus('current') if mibBuilder.loadTexts: scspAtmarpLSRowStatus.setDescription('This object allows Atmarp Local Server Table entries to be created and deleted from the scspAtmarpLSTable. Note that scspAtmarpLSTable entry creation and deletion is coupled with scspLSTable entry creation and deletion. A scspAtmarpLSTable entry cannot be created until its corresponding scspLSTable entry is created. When a scspLSTable entry is deleted, it also removes the corresponding scspAtmarpLSTable entry.') scsp_atmarp_peer_table = mib_table((1, 3, 6, 1, 3, 2002, 1, 3)) if mibBuilder.loadTexts: scspAtmarpPeerTable.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerTable.setDescription('The objects defined in this table are used to for the management of the ATMARP sever peers.') scsp_atmarp_peer_entry = mib_table_row((1, 3, 6, 1, 3, 2002, 1, 3, 1)).setIndexNames((0, 'SCSP-MIB', 'scspServerGroupID'), (0, 'SCSP-MIB', 'scspServerGroupPID'), (0, 'SCSPATMARP-MIB', 'scspAtmarpPeerIndex')) if mibBuilder.loadTexts: scspAtmarpPeerEntry.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerEntry.setDescription('Information about each peer ATMARP server participated in the scsp Server group. The table is indexed by scspServerGroupID, scspServerGroupPID, and scspAtmarpPeerIndex.') scsp_atmarp_peer_index = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 3, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpPeerIndex.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerIndex.setDescription('The table index of the peer Atmarp server table.') scsp_atmarp_peer_ip_addr = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 3, 1, 2), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpPeerIPAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerIPAddr.setDescription('The IP address of the peer Atmarp server. Since an Atmarp server does not have to be assigned an IP address, this object is optional.') scsp_atmarp_peer_atm_addr = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 3, 1, 3), atm_addr()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpPeerAtmAddr.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerAtmAddr.setDescription("The ATM address of the Peer. If SVC is used between LS and Peer, Peer's ATM address should be valid. However, if PVC is used instead SVC, the Peer's ATM address may be a Null OCTET STRING.") scsp_atmarp_peer_vc_type = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 3, 1, 4), atm_conn_kind()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpPeerVCType.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerVCType.setDescription('The type of the virtual circuit between LS and Peer.') scsp_atmarp_peer_vpi = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 3, 1, 5), scspvpi_integer()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpPeerVPI.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerVPI.setDescription('The VPI value for the virtual circuit between LS and Peer.') scsp_atmarp_peer_vci = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 3, 1, 6), scspvci_integer()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpPeerVCI.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerVCI.setDescription('The VCI value for the virtual circuit between LS and Peer.') scsp_atmarp_peer_dcsid = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 3, 1, 7), octet_string().subtype(subtypeSpec=value_size_constraint(0, 63))).setMaxAccess('readonly') if mibBuilder.loadTexts: scspAtmarpPeerDCSID.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerDCSID.setDescription('The DCS ID for this peer. When the peer tabel is created, DCS ID may not have been discovered. Tt is set to a Null string. It will be update when the DCS ID associated with this peer (ATM address) is discovered.') scsp_atmarp_peer_row_status = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 3, 1, 8), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: scspAtmarpPeerRowStatus.setReference("RFC 1903, 'Textual Conventions for version 2 of the Simple Network Management Protocol (SNMPv2).'") if mibBuilder.loadTexts: scspAtmarpPeerRowStatus.setStatus('current') if mibBuilder.loadTexts: scspAtmarpPeerRowStatus.setDescription('This object allows Atmarp Peer table entries to be created and deleted from the scspAtmarpPeerTable. Note that scspAtmarpPeerTable entry is created when a peer is configured loaclly or when a peer not previously configured connects to LS.') scsp_atmarp_hfsm_table = mib_table((1, 3, 6, 1, 3, 2002, 1, 4)) if mibBuilder.loadTexts: scspAtmarpHFSMTable.setStatus('current') if mibBuilder.loadTexts: scspAtmarpHFSMTable.setDescription('The objects defined in this table are used to for the management of the HFSM between the LS and the DCS.') scsp_atmarp_hfsm_entry = mib_table_row((1, 3, 6, 1, 3, 2002, 1, 4, 1)).setIndexNames((0, 'SCSP-MIB', 'scspServerGroupID'), (0, 'SCSP-MIB', 'scspServerGroupPID'), (0, 'SCSPATMARP-MIB', 'scspAtmarpPeerIndex')) if mibBuilder.loadTexts: scspAtmarpHFSMEntry.setStatus('current') if mibBuilder.loadTexts: scspAtmarpHFSMEntry.setDescription('Information about SCSP HFSM session between the LS and its HFSMs. The table is indexed by scspServerGroupID, scspServerGroupPID, and scspAtmarpPeerIndex.') scsp_hfsmhfsm_state = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 4, 1, 1), scsp_hfsm_state_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspHFSMHFSMState.setReference('SCSP draft, Section 2.1') if mibBuilder.loadTexts: scspHFSMHFSMState.setStatus('current') if mibBuilder.loadTexts: scspHFSMHFSMState.setDescription('The current state of the Hello Finite State Machine. The allowable states are: down(1), waiting(2), uniConn(3), biConn(4).') scsp_hfsm_hello_in = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 4, 1, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspHFSMHelloIn.setStatus('current') if mibBuilder.loadTexts: scspHFSMHelloIn.setDescription("The number of 'Hello' messages received from this HFSM.") scsp_hfsm_hello_out = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 4, 1, 3), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspHFSMHelloOut.setStatus('current') if mibBuilder.loadTexts: scspHFSMHelloOut.setDescription("The number of 'Hello' messages sent from LS to this HFSM.") scsp_hfsm_hello_invalid_in = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 4, 1, 4), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: scspHFSMHelloInvalidIn.setStatus('current') if mibBuilder.loadTexts: scspHFSMHelloInvalidIn.setDescription("The number of invalid 'Hello' messages received from this HFSM. Possible message errors include: Hello message when the HFSM is in 'Down' state; Hello message is too short to contain the number of Receiver ID records specified in the header, etc. Other common errors include failed authentication if applicable, errors in the message fields, etc.") scsp_hfsm_hello_interval = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 4, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: scspHFSMHelloInterval.setStatus('current') if mibBuilder.loadTexts: scspHFSMHelloInterval.setDescription('This object contains the value for HelloInterval with the associated HFSM. It is the time (in seconds) between sending of consecutive Hello messages from the HFSM.') scsp_hfsm_dead_factor = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 4, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: scspHFSMDeadFactor.setStatus('current') if mibBuilder.loadTexts: scspHFSMDeadFactor.setDescription("This object contains the value for DeadFactor with this associated server. The DeadFactor along with HelloInterval are contained in 'Hello' messages sent from this HFSM. If 'Hello' messages are not received from this HFSM within the time out interval 'HelloInterval*DeadFactor' (in seconds), then the HFSM MUST be considered to be stalled.") scsp_hfsm_family_id = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 4, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readonly') if mibBuilder.loadTexts: scspHFSMFamilyID.setReference('SCSP draft, Sec.2 and Sec. B.2.5') if mibBuilder.loadTexts: scspHFSMFamilyID.setStatus('current') if mibBuilder.loadTexts: scspHFSMFamilyID.setDescription('The family ID is used to refer an aggregate of Protocol ID/SGID pairs. Only a single HFSM is run for all Protocol ID/SGID pairs assigned to a Family ID. When the HFSM is not shared by an aggregate of Protocol ID/SGID pairs, this object should be set to 0.') scsp_atmarp_hfsm_row_status = mib_table_column((1, 3, 6, 1, 3, 2002, 1, 4, 1, 8), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: scspAtmarpHFSMRowStatus.setReference("RFC 1903, 'Textual Conventions for version 2 of the Simple Network Management Protocol (SNMPv2).'") if mibBuilder.loadTexts: scspAtmarpHFSMRowStatus.setStatus('current') if mibBuilder.loadTexts: scspAtmarpHFSMRowStatus.setDescription('This object allows Atmarp HFSM table entries to be created and deleted from the scspAtmarpHFSMTable. Note that scspAtmarpHFSMTable entry creation and deletion is closely coupled with scspHFSMTable entry creation. A scspAtmarpHFSMTable entry cannot be created until its corresponding scspHFSMTable entry is created. When a scspHFSMTable entry is deleted, it also removes the corresponding scspAtmarpHFSMTable entry.') scsp_hfsm_down = notification_type((1, 3, 6, 1, 3, 2002, 2, 1)).setObjects(('SCSP-MIB', 'scspServerGroupID'), ('SCSP-MIB', 'scspServerGroupPID'), ('SCSPATMARP-MIB', 'scspAtmarpPeerIndex')) if mibBuilder.loadTexts: scspHFSMDown.setStatus('current') if mibBuilder.loadTexts: scspHFSMDown.setDescription("The Hello Finite State Machine associated with this LS/DCS pair enters 'Down' state.") scsp_hfsm_waiting = notification_type((1, 3, 6, 1, 3, 2002, 2, 2)).setObjects(('SCSP-MIB', 'scspServerGroupID'), ('SCSP-MIB', 'scspServerGroupPID'), ('SCSPATMARP-MIB', 'scspAtmarpPeerIndex')) if mibBuilder.loadTexts: scspHFSMWaiting.setStatus('current') if mibBuilder.loadTexts: scspHFSMWaiting.setDescription("The Hello Finite State Machine associated with this LS/DCS pair enters 'Waiting' state.") scsp_hfsm_bi_conn = notification_type((1, 3, 6, 1, 3, 2002, 2, 3)).setObjects(('SCSP-MIB', 'scspServerGroupID'), ('SCSP-MIB', 'scspServerGroupPID'), ('SCSPATMARP-MIB', 'scspAtmarpPeerIndex')) if mibBuilder.loadTexts: scspHFSMBiConn.setStatus('current') if mibBuilder.loadTexts: scspHFSMBiConn.setDescription("The Hello Finite State Machine associated with this LS/DCS pair enters 'Bidirectional connection' state.") scsp_atmarp_compliances = mib_identifier((1, 3, 6, 1, 3, 2002, 3, 1)) scsp_atmarp_groups = mib_identifier((1, 3, 6, 1, 3, 2002, 3, 2)) scsp_atmarp_compliance = module_compliance((1, 3, 6, 1, 3, 2002, 3, 1, 1)).setObjects(('SCSPATMARP-MIB', 'scspAtmarpGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): scsp_atmarp_compliance = scspAtmarpCompliance.setStatus('current') if mibBuilder.loadTexts: scspAtmarpCompliance.setDescription('The compliance statement for entities that are required for the management of SCSP when applied to ATMARP servers.') scsp_atmarp_group = object_group((1, 3, 6, 1, 3, 2002, 3, 2, 1)).setObjects(('SCSPATMARP-MIB', 'scspAtmarpServerGroupNetMask'), ('SCSPATMARP-MIB', 'scspAtmarpServerGroupSubnetAddr'), ('SCSPATMARP-MIB', 'scspAtmarpLSLSIPAddr'), ('SCSPATMARP-MIB', 'scspAtmarpLSLSAtmAddr'), ('SCSPATMARP-MIB', 'scspAtmarpPeerIndex'), ('SCSPATMARP-MIB', 'scspAtmarpPeerAtmAddr'), ('SCSPATMARP-MIB', 'scspAtmarpPeerVCType'), ('SCSPATMARP-MIB', 'scspAtmarpPeerVPI'), ('SCSPATMARP-MIB', 'scspAtmarpPeerVCI'), ('SCSPATMARP-MIB', 'scspAtmarpPeerDCSID'), ('SCSPATMARP-MIB', 'scspHFSMHFSMState'), ('SCSPATMARP-MIB', 'scspHFSMHelloIn'), ('SCSPATMARP-MIB', 'scspHFSMHelloOut'), ('SCSPATMARP-MIB', 'scspHFSMHelloInvalidIn'), ('SCSPATMARP-MIB', 'scspHFSMHelloInterval'), ('SCSPATMARP-MIB', 'scspHFSMDeadFactor'), ('SCSPATMARP-MIB', 'scspHFSMFamilyID')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): scsp_atmarp_group = scspAtmarpGroup.setStatus('current') if mibBuilder.loadTexts: scspAtmarpGroup.setDescription('This group is mandatory when Atmarp is the client/server protocol running SCSP.') mibBuilder.exportSymbols('SCSPATMARP-MIB', scspAtmarpObjects=scspAtmarpObjects, scspHFSMHelloOut=scspHFSMHelloOut, scspHFSMWaiting=scspHFSMWaiting, scspAtmarpGroups=scspAtmarpGroups, scspAtmarpPeerVCI=scspAtmarpPeerVCI, scspAtmarpCompliance=scspAtmarpCompliance, scspAtmarpConformance=scspAtmarpConformance, scspAtmarpLSRowStatus=scspAtmarpLSRowStatus, scspAtmarpServerGroupNetMask=scspAtmarpServerGroupNetMask, scspAtmarpPeerRowStatus=scspAtmarpPeerRowStatus, scspAtmarpHFSMTable=scspAtmarpHFSMTable, scspAtmarpPeerDCSID=scspAtmarpPeerDCSID, scspAtmarpServerGroupEntry=scspAtmarpServerGroupEntry, scspAtmarpPeerTable=scspAtmarpPeerTable, scspAtmarpLSLSAtmAddr=scspAtmarpLSLSAtmAddr, scspHFSMFamilyID=scspHFSMFamilyID, scspAtmarpServerGroupTable=scspAtmarpServerGroupTable, scspAtmarpLSTable=scspAtmarpLSTable, scspHFSMDeadFactor=scspHFSMDeadFactor, scspHFSMHelloInterval=scspHFSMHelloInterval, scspAtmarpLSEntry=scspAtmarpLSEntry, scspAtmarpPeerEntry=scspAtmarpPeerEntry, scspHFSMHFSMState=scspHFSMHFSMState, scspAtmarpLSLSIPAddr=scspAtmarpLSLSIPAddr, scspAtmarpPeerAtmAddr=scspAtmarpPeerAtmAddr, scspHFSMHelloIn=scspHFSMHelloIn, scspAtmarpGroup=scspAtmarpGroup, scspAtmarpNotifications=scspAtmarpNotifications, scspAtmarpServerGroupRowStatus=scspAtmarpServerGroupRowStatus, scspAtmarpMIB=scspAtmarpMIB, scspAtmarpHFSMEntry=scspAtmarpHFSMEntry, scspAtmarpPeerIndex=scspAtmarpPeerIndex, PYSNMP_MODULE_ID=scspAtmarpMIB, scspAtmarpServerGroupSubnetAddr=scspAtmarpServerGroupSubnetAddr, scspHFSMHelloInvalidIn=scspHFSMHelloInvalidIn, scspHFSMBiConn=scspHFSMBiConn, scspAtmarpHFSMRowStatus=scspAtmarpHFSMRowStatus, scspAtmarpPeerVCType=scspAtmarpPeerVCType, scspAtmarpPeerIPAddr=scspAtmarpPeerIPAddr, scspAtmarpCompliances=scspAtmarpCompliances, scspHFSMDown=scspHFSMDown, scspAtmarpPeerVPI=scspAtmarpPeerVPI)
# coding=utf-8 __author__ = 'lxn3032' class ControllerBase(object): def __init__(self, period, ValueType=float): self.ValueType = ValueType self.T = period self.error_1 = ValueType(0) self.error_2 = ValueType(0) self.current_value = ValueType(0) self.target_value = ValueType(0) def delta_closed_loop_gain(self, feedback): raise NotImplementedError def close_loop_gain(self, feedback): raise NotImplementedError def set_target_value(self, val): self.target_value = val def get_current_value(self): return self.current_value def reset_errors(self): self.error_1 = self.error_2 = self.ValueType(0) class PIDController(ControllerBase): def __init__(self, period, Kp=1, Ki=0, Kd=0, ValueType=float): super(PIDController, self).__init__(period, ValueType) self.Kp = Kp self.Ki = Ki self.Kd = Kd self.sum_error = ValueType(0) def delta_closed_loop_gain(self, feedback): self.current_value = feedback error = self.target_value - self.current_value d_error = error - self.error_1 d2_error = error - 2 * self.error_1 + self.error_2 delta_output = self.Kp * d_error + self.Ki * error + self.Kd * d2_error self.error_2 = self.error_1 self.error_1 = error return delta_output def closed_loop_gain(self, feedback): self.current_value = feedback error = self.target_value - self.current_value self.sum_error += error d_error = error - self.error_1 output = self.Kp * error + self.Ki * self.sum_error + self.Kd * d_error self.error_2 = self.error_1 self.error_1 = error return output
__author__ = 'lxn3032' class Controllerbase(object): def __init__(self, period, ValueType=float): self.ValueType = ValueType self.T = period self.error_1 = value_type(0) self.error_2 = value_type(0) self.current_value = value_type(0) self.target_value = value_type(0) def delta_closed_loop_gain(self, feedback): raise NotImplementedError def close_loop_gain(self, feedback): raise NotImplementedError def set_target_value(self, val): self.target_value = val def get_current_value(self): return self.current_value def reset_errors(self): self.error_1 = self.error_2 = self.ValueType(0) class Pidcontroller(ControllerBase): def __init__(self, period, Kp=1, Ki=0, Kd=0, ValueType=float): super(PIDController, self).__init__(period, ValueType) self.Kp = Kp self.Ki = Ki self.Kd = Kd self.sum_error = value_type(0) def delta_closed_loop_gain(self, feedback): self.current_value = feedback error = self.target_value - self.current_value d_error = error - self.error_1 d2_error = error - 2 * self.error_1 + self.error_2 delta_output = self.Kp * d_error + self.Ki * error + self.Kd * d2_error self.error_2 = self.error_1 self.error_1 = error return delta_output def closed_loop_gain(self, feedback): self.current_value = feedback error = self.target_value - self.current_value self.sum_error += error d_error = error - self.error_1 output = self.Kp * error + self.Ki * self.sum_error + self.Kd * d_error self.error_2 = self.error_1 self.error_1 = error return output
{ "cells": [ { "cell_type": "code", "execution_count": 20, "id": "informative-england", "metadata": {}, "outputs": [], "source": [ "### This is the interworkings and mathematics behind the equity models\n", "\n", "### Gordon (Constant) Growth Model module ###\n", "def Gordongrowth(dividend, costofequity, growthrate):\n", " price = dividend / (costofequity - growthrate)\n", " price1 = round(price * .95, 2)\n", " price2 = round(price * 1.05, 2)\n", " print(f\"Based on the Gordon Growth Model, this stock's price is valued between: {price1} and {price2}.\")\n", " \n", "### One Year Holding Perid\n", "def oneyearmodel(saleprice, dividend, costofequity):\n", " price = (dividend + saleprice) / (1 + costofequity)\n", " price1 = round(price * .95, 2)\n", " price2 = round(price * 1.05, 2)\n", " print(f\"Based on the One Year Holding Model, this stock's price is valued between: {price1} and {price2}.\")\n", "\n", "### Multi-Stage (Double Year Holding Period) Dividend Discount Model module ###\n", "def doubleyearmodel(saleprice, dividend1, dividend2, costofequity):\n", " price = (dividend1 / (1 + costofequity)) + (dividend2 / (1 + costofequity)**2) + (saleprice / (1 + costofequity)**2)\n", " price1 = round(price * .95, 2)\n", " price2 = round(price * 1.05, 2)\n", " print(f\"Based on the Two Year Holding Model, this stock's price is valued between: {price1} and {price2}.\")" ] }, { "cell_type": "code", "execution_count": 25, "id": "postal-title", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Based on the Gordon Growth Model, this stock's price is valued between: 158.33 and 175.0.\n" ] } ], "source": [ "Gordongrowth(5, .08, 0.05)" ] }, { "cell_type": "code", "execution_count": 26, "id": "thrown-length", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Based on the Two Year Holding Model, this stock's price is valued between: 194.09 and 214.52.\n" ] } ], "source": [ "doubleyearmodel(200, 5, 20,.05)" ] }, { "cell_type": "code", "execution_count": 27, "id": "hungarian-symbol", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Based on the One Year Holding Model, this stock's price is valued between: 185.48 and 205.0.\n" ] } ], "source": [ "oneyearmodel(200, 5, .05)" ] }, { "cell_type": "code", "execution_count": 24, "id": "impossible-coral", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "oneyearmodel() missing 1 required positional argument: 'costofequity'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m<ipython-input-24-e0f7cbe98c62>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0moneyearmodel\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: oneyearmodel() missing 1 required positional argument: 'costofequity'" ] } ], "source": [ "oneyearmodel(2,4)" ] }, { "cell_type": "code", "execution_count": null, "id": "binary-glass", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.1" } }, "nbformat": 4, "nbformat_minor": 5 }
{'cells': [{'cell_type': 'code', 'execution_count': 20, 'id': 'informative-england', 'metadata': {}, 'outputs': [], 'source': ['### This is the interworkings and mathematics behind the equity models\n', '\n', '### Gordon (Constant) Growth Model module ###\n', 'def Gordongrowth(dividend, costofequity, growthrate):\n', ' price = dividend / (costofequity - growthrate)\n', ' price1 = round(price * .95, 2)\n', ' price2 = round(price * 1.05, 2)\n', ' print(f"Based on the Gordon Growth Model, this stock\'s price is valued between: {price1} and {price2}.")\n', ' \n', '### One Year Holding Perid\n', 'def oneyearmodel(saleprice, dividend, costofequity):\n', ' price = (dividend + saleprice) / (1 + costofequity)\n', ' price1 = round(price * .95, 2)\n', ' price2 = round(price * 1.05, 2)\n', ' print(f"Based on the One Year Holding Model, this stock\'s price is valued between: {price1} and {price2}.")\n', '\n', '### Multi-Stage (Double Year Holding Period) Dividend Discount Model module ###\n', 'def doubleyearmodel(saleprice, dividend1, dividend2, costofequity):\n', ' price = (dividend1 / (1 + costofequity)) + (dividend2 / (1 + costofequity)**2) + (saleprice / (1 + costofequity)**2)\n', ' price1 = round(price * .95, 2)\n', ' price2 = round(price * 1.05, 2)\n', ' print(f"Based on the Two Year Holding Model, this stock\'s price is valued between: {price1} and {price2}.")']}, {'cell_type': 'code', 'execution_count': 25, 'id': 'postal-title', 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ["Based on the Gordon Growth Model, this stock's price is valued between: 158.33 and 175.0.\n"]}], 'source': ['Gordongrowth(5, .08, 0.05)']}, {'cell_type': 'code', 'execution_count': 26, 'id': 'thrown-length', 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ["Based on the Two Year Holding Model, this stock's price is valued between: 194.09 and 214.52.\n"]}], 'source': ['doubleyearmodel(200, 5, 20,.05)']}, {'cell_type': 'code', 'execution_count': 27, 'id': 'hungarian-symbol', 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ["Based on the One Year Holding Model, this stock's price is valued between: 185.48 and 205.0.\n"]}], 'source': ['oneyearmodel(200, 5, .05)']}, {'cell_type': 'code', 'execution_count': 24, 'id': 'impossible-coral', 'metadata': {}, 'outputs': [{'ename': 'TypeError', 'evalue': "oneyearmodel() missing 1 required positional argument: 'costofequity'", 'output_type': 'error', 'traceback': ['\x1b[1;31m---------------------------------------------------------------------------\x1b[0m', '\x1b[1;31mTypeError\x1b[0m Traceback (most recent call last)', '\x1b[1;32m<ipython-input-24-e0f7cbe98c62>\x1b[0m in \x1b[0;36m<module>\x1b[1;34m\x1b[0m\n\x1b[1;32m----> 1\x1b[1;33m \x1b[0moneyearmodel\x1b[0m\x1b[1;33m(\x1b[0m\x1b[1;36m2\x1b[0m\x1b[1;33m,\x1b[0m\x1b[1;36m4\x1b[0m\x1b[1;33m)\x1b[0m\x1b[1;33m\x1b[0m\x1b[1;33m\x1b[0m\x1b[0m\n\x1b[0m', "\x1b[1;31mTypeError\x1b[0m: oneyearmodel() missing 1 required positional argument: 'costofequity'"]}], 'source': ['oneyearmodel(2,4)']}, {'cell_type': 'code', 'execution_count': null, 'id': 'binary-glass', 'metadata': {}, 'outputs': [], 'source': []}], 'metadata': {'kernelspec': {'display_name': 'Python 3', 'language': 'python', 'name': 'python3'}, 'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3}, 'file_extension': '.py', 'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python', 'pygments_lexer': 'ipython3', 'version': '3.9.1'}}, 'nbformat': 4, 'nbformat_minor': 5}
# -*- coding: utf-8 -*- """Dot.notation attributes for dictionaries. Includes recursive DotDict behavior for nested dictionaries. """ class DotDict(dict): """DotDict creates an interface for using dictionaries as attr containers. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for key, val in self.items(): self.__setitem__(key, val) def __getattr__(self, name): try: return self[name] except KeyError as ex: raise AttributeError(f"no attribute called {name}") from ex def __delattr__(self, name): try: del self[name] except KeyError as ex: raise AttributeError(f"no attribute called {name}") from ex def __setitem__(self, name, value): super().__setitem__(name, DotDict.__convert(value)) __setattr__ = __setitem__ @staticmethod def __convert(val): if isinstance(val, (dict,)): return DotDict(val) if isinstance(val, (list, set, tuple)): items = filter(None, (DotDict.__convert(val_item) for val_item in val)) return type(val)(items) return val @staticmethod def build_from_object(obj): """Creates a DotDict from an object's public/protected attrs. builtins and methods are skipped """ result = DotDict() for name in dir(obj): if not isinstance(name, (str, bytes)) or name.startswith('__'): continue result[name] = DotDict.__convert(getattr(obj, name)) return result
"""Dot.notation attributes for dictionaries. Includes recursive DotDict behavior for nested dictionaries. """ class Dotdict(dict): """DotDict creates an interface for using dictionaries as attr containers. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for (key, val) in self.items(): self.__setitem__(key, val) def __getattr__(self, name): try: return self[name] except KeyError as ex: raise attribute_error(f'no attribute called {name}') from ex def __delattr__(self, name): try: del self[name] except KeyError as ex: raise attribute_error(f'no attribute called {name}') from ex def __setitem__(self, name, value): super().__setitem__(name, DotDict.__convert(value)) __setattr__ = __setitem__ @staticmethod def __convert(val): if isinstance(val, (dict,)): return dot_dict(val) if isinstance(val, (list, set, tuple)): items = filter(None, (DotDict.__convert(val_item) for val_item in val)) return type(val)(items) return val @staticmethod def build_from_object(obj): """Creates a DotDict from an object's public/protected attrs. builtins and methods are skipped """ result = dot_dict() for name in dir(obj): if not isinstance(name, (str, bytes)) or name.startswith('__'): continue result[name] = DotDict.__convert(getattr(obj, name)) return result
class SYCSException(Exception): pass class CredentialsException(SYCSException): def __init__(self): super(SYCSException, self).__init__('username or password not provided.') class InvalidCredentialsException(SYCSException): def __init__(self): super(SYCSException, self).__init__('wrong username or password.') class WrongRangeException(SYCSException): def __init__(self): super(SYCSException, self).__init__("start or end must be equal or greater than 1 and start must be equal or " "lower than end") class ForbiddenException(SYCSException): def __init__(self): super(SYCSException, self).__init__("access forbidden, perhaps unpaid subscription o_0 ?") class CourseNotFoundException(SYCSException): def __init__(self): super(SYCSException, self).__init__("invalid course") class TooManyException(SYCSException): def __init__(self): super(SYCSException, self).__init__("on auth server response: too many, slow down the process")
class Sycsexception(Exception): pass class Credentialsexception(SYCSException): def __init__(self): super(SYCSException, self).__init__('username or password not provided.') class Invalidcredentialsexception(SYCSException): def __init__(self): super(SYCSException, self).__init__('wrong username or password.') class Wrongrangeexception(SYCSException): def __init__(self): super(SYCSException, self).__init__('start or end must be equal or greater than 1 and start must be equal or lower than end') class Forbiddenexception(SYCSException): def __init__(self): super(SYCSException, self).__init__('access forbidden, perhaps unpaid subscription o_0 ?') class Coursenotfoundexception(SYCSException): def __init__(self): super(SYCSException, self).__init__('invalid course') class Toomanyexception(SYCSException): def __init__(self): super(SYCSException, self).__init__('on auth server response: too many, slow down the process')
def solution(A, B, s): A.sort() B.sort() i = len(A) - 1 j = len(B) - 1 while 0 <= j <= len(B) - 1 and i: pass
def solution(A, B, s): A.sort() B.sort() i = len(A) - 1 j = len(B) - 1 while 0 <= j <= len(B) - 1 and i: pass
a = int(input()) for i in range(1, a+1): if a % i == 0: print(i)
a = int(input()) for i in range(1, a + 1): if a % i == 0: print(i)
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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. # # Const Class # this is a auto generated file generated by Cheetah # Libre Office Version: 7.3 # Namespace: com.sun.star.text class RelOrientation(object): """ Const Class These values define the reference position of relative orientations. **since** LibreOffice 7.0 See Also: `API RelOrientation <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1text_1_1RelOrientation.html>`_ """ __ooo_ns__: str = 'com.sun.star.text' __ooo_full_ns__: str = 'com.sun.star.text.RelOrientation' __ooo_type_name__: str = 'const' FRAME = 0 """ paragraph, including margins """ PRINT_AREA = 1 """ paragraph, without margins """ CHAR = 2 """ at a character """ PAGE_LEFT = 3 """ inside the left page margin """ PAGE_RIGHT = 4 """ inside the right page margin """ FRAME_LEFT = 5 """ inside the left paragraph margin """ FRAME_RIGHT = 6 """ inside the right paragraph margin """ PAGE_FRAME = 7 """ page includes margins for page-anchored frames identical with RelOrientation.FRAME """ PAGE_PRINT_AREA = 8 """ page without borders (for page anchored frames identical with RelOrientation.PRINT_AREA). """ TEXT_LINE = 9 """ at the top of the text line, only sensible for vertical orientation. **since** OOo 2.0 """ PAGE_PRINT_AREA_BOTTOM = 10 """ Bottom page border (page area below PAGE_PRINT_AREA). **since** LibreOffice 7.0 """ PAGE_PRINT_AREA_TOP = 11 """ Top page border (page area above PAGE_PRINT_AREA). **since** LibreOffice 7.1 """ __all__ = ['RelOrientation']
class Relorientation(object): """ Const Class These values define the reference position of relative orientations. **since** LibreOffice 7.0 See Also: `API RelOrientation <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1text_1_1RelOrientation.html>`_ """ __ooo_ns__: str = 'com.sun.star.text' __ooo_full_ns__: str = 'com.sun.star.text.RelOrientation' __ooo_type_name__: str = 'const' frame = 0 '\n paragraph, including margins\n ' print_area = 1 '\n paragraph, without margins\n ' char = 2 '\n at a character\n ' page_left = 3 '\n inside the left page margin\n ' page_right = 4 '\n inside the right page margin\n ' frame_left = 5 '\n inside the left paragraph margin\n ' frame_right = 6 '\n inside the right paragraph margin\n ' page_frame = 7 '\n page includes margins for page-anchored frames identical with RelOrientation.FRAME\n ' page_print_area = 8 '\n page without borders (for page anchored frames identical with RelOrientation.PRINT_AREA).\n ' text_line = 9 '\n at the top of the text line, only sensible for vertical orientation.\n \n **since**\n \n OOo 2.0\n ' page_print_area_bottom = 10 '\n Bottom page border (page area below PAGE_PRINT_AREA).\n \n **since**\n \n LibreOffice 7.0\n ' page_print_area_top = 11 '\n Top page border (page area above PAGE_PRINT_AREA).\n \n **since**\n \n LibreOffice 7.1\n ' __all__ = ['RelOrientation']
class When_we_have_a_test: @classmethod def examples(cls): yield 1 yield 3 def when_things_happen(self): pass def it_should_do_this_test(self, arg): assert arg < 3
class When_We_Have_A_Test: @classmethod def examples(cls): yield 1 yield 3 def when_things_happen(self): pass def it_should_do_this_test(self, arg): assert arg < 3
# Copyright 2021 Adobe. All rights reserved. # This file is licensed to you under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. You may obtain a copy # of the License at http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS # OF ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. """Error and log messages""" DECISIONING_ENGINE_NOT_READY = "Unable to fulfill request; decisioning engine not ready." def attribute_not_exist(key_name, mbox_name): """Mbox attribute does not exist error string""" return "Attribute '{}' does not exist for mbox '{}'".format(key_name, mbox_name) def property_token_mismatch(request_property, config_property): """Property token mismatch error string""" return "The property token specified in the request '{}' does not match the one specified in the config '{}'."\ .format(request_property, config_property)
"""Error and log messages""" decisioning_engine_not_ready = 'Unable to fulfill request; decisioning engine not ready.' def attribute_not_exist(key_name, mbox_name): """Mbox attribute does not exist error string""" return "Attribute '{}' does not exist for mbox '{}'".format(key_name, mbox_name) def property_token_mismatch(request_property, config_property): """Property token mismatch error string""" return "The property token specified in the request '{}' does not match the one specified in the config '{}'.".format(request_property, config_property)
class Solution: def validTree(self, n: int, edges: list[list[int]]) -> bool: if not n: return True adj = {i: [] for i in range(n)} for n1, n2 in edges: adj[n1].append(n2) adj[n2].append(n1) visit = set() def dfs(i, prev): if i in visit: return False visit.add(i) for j in adj[i]: if j == prev: continue if not dfs(j, i): return False return True return dfs(0, -1) and n == len(visit)
class Solution: def valid_tree(self, n: int, edges: list[list[int]]) -> bool: if not n: return True adj = {i: [] for i in range(n)} for (n1, n2) in edges: adj[n1].append(n2) adj[n2].append(n1) visit = set() def dfs(i, prev): if i in visit: return False visit.add(i) for j in adj[i]: if j == prev: continue if not dfs(j, i): return False return True return dfs(0, -1) and n == len(visit)
def get_accounts_for_path(client, path): ou = client.convert_path_to_ou(path) response = client.list_children_nested(ParentId=ou, ChildType="ACCOUNT") return ",".join([r.get("Id") for r in response]) # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 macros = {"get_accounts_for_path": get_accounts_for_path}
def get_accounts_for_path(client, path): ou = client.convert_path_to_ou(path) response = client.list_children_nested(ParentId=ou, ChildType='ACCOUNT') return ','.join([r.get('Id') for r in response]) macros = {'get_accounts_for_path': get_accounts_for_path}
# Busiest Time in The Mall def find_busiest_period(data): peak_time = peak_vis = cur_vis = i = 0 while i < len(data): time, v, enter = data[i] cur_vis += v if enter else -v if i == len(data)-1 or time != data[i+1][0]: if cur_vis > peak_vis: peak_vis = cur_vis peak_time = time i += 1 return peak_time
def find_busiest_period(data): peak_time = peak_vis = cur_vis = i = 0 while i < len(data): (time, v, enter) = data[i] cur_vis += v if enter else -v if i == len(data) - 1 or time != data[i + 1][0]: if cur_vis > peak_vis: peak_vis = cur_vis peak_time = time i += 1 return peak_time
def test__delete__401_when_no_auth_headers(client): r = client.delete('/themes/1') assert r.status_code == 401, r.get_json() def test__delete__401_when_incorrect_auth(client, faker): r = client.delete('/themes/1', headers={ 'Authentication': 'some_incorrect_token'}) assert r.status_code == 401, r.get_json() # TODO # def test__delete__403_when_incorrect_role(client, faker): # r = client.delete('/themes/1', headers={ # 'Authentication': 'some_incorrect_token'}) # assert r.status_code == 401, r.get_json()
def test__delete__401_when_no_auth_headers(client): r = client.delete('/themes/1') assert r.status_code == 401, r.get_json() def test__delete__401_when_incorrect_auth(client, faker): r = client.delete('/themes/1', headers={'Authentication': 'some_incorrect_token'}) assert r.status_code == 401, r.get_json()
# Python 3.8.3 with open("input.txt", "r") as f: puzzle_input = [int(i) for i in f.read().split()] def fuel_needed(mass): fuel = mass // 3 - 2 return fuel + fuel_needed(fuel) if fuel > 0 else 0 sum = 0 for mass in puzzle_input: sum += fuel_needed(mass) print(sum)
with open('input.txt', 'r') as f: puzzle_input = [int(i) for i in f.read().split()] def fuel_needed(mass): fuel = mass // 3 - 2 return fuel + fuel_needed(fuel) if fuel > 0 else 0 sum = 0 for mass in puzzle_input: sum += fuel_needed(mass) print(sum)
"""defines errors for canvasplus.""" """Luke-zhang-04 CanvasPlus v1.3.0 (https://github.com/Luke-zhang-04/CanvasPlus) Copyright (C) 2020 Luke Zhang Licensed under the MIT License """ class Error(Exception): """Base class for other exceptions.""" pass class InvalidUnitError(Error): """Raised when unit is not recognised.""" pass class UnsupportedObjectType(UserWarning): """raised when object type is not supported.""" pass class InvalidObjectType(Error): """raised when object type not supported.""" pass class InvalidEquation(Error): """raised when euqtion of a line is invalid.""" pass class MorphError(Error): """raised when *coords array in async_morph is not the same size as the coords of the original shape.""" pass
"""defines errors for canvasplus.""" 'Luke-zhang-04\nCanvasPlus v1.3.0 (https://github.com/Luke-zhang-04/CanvasPlus)\nCopyright (C) 2020 Luke Zhang\nLicensed under the MIT License\n' class Error(Exception): """Base class for other exceptions.""" pass class Invaliduniterror(Error): """Raised when unit is not recognised.""" pass class Unsupportedobjecttype(UserWarning): """raised when object type is not supported.""" pass class Invalidobjecttype(Error): """raised when object type not supported.""" pass class Invalidequation(Error): """raised when euqtion of a line is invalid.""" pass class Morpherror(Error): """raised when *coords array in async_morph is not the same size as the coords of the original shape.""" pass
# Date: 2020/11/12 # Author: Luis Marquez # Description: # This is a simple program in which the binary search will be implemented to calculate a square root result # #BINARY_SEARCH(): This function realize a binary search def binary_search(): #objective: The number in which the root will be calculated objective = int(input(f"\nType a number: ")) print(f"\n") #epilson: Margin of error epsilon = 0.01 #low: The lowest number of the current binary search range low = 0.0 #high: The highest number of the currente binary search range high = max(1.0, objective) #answer: answer = ((high + low)/(2)) #while: on this wile we will do a walk throught, cutting the numerical set in half while (abs(answer**2 - objective) >= (epsilon)): print(f"Low={round(low, 2)} \t high={round(high, 2)} \t Answer={round(answer, 2)}\n") if (answer**2 < objective): low = answer else: high = answer answer = ((high + low)/(2)) #printing the answer print(f"The square root of {objective} is {answer}") #RUN(): On this function the program run def run(): binary_search() #MAIN: Main function if __name__ == "__main__": run()
def binary_search(): objective = int(input(f'\nType a number: ')) print(f'\n') epsilon = 0.01 low = 0.0 high = max(1.0, objective) answer = (high + low) / 2 while abs(answer ** 2 - objective) >= epsilon: print(f'Low={round(low, 2)} \t high={round(high, 2)} \t Answer={round(answer, 2)}\n') if answer ** 2 < objective: low = answer else: high = answer answer = (high + low) / 2 print(f'The square root of {objective} is {answer}') def run(): binary_search() if __name__ == '__main__': run()
class Config(object): DESCRIPTION = 'Mock generator for c code' VERSION = '0.5' AUTHOR = 'Freddy Hurkmans' LICENSE = 'BSD 3-Clause' # set defaults for parameters verbose = False max_nr_function_calls = '25' charstar_is_input_string = False UNITY_INCLUDE = '#include "unity.h"' # CUSTOM_INCLUDES = ['#include "resource_detector.h"'] CUSTOM_INCLUDES = [] # List of all supported c types and the matching unity ASSERT macro's # If these types have different sizes on your system, you can simply # correct the macros. If you have missing types, you can simply add # your type/macro pairs CTYPE_TO_UNITY_ASSERT_MACRO = [ ['char', 'TEST_ASSERT_EQUAL_INT8_MESSAGE'], ['signed char', 'TEST_ASSERT_EQUAL_INT8_MESSAGE'], ['unsigned char', 'TEST_ASSERT_EQUAL_UINT8_MESSAGE'], ['short', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['short int', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['signed short', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['signed short int', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['unsigned short', 'TEST_ASSERT_EQUAL_UINT16_MESSAGE'], ['unsigned short int', 'TEST_ASSERT_EQUAL_UINT16_MESSAGE'], ['int', 'TEST_ASSERT_EQUAL_INT_MESSAGE'], ['signed int', 'TEST_ASSERT_EQUAL_INT_MESSAGE'], ['unsigned', 'TEST_ASSERT_EQUAL_UINT_MESSAGE'], ['unsigned int', 'TEST_ASSERT_EQUAL_UINT_MESSAGE'], ['long', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['long int', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['signed long', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['signed long int', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['unsigned long', 'TEST_ASSERT_EQUAL_UINT64_MESSAGE'], ['unsigned long int', 'TEST_ASSERT_EQUAL_UINT64_MESSAGE'], ['float', 'TEST_ASSERT_EQUAL_FLOAT_MESSAGE'], ['double', 'TEST_ASSERT_EQUAL_FLOAT_MESSAGE'], ['long double', 'TEST_ASSERT_EQUAL_FLOAT_MESSAGE'], ['int8_t', 'TEST_ASSERT_EQUAL_INT8_MESSAGE'], ['int16_t', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['int32_t', 'TEST_ASSERT_EQUAL_INT32_MESSAGE'], ['int64_t', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['uint8_t', 'TEST_ASSERT_EQUAL_UINT8_MESSAGE'], ['uint16_t', 'TEST_ASSERT_EQUAL_UINT16_MESSAGE'], ['uint32_t', 'TEST_ASSERT_EQUAL_UINT32_MESSAGE'], ['uint64_t', 'TEST_ASSERT_EQUAL_UINT64_MESSAGE'] ] CTAGS_EXECUTABLE = 'ctags'
class Config(object): description = 'Mock generator for c code' version = '0.5' author = 'Freddy Hurkmans' license = 'BSD 3-Clause' verbose = False max_nr_function_calls = '25' charstar_is_input_string = False unity_include = '#include "unity.h"' custom_includes = [] ctype_to_unity_assert_macro = [['char', 'TEST_ASSERT_EQUAL_INT8_MESSAGE'], ['signed char', 'TEST_ASSERT_EQUAL_INT8_MESSAGE'], ['unsigned char', 'TEST_ASSERT_EQUAL_UINT8_MESSAGE'], ['short', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['short int', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['signed short', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['signed short int', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['unsigned short', 'TEST_ASSERT_EQUAL_UINT16_MESSAGE'], ['unsigned short int', 'TEST_ASSERT_EQUAL_UINT16_MESSAGE'], ['int', 'TEST_ASSERT_EQUAL_INT_MESSAGE'], ['signed int', 'TEST_ASSERT_EQUAL_INT_MESSAGE'], ['unsigned', 'TEST_ASSERT_EQUAL_UINT_MESSAGE'], ['unsigned int', 'TEST_ASSERT_EQUAL_UINT_MESSAGE'], ['long', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['long int', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['signed long', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['signed long int', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['unsigned long', 'TEST_ASSERT_EQUAL_UINT64_MESSAGE'], ['unsigned long int', 'TEST_ASSERT_EQUAL_UINT64_MESSAGE'], ['float', 'TEST_ASSERT_EQUAL_FLOAT_MESSAGE'], ['double', 'TEST_ASSERT_EQUAL_FLOAT_MESSAGE'], ['long double', 'TEST_ASSERT_EQUAL_FLOAT_MESSAGE'], ['int8_t', 'TEST_ASSERT_EQUAL_INT8_MESSAGE'], ['int16_t', 'TEST_ASSERT_EQUAL_INT16_MESSAGE'], ['int32_t', 'TEST_ASSERT_EQUAL_INT32_MESSAGE'], ['int64_t', 'TEST_ASSERT_EQUAL_INT64_MESSAGE'], ['uint8_t', 'TEST_ASSERT_EQUAL_UINT8_MESSAGE'], ['uint16_t', 'TEST_ASSERT_EQUAL_UINT16_MESSAGE'], ['uint32_t', 'TEST_ASSERT_EQUAL_UINT32_MESSAGE'], ['uint64_t', 'TEST_ASSERT_EQUAL_UINT64_MESSAGE']] ctags_executable = 'ctags'
left_eye_connection = [ # Left eye. (263, 249), (249, 390), (390, 373), (373, 374), (374, 380), (380, 381), (381, 382), (382, 362), (263, 466), (466, 388), (388, 387), (387, 386), (386, 385), (385, 384), (384, 398), (398, 362) ] left_eyebrow_connection = [ # Left eyebrow. (276, 283), (283, 282), (282, 295), (295, 285), (300, 293), (293, 334), (334, 296), (296, 336) ] right_eye_connection = [ # Right eye. (33, 7), (7, 163), (163, 144), (144, 145), (145, 153), (153, 154), (154, 155), (155, 133), (33, 246), (246, 161), (161, 160), (160, 159), (159, 158), (158, 157), (157, 173), (173, 133) ] right_eyebrow_connection = [ # Right eyebrow. (46, 53), (53, 52), (52, 65), (65, 55), (70, 63), (63, 105), (105, 66), (66, 107) ] all_eye_connection = frozenset(left_eye_connection + right_eye_connection) face_features = { 'silhouette': [ 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109 ], 'lipsUpperOuter': [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291], 'lipsLowerOuter': [146, 91, 181, 84, 17, 314, 405, 321, 375, 291], 'lipsUpperInner': [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308], 'lipsLowerInner': [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308], 'rightEyeUpper0': [246, 161, 160, 159, 158, 157, 173], 'rightEyeLower0': [33, 7, 163, 144, 145, 153, 154, 155, 133], 'rightEyeUpper1': [247, 30, 29, 27, 28, 56, 190], 'rightEyeLower1': [130, 25, 110, 24, 23, 22, 26, 112, 243], 'rightEyeUpper2': [113, 225, 224, 223, 222, 221, 189], 'rightEyeLower2': [226, 31, 228, 229, 230, 231, 232, 233, 244], 'rightEyeLower3': [143, 111, 117, 118, 119, 120, 121, 128, 245], 'rightEyebrowUpper': [156, 70, 63, 105, 66, 107, 55, 193], 'rightEyebrowLower': [35, 124, 46, 53, 52, 65], 'leftEyeUpper0': [466, 388, 387, 386, 385, 384, 398], 'leftEyeLower0': [263, 249, 390, 373, 374, 380, 381, 382, 362], 'leftEyeUpper1': [467, 260, 259, 257, 258, 286, 414], 'leftEyeLower1': [359, 255, 339, 254, 253, 252, 256, 341, 463], 'leftEyeUpper2': [342, 445, 444, 443, 442, 441, 413], 'leftEyeLower2': [446, 261, 448, 449, 450, 451, 452, 453, 464], 'leftEyeLower3': [372, 340, 346, 347, 348, 349, 350, 357, 465], 'leftEyebrowUpper': [383, 300, 293, 334, 296, 336, 285, 417], 'leftEyebrowLower': [265, 353, 276, 283, 282, 295], 'midwayBetweenEyes': [168], 'noseTip': [1], 'noseBottom': [2], 'noseRightCorner': [98], 'noseLeftCorner': [327], 'rightCheek': [205], 'leftCheek': [425] }
left_eye_connection = [(263, 249), (249, 390), (390, 373), (373, 374), (374, 380), (380, 381), (381, 382), (382, 362), (263, 466), (466, 388), (388, 387), (387, 386), (386, 385), (385, 384), (384, 398), (398, 362)] left_eyebrow_connection = [(276, 283), (283, 282), (282, 295), (295, 285), (300, 293), (293, 334), (334, 296), (296, 336)] right_eye_connection = [(33, 7), (7, 163), (163, 144), (144, 145), (145, 153), (153, 154), (154, 155), (155, 133), (33, 246), (246, 161), (161, 160), (160, 159), (159, 158), (158, 157), (157, 173), (173, 133)] right_eyebrow_connection = [(46, 53), (53, 52), (52, 65), (65, 55), (70, 63), (63, 105), (105, 66), (66, 107)] all_eye_connection = frozenset(left_eye_connection + right_eye_connection) face_features = {'silhouette': [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109], 'lipsUpperOuter': [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291], 'lipsLowerOuter': [146, 91, 181, 84, 17, 314, 405, 321, 375, 291], 'lipsUpperInner': [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308], 'lipsLowerInner': [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308], 'rightEyeUpper0': [246, 161, 160, 159, 158, 157, 173], 'rightEyeLower0': [33, 7, 163, 144, 145, 153, 154, 155, 133], 'rightEyeUpper1': [247, 30, 29, 27, 28, 56, 190], 'rightEyeLower1': [130, 25, 110, 24, 23, 22, 26, 112, 243], 'rightEyeUpper2': [113, 225, 224, 223, 222, 221, 189], 'rightEyeLower2': [226, 31, 228, 229, 230, 231, 232, 233, 244], 'rightEyeLower3': [143, 111, 117, 118, 119, 120, 121, 128, 245], 'rightEyebrowUpper': [156, 70, 63, 105, 66, 107, 55, 193], 'rightEyebrowLower': [35, 124, 46, 53, 52, 65], 'leftEyeUpper0': [466, 388, 387, 386, 385, 384, 398], 'leftEyeLower0': [263, 249, 390, 373, 374, 380, 381, 382, 362], 'leftEyeUpper1': [467, 260, 259, 257, 258, 286, 414], 'leftEyeLower1': [359, 255, 339, 254, 253, 252, 256, 341, 463], 'leftEyeUpper2': [342, 445, 444, 443, 442, 441, 413], 'leftEyeLower2': [446, 261, 448, 449, 450, 451, 452, 453, 464], 'leftEyeLower3': [372, 340, 346, 347, 348, 349, 350, 357, 465], 'leftEyebrowUpper': [383, 300, 293, 334, 296, 336, 285, 417], 'leftEyebrowLower': [265, 353, 276, 283, 282, 295], 'midwayBetweenEyes': [168], 'noseTip': [1], 'noseBottom': [2], 'noseRightCorner': [98], 'noseLeftCorner': [327], 'rightCheek': [205], 'leftCheek': [425]}
# -------------------------------------------------------- # GA3C for Dragon # Copyright(c) 2017 SeetaTech # Written by Ting Pan # -------------------------------------------------------- class Config(object): ######################################################################### # Game configuration # Name of the game, with version (e.g. PongDeterministic-v0) ATARI_GAME = 'PongDeterministic-v0' # Enable to see the trained agent in action PLAY_MODE = False # Enable to train TRAIN_MODELS = True # Load old models. Throws if the model doesn't exist LOAD_CHECKPOINT = False # If 0, the latest checkpoint is loaded LOAD_EPISODE = 32000 ######################################################################### # Number of agents, predictors, trainers and other system settings # If the dynamic configuration is on, these are the initial values. # Number of Agents AGENTS = 32 # Number of Predictors PREDICTORS = 2 # Number of Trainers TRAINERS = 2 # Device DEVICE = 'gpu:0' # Enable the dynamic adjustment (+ waiting time to start it) DYNAMIC_SETTINGS = True DYNAMIC_SETTINGS_STEP_WAIT = 20 DYNAMIC_SETTINGS_INITIAL_WAIT = 10 ######################################################################### # Algorithm parameters # Discount factor DISCOUNT = 0.99 # Tmax TIME_MAX = 5 # Reward Clipping REWARD_MIN = -1 REWARD_MAX = 1 # Max size of the queue MAX_QUEUE_SIZE = 100 PREDICTION_BATCH_SIZE = 128 # Input of the DNN STACKED_FRAMES = 4 IMAGE_WIDTH = 84 IMAGE_HEIGHT = 84 # Total number of episodes and annealing frequency EPISODES = 400000 ANNEALING_EPISODE_COUNT = 400000 # Entropy regualrization hyper-parameter BETA_START = 0.01 BETA_END = 0.01 # Learning rate LEARNING_RATE_START = 0.0003 LEARNING_RATE_END = 0.0003 # RMSProp parameters RMSPROP_DECAY = 0.99 RMSPROP_MOMENTUM = 0.0 RMSPROP_EPSILON = 0.1 # Dual RMSProp - we found that using a single RMSProp for the two cost function works better and faster DUAL_RMSPROP = False # Gradient clipping USE_GRAD_CLIP = True GRAD_CLIP_NORM = 40.0 # Epsilon (regularize policy lag in GA3C) LOG_EPSILON = 1e-6 # Training min batch size - increasing the batch size increases the stability of the algorithm, but make learning slower TRAINING_MIN_BATCH_SIZE = 0 ######################################################################### # Log and save # Enable TensorBoard TENSORBOARD = False # Update TensorBoard every X training steps TENSORBOARD_UPDATE_FREQUENCY = 1000 # Enable to save models every SAVE_FREQUENCY episodes SAVE_MODELS = True # Save every SAVE_FREQUENCY episodes SAVE_FREQUENCY = 2000 # Print stats every PRINT_STATS_FREQUENCY episodes PRINT_STATS_FREQUENCY = 1 # The window to average stats STAT_ROLLING_MEAN_WINDOW = 1000 # Results filename RESULTS_FILENAME = 'results.txt' # Network checkpoint name NETWORK_NAME = 'network' ######################################################################### # More experimental parameters here # Minimum policy MIN_POLICY = 0.0 # Use log_softmax() instead of log(softmax()) USE_LOG_SOFTMAX = False
class Config(object): atari_game = 'PongDeterministic-v0' play_mode = False train_models = True load_checkpoint = False load_episode = 32000 agents = 32 predictors = 2 trainers = 2 device = 'gpu:0' dynamic_settings = True dynamic_settings_step_wait = 20 dynamic_settings_initial_wait = 10 discount = 0.99 time_max = 5 reward_min = -1 reward_max = 1 max_queue_size = 100 prediction_batch_size = 128 stacked_frames = 4 image_width = 84 image_height = 84 episodes = 400000 annealing_episode_count = 400000 beta_start = 0.01 beta_end = 0.01 learning_rate_start = 0.0003 learning_rate_end = 0.0003 rmsprop_decay = 0.99 rmsprop_momentum = 0.0 rmsprop_epsilon = 0.1 dual_rmsprop = False use_grad_clip = True grad_clip_norm = 40.0 log_epsilon = 1e-06 training_min_batch_size = 0 tensorboard = False tensorboard_update_frequency = 1000 save_models = True save_frequency = 2000 print_stats_frequency = 1 stat_rolling_mean_window = 1000 results_filename = 'results.txt' network_name = 'network' min_policy = 0.0 use_log_softmax = False
INPUT_BUCKET = 'input-image-files' OUTPUT_BUCKET = 'output-image-files' INPUT_QUEUE = 'https://sqs.us-east-1.amazonaws.com/378107157540/Request-Queue' OUTPUT_QUEUE = 'https://sqs.us-east-1.amazonaws.com/378107157540/Response-Queue'
input_bucket = 'input-image-files' output_bucket = 'output-image-files' input_queue = 'https://sqs.us-east-1.amazonaws.com/378107157540/Request-Queue' output_queue = 'https://sqs.us-east-1.amazonaws.com/378107157540/Response-Queue'
f='11' for i in range(5): c=1 s='' for j in range(len(f)-1): if f[j]==f[j+1]: c+=1 else: s=(str(c)+(f[j])) s=str(c)+(f[j]) f=str(s) print(f)
f = '11' for i in range(5): c = 1 s = '' for j in range(len(f) - 1): if f[j] == f[j + 1]: c += 1 else: s = str(c) + f[j] s = str(c) + f[j] f = str(s) print(f)
"""API routes""" ROUTE_CVE_ANNOUNCEMENTS = "/api/v3/cve_announcements" ROUTE_GROUPS = "/api/v3/groups" ROUTE_HOSTS = "/api/v3/hosts" ROUTE_NODES = "/api/v3/nodes" ROUTE_PING = "/api/v3/ping" ROUTE_REMOTE_ACCESSES = "/api/v3/remote_accesses" ROUTE_SECURITY_ISSUES = "/api/v3/security_issues" ROUTE_SERVERS = "/api/v3/servers" ROUTE_USERS = "/api/v3/users"
"""API routes""" route_cve_announcements = '/api/v3/cve_announcements' route_groups = '/api/v3/groups' route_hosts = '/api/v3/hosts' route_nodes = '/api/v3/nodes' route_ping = '/api/v3/ping' route_remote_accesses = '/api/v3/remote_accesses' route_security_issues = '/api/v3/security_issues' route_servers = '/api/v3/servers' route_users = '/api/v3/users'
#!/usr/bin/env python # -*- coding: utf-8 -*- class ComposeModeException(Exception): """ Base exception for compose-mode """ class ComposeModeYmlNotFound(ComposeModeException): """ Exception raised when no configuration file was found """ def main(): pass if __name__ == '__main__': main()
class Composemodeexception(Exception): """ Base exception for compose-mode """ class Composemodeymlnotfound(ComposeModeException): """ Exception raised when no configuration file was found """ def main(): pass if __name__ == '__main__': main()
query = """ type Query { photo(photoId: ID!): Photo! photos(page: Int, profileId: ID, photosPerPage: Int): PhotoPagination! profile(profileId: ID!): Profile! profiles(page: Int, perPage: Int): ProfilePagination! identifyFace(faceId: ID!): [IdentifyFaceResult]! task(taskCollectionId: ID!): Task tasks: [Task] } """
query = '\ntype Query {\n photo(photoId: ID!): Photo!\n photos(page: Int, profileId: ID, photosPerPage: Int): PhotoPagination!\n profile(profileId: ID!): Profile!\n profiles(page: Int, perPage: Int): ProfilePagination!\n identifyFace(faceId: ID!): [IdentifyFaceResult]!\n task(taskCollectionId: ID!): Task\n tasks: [Task]\n}\n'
a=input("ENTER THE NUMBER\n") if a[0]==a[1] or a[0]==a[2] or a[0]==a[3] or a[0]==a[4] or a[1]==a[2] or a[1]==a[3] or a[1]==a[4] or a[2]==a[3] or a[2]==a[4]: print("THE ENTERED NUMBER IS NOT A UNIQUE NUMBER") else: print(a,"IS AN UNIQUE NUMBER")
a = input('ENTER THE NUMBER\n') if a[0] == a[1] or a[0] == a[2] or a[0] == a[3] or (a[0] == a[4]) or (a[1] == a[2]) or (a[1] == a[3]) or (a[1] == a[4]) or (a[2] == a[3]) or (a[2] == a[4]): print('THE ENTERED NUMBER IS NOT A UNIQUE NUMBER') else: print(a, 'IS AN UNIQUE NUMBER')
def isPrime(n: int)->bool: """ Give an Integer 'n'. Check if 'n' is Prime or Not :param n: :return: bool - True or False A no. is prime if it is divisible only by 1 & itself. 1- is neither Prime nor Composite - check for n being a even number i.e divisble by 2 - check for n being divisible by 3 - then create a range of i following series, 5,7,11,13,17,19,23,.... till sqrt(n) with step as +6 - check for divisibility of n with each value of i & i+2 """ if n== 1: return False # handle boundary conditions if n == 2 or n==3: return True # Now check for divisibility of n by 2 & 3 if n % 2 ==0 or n % 3 ==0: return False i = 5 while (i*i <= n): if n%i ==0 or n%(i+2) ==0: return False i = i+ 6 return True #Driver Code if __name__ == '__main__': n = 24971 returned = isPrime(n) print(returned)
def is_prime(n: int) -> bool: """ Give an Integer 'n'. Check if 'n' is Prime or Not :param n: :return: bool - True or False A no. is prime if it is divisible only by 1 & itself. 1- is neither Prime nor Composite - check for n being a even number i.e divisble by 2 - check for n being divisible by 3 - then create a range of i following series, 5,7,11,13,17,19,23,.... till sqrt(n) with step as +6 - check for divisibility of n with each value of i & i+2 """ if n == 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i = i + 6 return True if __name__ == '__main__': n = 24971 returned = is_prime(n) print(returned)
# The goal of this exercise is to get hands-on experience working with # list comprehensions, and other comprehensions. Write a complementary # function to each of the below, which accomplishes the same logic in # a one-liner (using list/set/dict comprehensions). # Exercise 1 # Adds 5 to each element def add_five(numbers): out = [] for num in numbers: out.append(num + 5) return out # TODO Complete this function def add_five_one_liner(numbers): pass # Exercise 2 # Drops any small numbers (strictly less than 4) def drop_small(numbers): out = [] for num in numbers: if not num < 4: out.append(num) return out # TODO Complete this function def drop_small_one_liner(numbers): pass # Exercise 3 # Returns a *set* of all distinct numbers (i.e. no repeats) def get_distinct(numbers): out = set() for num in numbers: out.add(num) return out # TODO Complete this function def get_distinct_one_liner(numbers): pass ## Helper testing functions, for your convienence ## def test_add_five(numbers): out1 = add_five(numbers) out2 = add_five_one_liner(numbers) assert(out1 == out2) def test_drop_small(numbers): out1 = drop_small(numbers) out2 = drop_small_one_liner(numbers) assert(out1 == out2) def test_get_distinct(numbers): out1 = get_distinct(numbers) out2 = get_distinct_one_liner(numbers) assert(out1 == out2) # Main method def main(): # Feel free to add anything you need to test your solutions here pass if __name__ == "__main__": main()
def add_five(numbers): out = [] for num in numbers: out.append(num + 5) return out def add_five_one_liner(numbers): pass def drop_small(numbers): out = [] for num in numbers: if not num < 4: out.append(num) return out def drop_small_one_liner(numbers): pass def get_distinct(numbers): out = set() for num in numbers: out.add(num) return out def get_distinct_one_liner(numbers): pass def test_add_five(numbers): out1 = add_five(numbers) out2 = add_five_one_liner(numbers) assert out1 == out2 def test_drop_small(numbers): out1 = drop_small(numbers) out2 = drop_small_one_liner(numbers) assert out1 == out2 def test_get_distinct(numbers): out1 = get_distinct(numbers) out2 = get_distinct_one_liner(numbers) assert out1 == out2 def main(): pass if __name__ == '__main__': main()
n = len(x) if n % 2: median_ = sorted(x)[round(0.5*(n-1))] else: x_ord, index = sorted(x), round(0.5 * n) median_ = 0.5 * (x_ord[index-1] + x_ord[index]) median_
n = len(x) if n % 2: median_ = sorted(x)[round(0.5 * (n - 1))] else: (x_ord, index) = (sorted(x), round(0.5 * n)) median_ = 0.5 * (x_ord[index - 1] + x_ord[index]) median_
def agreeanswer(): i01.disableRobotRandom(30) i01.setHandSpeed("left", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0) i01.setHeadSpeed(1.0, 0.90) i01.setTorsoSpeed(1.0, 1.0, 1.0) i01.moveHead(120,90) sleep(0.5) i01.moveHead(20,90) sleep(0.5) i01.moveArm("left",20,93,42,16) i01.moveArm("right",20,93,37,18) i01.moveHand("left",180,180,65,81,41,143) i01.moveHand("right",180,180,18,61,36,21) i01.moveTorso(90,90,90) sleep(0.5) i01.moveHead(90,90) sleep(0.2) relax()
def agreeanswer(): i01.disableRobotRandom(30) i01.setHandSpeed('left', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) i01.setHandSpeed('right', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed('left', 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed('right', 1.0, 1.0, 1.0, 1.0) i01.setHeadSpeed(1.0, 0.9) i01.setTorsoSpeed(1.0, 1.0, 1.0) i01.moveHead(120, 90) sleep(0.5) i01.moveHead(20, 90) sleep(0.5) i01.moveArm('left', 20, 93, 42, 16) i01.moveArm('right', 20, 93, 37, 18) i01.moveHand('left', 180, 180, 65, 81, 41, 143) i01.moveHand('right', 180, 180, 18, 61, 36, 21) i01.moveTorso(90, 90, 90) sleep(0.5) i01.moveHead(90, 90) sleep(0.2) relax()
# GENERAL TREE STRUCTURE SETUP # Santiago Garcia Arango, July 2020 """ The goal is to create a tree structure to organize better the information. The final result should be able to create a tree and print it like this: (from the "root", be able to go deep in a tree structure) UNIVERITY (level 0) |__MANAGEMENT (level 1) | |__BUSSINESS (level 2) | |__ECONOMICS | |__RISKS |__MECHATRONICS | |__ROBOTICS | |__CONTROL | |__ELECTRONICS |__MECHANICS | |__THERMODYNAMICS | |__MECHANISMS | |__WELDING |__BIOMEDICS | |__SIGNALS | |__BIOMATERIALS | |__BIOLOGY """ class TreeNode: """ --------TREENODE HELP-------- This is the general node for building any tree general structure. :param data: any information, data or object to be stored. """ def __init__(self, data): self.data = data self.children = [] self.parent = None def add_child(self, child): # Before adding the "child" to the tree, we give it the instance... # ... of the main parent (which is the upper TreeNode class) child.parent = self self.children.append(child) def get_level(self): # The idea of this method is to be able to se de "depth" of this... # ... specific node in the tree, to use it the print_tree() method level = 0 current_parent = self.parent while current_parent != None: # Add levels by recursive accessing each parent (until None) level += 1 current_parent = current_parent.parent return level def print_tree(self, levels_to_show=5): # Extra printing setup for organizing visual tree setup = " |" * self.get_level() + "__" # Access the information of this specific TreeNode print(setup + self.data) if len(self.children) > 0: # For each child, do a recursive approach of <print_tree> method for c in self.children: # Extra condition to only show levels given by the user if self.get_level() < levels_to_show: c.print_tree(levels_to_show) # Tests are in < test_general_tree.py >
""" The goal is to create a tree structure to organize better the information. The final result should be able to create a tree and print it like this: (from the "root", be able to go deep in a tree structure) UNIVERITY (level 0) |__MANAGEMENT (level 1) | |__BUSSINESS (level 2) | |__ECONOMICS | |__RISKS |__MECHATRONICS | |__ROBOTICS | |__CONTROL | |__ELECTRONICS |__MECHANICS | |__THERMODYNAMICS | |__MECHANISMS | |__WELDING |__BIOMEDICS | |__SIGNALS | |__BIOMATERIALS | |__BIOLOGY """ class Treenode: """ --------TREENODE HELP-------- This is the general node for building any tree general structure. :param data: any information, data or object to be stored. """ def __init__(self, data): self.data = data self.children = [] self.parent = None def add_child(self, child): child.parent = self self.children.append(child) def get_level(self): level = 0 current_parent = self.parent while current_parent != None: level += 1 current_parent = current_parent.parent return level def print_tree(self, levels_to_show=5): setup = ' |' * self.get_level() + '__' print(setup + self.data) if len(self.children) > 0: for c in self.children: if self.get_level() < levels_to_show: c.print_tree(levels_to_show)
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l1node = l1 l2node = l2 prenode = None r = 0 flag = 0 while l1node is not None or l2node is not None: if l1node is None: l2node.val += r r = l2node.val // 10 l2node.val %= 10 prenode = l2node l2node = l2node.next flag = 1 elif l2node is None: l1node.val += r r = l1node.val // 10 l1node.val %= 10 prenode = l1node l1node = l1node.next flag = 2 else: l1node.val += (l2node.val + r) r = l1node.val // 10 l1node.val %= 10 l2node.val = l1node.val prenode = l1node l1node = l1node.next l2node = l2node.next if r > 0: node = ListNode(r) prenode.next = node return l2 if flag == 1 else l1 if __name__ == "__main__": solution = Solution() node1 = ListNode(2) node1.next = ListNode(4) node1.next.next = ListNode(3) node2 = ListNode(5) node2.next = ListNode(6) node2.next.next = ListNode(4) print(solution.addTwoNumbers(node1, node2).val) node1.next = ListNode(1) print(solution.addTwoNumbers(node1, node2))
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def add_two_numbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l1node = l1 l2node = l2 prenode = None r = 0 flag = 0 while l1node is not None or l2node is not None: if l1node is None: l2node.val += r r = l2node.val // 10 l2node.val %= 10 prenode = l2node l2node = l2node.next flag = 1 elif l2node is None: l1node.val += r r = l1node.val // 10 l1node.val %= 10 prenode = l1node l1node = l1node.next flag = 2 else: l1node.val += l2node.val + r r = l1node.val // 10 l1node.val %= 10 l2node.val = l1node.val prenode = l1node l1node = l1node.next l2node = l2node.next if r > 0: node = list_node(r) prenode.next = node return l2 if flag == 1 else l1 if __name__ == '__main__': solution = solution() node1 = list_node(2) node1.next = list_node(4) node1.next.next = list_node(3) node2 = list_node(5) node2.next = list_node(6) node2.next.next = list_node(4) print(solution.addTwoNumbers(node1, node2).val) node1.next = list_node(1) print(solution.addTwoNumbers(node1, node2))
def linear_search(arr, value): """ My Python implementation of linear search Searches an array and returns either the index of the value (if found) or -1 (if not found) Time complexity: O(n) Space complexity: O(1) """ for i in range(len(arr)): # O(n) if arr[i] == value: return i return -1
def linear_search(arr, value): """ My Python implementation of linear search Searches an array and returns either the index of the value (if found) or -1 (if not found) Time complexity: O(n) Space complexity: O(1) """ for i in range(len(arr)): if arr[i] == value: return i return -1
# Filename: route.py """ Transit Route Module """ # Standard libraries class Route(object): """ A representation of a route. Every route has: * name - string * id - unique identification (string) for the route for the agency * stops - list of stops relevant for the route """ def __init__(self, name, uid): """ Constructor :param uid: string - unique identification of a route """ self.name = str(name) self.uid = str(uid) self.stops = list()
""" Transit Route Module """ class Route(object): """ A representation of a route. Every route has: * name - string * id - unique identification (string) for the route for the agency * stops - list of stops relevant for the route """ def __init__(self, name, uid): """ Constructor :param uid: string - unique identification of a route """ self.name = str(name) self.uid = str(uid) self.stops = list()
database_path = "{projects}/brewmaster/server/data/" heater_port = 12 port_number = 5000 stirrer_port = 13 temp_sensor_path = "/sys/bus/w1/devices/{your_sensor_id}/w1_slave" use_fake = True
database_path = '{projects}/brewmaster/server/data/' heater_port = 12 port_number = 5000 stirrer_port = 13 temp_sensor_path = '/sys/bus/w1/devices/{your_sensor_id}/w1_slave' use_fake = True
# def favcolors(mameet,qj,mustafa): # print(mameet, qj,mustafa) # favcolors(qj='green',mameet='black',mustafa='blue') # # ,, def favcolors(**kwargs): print(kwargs) for key,val in kwargs.items(): print('Favourite color of',key,'is',val) # favcolors(qj='green',mameet='black',mustafa='blue',fatima='orange',taher='yellow') # Both * and ** # ordering def favcolors2(num1,*args,qj,**kwargs): print('num1:',num1) print('args:',args) print('def arguments:',qj) print('kwargs:',kwargs) # for key,val in kwargs.items(): # print('Favourite color of',key,'is',val) favcolors2(10,20,'aaaa',qj='green',mameet='black',mustafa='blue',fatima='orange',taher='yellow')
def favcolors(**kwargs): print(kwargs) for (key, val) in kwargs.items(): print('Favourite color of', key, 'is', val) def favcolors2(num1, *args, qj, **kwargs): print('num1:', num1) print('args:', args) print('def arguments:', qj) print('kwargs:', kwargs) favcolors2(10, 20, 'aaaa', qj='green', mameet='black', mustafa='blue', fatima='orange', taher='yellow')
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date # Formatting for date objects. DATE_FORMAT = 'N j, Y' # Formatting for time objects. TIME_FORMAT = 'P' # Formatting for datetime objects. DATETIME_FORMAT = 'N j, Y, P' # Formatting for date objects when only the year and month are relevant. YEAR_MONTH_FORMAT = 'F Y' # Formatting for date objects when only the month and day are relevant. MONTH_DAY_FORMAT = 'F j' # Short formatting for date objects. SHORT_DATE_FORMAT = 'm/d/Y' # Short formatting for datetime objects. SHORT_DATETIME_FORMAT = 'm/d/Y P' # First day of week, to be used on calendars. # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK = 0 # Formats to be used when parsing dates from input boxes, in order. # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior # Note that these format strings are different from the ones to display dates. # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y', # '10/25/06' '%b %d %Y', # 'Oct 25 2006' '%b %d, %Y', # 'Oct 25, 2006' '%d %b %Y', # '25 Oct 2006' '%d %b, %Y', # '25 Oct, 2006' '%B %d %Y', # 'October 25 2006' '%B %d, %Y', # 'October 25, 2006' '%d %B %Y', # '25 October 2006' '%d %B, %Y', # '25 October, 2006' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' ] TIME_INPUT_FORMATS = [ '%H:%M:%S', # '14:30:59' '%H:%M:%S.%f', # '14:30:59.000200' '%H:%M', # '14:30' ] # Decimal separator symbol. DECIMAL_SEPARATOR = '.' # Thousand separator symbol. THOUSAND_SEPARATOR = ',' # Number of digits that will be together, when splitting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands. NUMBER_GROUPING = 3
date_format = 'N j, Y' time_format = 'P' datetime_format = 'N j, Y, P' year_month_format = 'F Y' month_day_format = 'F j' short_date_format = 'm/d/Y' short_datetime_format = 'm/d/Y P' first_day_of_week = 0 date_input_formats = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y'] datetime_input_formats = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M'] time_input_formats = ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'] decimal_separator = '.' thousand_separator = ',' number_grouping = 3
ENTRY_POINT = 'minSubArraySum' #[PROMPT] def minSubArraySum(nums): """ Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum([2, 3, 4, 1, 2, 4]) == 1 minSubArraySum([-1, -2, -3]) == -6 """ #[SOLUTION] max_sum = 0 s = 0 for num in nums: s += -num if (s < 0): s = 0 max_sum = max(s, max_sum) if max_sum == 0: max_sum = max(-i for i in nums) min_sum = -max_sum return min_sum #[CHECK] def check(candidate): # Check some simple cases assert candidate([2, 3, 4, 1, 2, 4]) == 1, "This prints if this assert fails 1 (good for debugging!)" assert candidate([-1, -2, -3]) == -6 assert candidate([-1, -2, -3, 2, -10]) == -14 assert candidate([-9999999999999999]) == -9999999999999999 assert candidate([0, 10, 20, 1000000]) == 0 assert candidate([-1, -2, -3, 10, -5]) == -6 assert candidate([100, -1, -2, -3, 10, -5]) == -6 assert candidate([10, 11, 13, 8, 3, 4]) == 3 assert candidate([100, -33, 32, -1, 0, -2]) == -33 # Check some edge cases that are easy to work out by hand. assert candidate([-10]) == -10, "This prints if this assert fails 2 (also good for debugging!)" assert candidate([7]) == 7 assert candidate([1, -1]) == -1
entry_point = 'minSubArraySum' def min_sub_array_sum(nums): """ Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum([2, 3, 4, 1, 2, 4]) == 1 minSubArraySum([-1, -2, -3]) == -6 """ max_sum = 0 s = 0 for num in nums: s += -num if s < 0: s = 0 max_sum = max(s, max_sum) if max_sum == 0: max_sum = max((-i for i in nums)) min_sum = -max_sum return min_sum def check(candidate): assert candidate([2, 3, 4, 1, 2, 4]) == 1, 'This prints if this assert fails 1 (good for debugging!)' assert candidate([-1, -2, -3]) == -6 assert candidate([-1, -2, -3, 2, -10]) == -14 assert candidate([-9999999999999999]) == -9999999999999999 assert candidate([0, 10, 20, 1000000]) == 0 assert candidate([-1, -2, -3, 10, -5]) == -6 assert candidate([100, -1, -2, -3, 10, -5]) == -6 assert candidate([10, 11, 13, 8, 3, 4]) == 3 assert candidate([100, -33, 32, -1, 0, -2]) == -33 assert candidate([-10]) == -10, 'This prints if this assert fails 2 (also good for debugging!)' assert candidate([7]) == 7 assert candidate([1, -1]) == -1
number_of_rooms = int(input()) free_chairs = 0 insufficiency = False for i in range(1, number_of_rooms + 1): list_of_chairs_and_people = input().split() chairs = len(list_of_chairs_and_people[0]) needed_ones = int(list_of_chairs_and_people[1]) if chairs >= needed_ones: free_chairs += chairs - needed_ones else: insufficiency = True print(f"{needed_ones-chairs} more chairs needed in room {i}") if not insufficiency: print(f"Game On, {free_chairs} free chairs left")
number_of_rooms = int(input()) free_chairs = 0 insufficiency = False for i in range(1, number_of_rooms + 1): list_of_chairs_and_people = input().split() chairs = len(list_of_chairs_and_people[0]) needed_ones = int(list_of_chairs_and_people[1]) if chairs >= needed_ones: free_chairs += chairs - needed_ones else: insufficiency = True print(f'{needed_ones - chairs} more chairs needed in room {i}') if not insufficiency: print(f'Game On, {free_chairs} free chairs left')
def funcion(): return 5 def generador(): yield 1,2,3,4,5,6,7,8,9 print(generador()) print(generador()) print(generador())
def funcion(): return 5 def generador(): yield (1, 2, 3, 4, 5, 6, 7, 8, 9) print(generador()) print(generador()) print(generador())
# vim: set ts=8 sts=4 sw=4 tw=99 et: # # This file is part of AMBuild. # # AMBuild is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # AMBuild is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with AMBuild. If not, see <http://www.gnu.org/licenses/>. class BaseGenerator(object): def __init__(self, cm): self.cm = cm @property def backend(self): raise Exception('Must be implemented!') def addSymlink(self, context, source, output_path): raise Exception('Must be implemented!') def addFolder(self, context, folder): raise Exception('Must be implemented!') def addCopy(self, context, source, output_path): raise Exception('Must be implemented!') def addShellCommand(self, context, inputs, argv, outputs, folder = -1, dep_type = None, weak_inputs = [], shared_outputs = [], env_data = None): raise Exception('Must be implemented!') def addConfigureFile(self, context, path): raise Exception('Must be implemented!') # The following methods are only needed to implement v2.2 generators. def newProgramProject(self, context, name): raise NotImplementedError() def newLibraryProject(self, context, name): raise NotImplementedError() def newStaticLibraryProject(self, context, name): raise NotImplementedError()
class Basegenerator(object): def __init__(self, cm): self.cm = cm @property def backend(self): raise exception('Must be implemented!') def add_symlink(self, context, source, output_path): raise exception('Must be implemented!') def add_folder(self, context, folder): raise exception('Must be implemented!') def add_copy(self, context, source, output_path): raise exception('Must be implemented!') def add_shell_command(self, context, inputs, argv, outputs, folder=-1, dep_type=None, weak_inputs=[], shared_outputs=[], env_data=None): raise exception('Must be implemented!') def add_configure_file(self, context, path): raise exception('Must be implemented!') def new_program_project(self, context, name): raise not_implemented_error() def new_library_project(self, context, name): raise not_implemented_error() def new_static_library_project(self, context, name): raise not_implemented_error()
# Copyright 2020 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. def one_level_function(): # dummy comment # to take up # three lines return 0 def multiline_args_tuple( a, b, c ): # dummy comment # to take up # three lines return 0 def nested_if_statements(): if True: if True: # dummy comment # to take up # three lines return 0 def nested_for_statements(): for x in range(1): for y in range(1): # dummy comment # to take up # three lines return 0 def nested_with_statements(): with open(__file__, 'r') as _: # dummy comment to take up a line return 0 def ending_tuple(): return ( # dummy comment # to take up # three lines 1, 2, 3 ) def ending_dict(): return { # dummy comment # to take up # three lines 'a': 1, 'b': 2, 'c': 3 } def ending_array(): return [ # dummy comment # to take up # three lines 1, 2, 3 ] def ending_list_comp(): return [x for x # dummy comment # to take up # three lines in range(2)] def ending_if_else(): if 1 == 2: return True else: # dummy comment # to take up # three lines return False def ending_if_elif(): if 1 == 2: return True elif True: # dummy comment # to take up # three lines return False def one_line_if(): return 1 if True else 2
def one_level_function(): return 0 def multiline_args_tuple(a, b, c): return 0 def nested_if_statements(): if True: if True: return 0 def nested_for_statements(): for x in range(1): for y in range(1): return 0 def nested_with_statements(): with open(__file__, 'r') as _: return 0 def ending_tuple(): return (1, 2, 3) def ending_dict(): return {'a': 1, 'b': 2, 'c': 3} def ending_array(): return [1, 2, 3] def ending_list_comp(): return [x for x in range(2)] def ending_if_else(): if 1 == 2: return True else: return False def ending_if_elif(): if 1 == 2: return True elif True: return False def one_line_if(): return 1 if True else 2
# -*- coding: utf-8 -*- class InternalCompilerError(Exception): """ An internal compiler error is unrecoverable and fatal. It should never happen for any user input. """ def __init__(self, message=''): self.message = message pass def __str__(self): return self.message def internal_assert(a, b=None): """ Make assertions about the compiler logic. Their failure will result in a hard InternalCompilerError. """ if b is None: if not a: message = 'Internal Error' raise InternalCompilerError(message) elif a != b: message = f'{str(a)} != {str(b)}' raise InternalCompilerError(message)
class Internalcompilererror(Exception): """ An internal compiler error is unrecoverable and fatal. It should never happen for any user input. """ def __init__(self, message=''): self.message = message pass def __str__(self): return self.message def internal_assert(a, b=None): """ Make assertions about the compiler logic. Their failure will result in a hard InternalCompilerError. """ if b is None: if not a: message = 'Internal Error' raise internal_compiler_error(message) elif a != b: message = f'{str(a)} != {str(b)}' raise internal_compiler_error(message)
# -*- coding: utf-8 -*- """ idfy_rest_client.models.authentication This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ class Authentication(object): """Implementation of the 'Authentication' model. TODO: type model description here. Attributes: auth_before_sign (bool): If this is set to true, you have to include the social security number or SignatureMethod unique id for the signer social_security_number (string): The signers social security number signature_method_unique_id (string): Define this if you have the signers unique signaturemethod id (i.e. the norwegian bankid pid). Only the person supposed to sign the document will then be allowed to sign it. """ # Create a mapping from Model property names to API property names _names = { "auth_before_sign":'authBeforeSign', "social_security_number":'socialSecurityNumber', "signature_method_unique_id":'signatureMethodUniqueId' } def __init__(self, auth_before_sign=None, social_security_number=None, signature_method_unique_id=None, additional_properties = {}): """Constructor for the Authentication class""" # Initialize members of the class self.auth_before_sign = auth_before_sign self.social_security_number = social_security_number self.signature_method_unique_id = signature_method_unique_id # Add additional model properties to the instance self.additional_properties = additional_properties @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary auth_before_sign = dictionary.get('authBeforeSign') social_security_number = dictionary.get('socialSecurityNumber') signature_method_unique_id = dictionary.get('signatureMethodUniqueId') # Clean out expected properties from dictionary for key in cls._names.values(): if key in dictionary: del dictionary[key] # Return an object of this model return cls(auth_before_sign, social_security_number, signature_method_unique_id, dictionary)
""" idfy_rest_client.models.authentication This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ class Authentication(object): """Implementation of the 'Authentication' model. TODO: type model description here. Attributes: auth_before_sign (bool): If this is set to true, you have to include the social security number or SignatureMethod unique id for the signer social_security_number (string): The signers social security number signature_method_unique_id (string): Define this if you have the signers unique signaturemethod id (i.e. the norwegian bankid pid). Only the person supposed to sign the document will then be allowed to sign it. """ _names = {'auth_before_sign': 'authBeforeSign', 'social_security_number': 'socialSecurityNumber', 'signature_method_unique_id': 'signatureMethodUniqueId'} def __init__(self, auth_before_sign=None, social_security_number=None, signature_method_unique_id=None, additional_properties={}): """Constructor for the Authentication class""" self.auth_before_sign = auth_before_sign self.social_security_number = social_security_number self.signature_method_unique_id = signature_method_unique_id self.additional_properties = additional_properties @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None auth_before_sign = dictionary.get('authBeforeSign') social_security_number = dictionary.get('socialSecurityNumber') signature_method_unique_id = dictionary.get('signatureMethodUniqueId') for key in cls._names.values(): if key in dictionary: del dictionary[key] return cls(auth_before_sign, social_security_number, signature_method_unique_id, dictionary)
""" This is the PyTurbSim 'stress models' package. For more information or to use this package import the stressModels.api package, e.g.: >>> import pyts.stressModels.api as rm **Currently the stress package does not function properly, unless no coherence is used. Fixing this is near the top of the list of things to repair in PyTurbSim.** """
""" This is the PyTurbSim 'stress models' package. For more information or to use this package import the stressModels.api package, e.g.: >>> import pyts.stressModels.api as rm **Currently the stress package does not function properly, unless no coherence is used. Fixing this is near the top of the list of things to repair in PyTurbSim.** """
class BusInPOZ: def __init__(self, intersection, check_in_bus_info, check_in_phase, check_in_phasetime, check_in_time, last_check_in): self.intersection_of_interest = intersection self.bus_id = check_in_bus_info.idVeh self.check_in_time = check_in_time self.check_in_phase = check_in_phase self.check_in_phasetime = check_in_phasetime self.last_check_in = last_check_in # previous bus check in time self.check_in_headway = check_in_time - last_check_in self.check_out_time = -1 self.check_out_headway = -1 self.last_update_time = check_in_time self.original_action = None self.original_state = None # state generated at check in def check_out(self, check_out_time, last_check_out=0): self.check_out_time = check_out_time self.check_out_headway = check_out_time - last_check_out self.last_update_time = check_out_time def set_action(self, action): if self.original_action is None: self.original_action = action else: print("duplicate set original action, check to make sure implementation is correct") def set_state(self, state): if self.original_state is None: self.original_state = state else: print("duplicate set original state, check to make sure implementation is correct")
class Businpoz: def __init__(self, intersection, check_in_bus_info, check_in_phase, check_in_phasetime, check_in_time, last_check_in): self.intersection_of_interest = intersection self.bus_id = check_in_bus_info.idVeh self.check_in_time = check_in_time self.check_in_phase = check_in_phase self.check_in_phasetime = check_in_phasetime self.last_check_in = last_check_in self.check_in_headway = check_in_time - last_check_in self.check_out_time = -1 self.check_out_headway = -1 self.last_update_time = check_in_time self.original_action = None self.original_state = None def check_out(self, check_out_time, last_check_out=0): self.check_out_time = check_out_time self.check_out_headway = check_out_time - last_check_out self.last_update_time = check_out_time def set_action(self, action): if self.original_action is None: self.original_action = action else: print('duplicate set original action, check to make sure implementation is correct') def set_state(self, state): if self.original_state is None: self.original_state = state else: print('duplicate set original state, check to make sure implementation is correct')
# -*- coding: utf-8 -*- __version__ = '0.5.0.dev0' PROJECT_NAME = "gx-tool-db" PROJECT_OWNER = PROJECT_USERAME = "galaxyproject" PROJECT_AUTHOR = 'Galaxy Project and Community' PROJECT_EMAIL = 'jmchilton@gmail.com' PROJECT_URL = "https://github.com/galaxyproject/gx-tool-db" RAW_CONTENT_URL = "https://raw.github.com/%s/%s/main/" % ( PROJECT_USERAME, PROJECT_NAME )
__version__ = '0.5.0.dev0' project_name = 'gx-tool-db' project_owner = project_userame = 'galaxyproject' project_author = 'Galaxy Project and Community' project_email = 'jmchilton@gmail.com' project_url = 'https://github.com/galaxyproject/gx-tool-db' raw_content_url = 'https://raw.github.com/%s/%s/main/' % (PROJECT_USERAME, PROJECT_NAME)
""" https://leetcode.com/problems/design-hashset/ Design a HashSet without using any built-in hash table libraries. To be specific, your design should include these functions: add(value): Insert a value into the HashSet. contains(value) : Return whether the value exists in the HashSet or not. remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing. Example: MyHashSet hashSet = new MyHashSet(); hashSet.add(1); hashSet.add(2); hashSet.contains(1); // returns true hashSet.contains(3); // returns false (not found) hashSet.add(2); hashSet.contains(2); // returns true hashSet.remove(2); hashSet.contains(2); // returns false (already removed) Note: All values will be in the range of [0, 1000000]. The number of operations will be in the range of [1, 10000]. Please do not use the built-in HashSet library. """ # time complexity: O(1), space complexity: O(n) class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.bucket = list([] for i in range(1000)) def _getHash(self, key: int) -> int: return int(str(hash(str(key)))[-3:]) def add(self, key: int) -> None: index = self._getHash(key) for i in self.bucket[index]: if i == key: return self.bucket[index].append(key) def remove(self, key: int) -> None: index = self._getHash(key) for i in self.bucket[index]: if i == key: self.bucket[index].remove(i) return def contains(self, key: int) -> bool: """ Returns true if this set contains the specified element """ index = self._getHash(key) for i in self.bucket[index]: if i == key: return True return False # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key)
""" https://leetcode.com/problems/design-hashset/ Design a HashSet without using any built-in hash table libraries. To be specific, your design should include these functions: add(value): Insert a value into the HashSet. contains(value) : Return whether the value exists in the HashSet or not. remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing. Example: MyHashSet hashSet = new MyHashSet(); hashSet.add(1); hashSet.add(2); hashSet.contains(1); // returns true hashSet.contains(3); // returns false (not found) hashSet.add(2); hashSet.contains(2); // returns true hashSet.remove(2); hashSet.contains(2); // returns false (already removed) Note: All values will be in the range of [0, 1000000]. The number of operations will be in the range of [1, 10000]. Please do not use the built-in HashSet library. """ class Myhashset: def __init__(self): """ Initialize your data structure here. """ self.bucket = list(([] for i in range(1000))) def _get_hash(self, key: int) -> int: return int(str(hash(str(key)))[-3:]) def add(self, key: int) -> None: index = self._getHash(key) for i in self.bucket[index]: if i == key: return self.bucket[index].append(key) def remove(self, key: int) -> None: index = self._getHash(key) for i in self.bucket[index]: if i == key: self.bucket[index].remove(i) return def contains(self, key: int) -> bool: """ Returns true if this set contains the specified element """ index = self._getHash(key) for i in self.bucket[index]: if i == key: return True return False
#! Line breaks in 'print' function. print( """1 line 2 line 3 line""" ) print( '1 line\n' '2 line\n' '3 line') # Separator parameter. print( '1 line\n', '2 line\n', '3 line', sep='______\n') # End paramerer. print('hello', 'kato', sep=' ', end="!")
print('1 line\n 2 line\n 3 line') print('1 line\n2 line\n3 line') print('1 line\n', '2 line\n', '3 line', sep='______\n') print('hello', 'kato', sep=' ', end='!')
class Vertex: def __init__(self, x=None, y=None): self.pos = [x, y] self.x = x self.y = y self.data = None def __str__(self): return f"{self.pos}" def __repr__(self): return f"{self.pos}" def __hash__(self): return hash(''.join([str(x) for x in self.pos])) @property def id(self): return self.__hash__()
class Vertex: def __init__(self, x=None, y=None): self.pos = [x, y] self.x = x self.y = y self.data = None def __str__(self): return f'{self.pos}' def __repr__(self): return f'{self.pos}' def __hash__(self): return hash(''.join([str(x) for x in self.pos])) @property def id(self): return self.__hash__()
# 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 rob(self, root): """ :type root: TreeNode :rtype: int """ return max(self.dfs(root)) def dfs(self, root): # Quick exit if not root: return 0, 0 # Left subtree left_skip_level, left_include_level = self.dfs(root.left) # Right subtree right_skip_level, right_include_level = self.dfs(root.right) # If we only take the maximums of subtrees by skipping current level skip_level = max(left_skip_level, left_include_level) + max(right_skip_level, right_include_level) # If we include current level and the skip levels below include_level = root.val + left_skip_level + right_skip_level return skip_level, include_level
class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ return max(self.dfs(root)) def dfs(self, root): if not root: return (0, 0) (left_skip_level, left_include_level) = self.dfs(root.left) (right_skip_level, right_include_level) = self.dfs(root.right) skip_level = max(left_skip_level, left_include_level) + max(right_skip_level, right_include_level) include_level = root.val + left_skip_level + right_skip_level return (skip_level, include_level)
#$Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/xmlBase/xmlBaseLib.py,v 1.4 2009/01/23 00:21:04 ecephas Exp $ def generate(env, **kw): if not kw.get('depsOnly',0): env.Tool('addLibrary', library = ['xmlBase'], package = 'xmlBase') if env['PLATFORM']=='win32' and env.get('CONTAINERNAME','')=='GlastRelease': env.Tool('findPkgPath', package = 'xmlBase') env.Tool('facilitiesLib') env.Tool('addLibrary', library = env['xercesLibs']) def exists(env): return 1
def generate(env, **kw): if not kw.get('depsOnly', 0): env.Tool('addLibrary', library=['xmlBase'], package='xmlBase') if env['PLATFORM'] == 'win32' and env.get('CONTAINERNAME', '') == 'GlastRelease': env.Tool('findPkgPath', package='xmlBase') env.Tool('facilitiesLib') env.Tool('addLibrary', library=env['xercesLibs']) def exists(env): return 1
# Python program to print the first non-repeating character NO_OF_CHARS = 256 # Returns an array of size 256 containg count # of characters in the passed char array def getCharCountArray(string): count = [0] * NO_OF_CHARS for i in string: count[ord(i)] += 1 return count # The function returns index of first non-repeating # character in a string. If all characters are repeating # then returns -1 def firstNonRepeating(string): count = getCharCountArray(string) index = -1 k = 0 for i in string: if count[ord(i)] == 1: index = k break k += 1 print(count) return index # Driver program to test above function string = input("Introduce string: ") index = firstNonRepeating(string) if index == 1: print("Either all characters are repeating or string is empty") else: print("First non-repeating character is ", index) # This code is contributed by Bhavya Jain
no_of_chars = 256 def get_char_count_array(string): count = [0] * NO_OF_CHARS for i in string: count[ord(i)] += 1 return count def first_non_repeating(string): count = get_char_count_array(string) index = -1 k = 0 for i in string: if count[ord(i)] == 1: index = k break k += 1 print(count) return index string = input('Introduce string: ') index = first_non_repeating(string) if index == 1: print('Either all characters are repeating or string is empty') else: print('First non-repeating character is ', index)
class Solution: def reverse(self, x: int) -> int: if x < 0 and x >= (-2**31): # x_str = str(x) # x_str_rev = '-' # access from the 2nd last element excluding "-" sign x_str_rev = '-' + str(x)[len(str(x)):0:-1] if int(x_str_rev) < (-2**31): return_value = 0 else: return_value = int(x_str_rev) elif x >= 0 and x <= ((2**31)-1): # x_str = str(x) # convert the int into str x_str_rev = str(x)[::-1] if int(x_str_rev) > (2**31)-1: return_value = 0 else: return_value = int(x_str_rev) else: return 0 return return_value
class Solution: def reverse(self, x: int) -> int: if x < 0 and x >= -2 ** 31: x_str_rev = '-' + str(x)[len(str(x)):0:-1] if int(x_str_rev) < -2 ** 31: return_value = 0 else: return_value = int(x_str_rev) elif x >= 0 and x <= 2 ** 31 - 1: x_str_rev = str(x)[::-1] if int(x_str_rev) > 2 ** 31 - 1: return_value = 0 else: return_value = int(x_str_rev) else: return 0 return return_value
# This problem was asked by Palantir. # Given a number represented by a list of digits, find the next greater permutation of a # number, in terms of lexicographic ordering. If there is not greater permutation possible, # return the permutation with the lowest value/ordering. # For example, the list [1,2,3] should return [1,3,2]. The list [1,3,2] should return [2,1,3]. # The list [3,2,1] should return [1,2,3]. # Can you perform the operation without allocating extra memory (disregarding the input memory)? #### def next_perm(arr): n = len(arr) i = n-1 while i > 0: arr[i], arr[i-1] = arr[i-1], arr[i] if arr[i-1] > arr[i]: return arr i -= 1 return sorted(arr) #### print(next_perm([1, 4, 3, 2]))
def next_perm(arr): n = len(arr) i = n - 1 while i > 0: (arr[i], arr[i - 1]) = (arr[i - 1], arr[i]) if arr[i - 1] > arr[i]: return arr i -= 1 return sorted(arr) print(next_perm([1, 4, 3, 2]))
def length_of_longest_substring(s): dici = {} max_s_rep = repeticao_na_fila = 0 for i, value in enumerate(s): if value in dici: num_repetidos = dici[value] + 1 if num_repetidos > repeticao_na_fila: repeticao_na_fila = num_repetidos num_repeticoes = i + 1 - repeticao_na_fila if num_repeticoes > max_s_rep: max_s_rep = num_repeticoes dici[value] = i return max_s_rep
def length_of_longest_substring(s): dici = {} max_s_rep = repeticao_na_fila = 0 for (i, value) in enumerate(s): if value in dici: num_repetidos = dici[value] + 1 if num_repetidos > repeticao_na_fila: repeticao_na_fila = num_repetidos num_repeticoes = i + 1 - repeticao_na_fila if num_repeticoes > max_s_rep: max_s_rep = num_repeticoes dici[value] = i return max_s_rep
#!/usr/bin/python3 f = open("/home/bccue/Cores-SweRV/testbench/asm/hello_world.s", "r") g = open("/home/bccue/Cores-SweRV/testbench/asm/hello_world_c.c", "w") for data in f: data = data.strip("\n") if (data == "") or ("//" in data): continue #New text to print to terminal if (".ascii" in data): print("__asm (\".ascii \\\"========================================\\n\\\"\");", file=g) print("__asm (\".ascii \\\"Technically C, but really just assembly.\\n\\\"\");", file=g) print("__asm (\".ascii \\\"========================================\\n\\\"\");", file=g) print("__asm (\".byte 0\");", file=g) break #Format the string print('__asm (\"', end="", file=g) for i in range(len(data)): if data[i] == '"': print("\\\"", end="", file=g) else: print(data[i], end="", file=g) print('\");', file=g) #Add .equ directives as #define doesn't work for some reason if (".text" in data): print("__asm (\".equ STDOUT, 0xd0580000\");", file=g) print("__asm (\".equ RV_ICCM_SADR, 0xee000000\");", file=g) f.close() g.close()
f = open('/home/bccue/Cores-SweRV/testbench/asm/hello_world.s', 'r') g = open('/home/bccue/Cores-SweRV/testbench/asm/hello_world_c.c', 'w') for data in f: data = data.strip('\n') if data == '' or '//' in data: continue if '.ascii' in data: print('__asm (".ascii \\"========================================\\n\\"");', file=g) print('__asm (".ascii \\"Technically C, but really just assembly.\\n\\"");', file=g) print('__asm (".ascii \\"========================================\\n\\"");', file=g) print('__asm (".byte 0");', file=g) break print('__asm ("', end='', file=g) for i in range(len(data)): if data[i] == '"': print('\\"', end='', file=g) else: print(data[i], end='', file=g) print('");', file=g) if '.text' in data: print('__asm (".equ STDOUT, 0xd0580000");', file=g) print('__asm (".equ RV_ICCM_SADR, 0xee000000");', file=g) f.close() g.close()
#!/usr/bin/python # ex:set fileencoding=utf-8: default_app_config = 'mosquitto.apps.Config'
default_app_config = 'mosquitto.apps.Config'
#Loading one line from file and starting a dictionary for line in open('rosalind_ini6.txt', 'r').readlines(): contents = line.split() dictionary = dict() #Checking if a word from line is in dictionary, then sum the occurrences for i in range(0, len(contents), 1): if (contents[i] not in dictionary): dictionary[contents[i]] = 1 else: dictionary[contents[i]] += 1 #Printing all the words with respective occurrences amount for key, value in dictionary.items(): print(key, value)
for line in open('rosalind_ini6.txt', 'r').readlines(): contents = line.split() dictionary = dict() for i in range(0, len(contents), 1): if contents[i] not in dictionary: dictionary[contents[i]] = 1 else: dictionary[contents[i]] += 1 for (key, value) in dictionary.items(): print(key, value)
# Python file # Save this with extension .py # Made By Arnav Naik # A beginner's guide to Python print("Welcome To The Trivia!!") # Scoring total_q = 4 print("Total Questions: ", total_q) def question_1(): global score score = int(0) # Question1 question1 = str(input("1. What's the best programming language? ")) ans1u = "python" ans1 = "Python" if question1 == ans1u or question1 == ans1: question_1() print("Correct!!") score = score + 1 print("Your Updated Score Is: ", score) else: print("Wrong!!, the correct answer is ",ans1u,"/",ans1) # Question2 question2 = str(input("2. What's 2+2? ")) ans2 = "4" if question2 == ans2: print("Correct!!") score = score + 1 print("Your Updated Score Is: ", score) else: print("Wrong, the correct answer is: ", ans2) # Question3 question3 = str(input("3. What's 4-5? ")) ans3 = "-1" if question3 == ans3: print("Correct!!") score = score + 1 print("Your Updated Score Is: ", score) else: print("Wrong, the correct answer is: ", ans3) # Question4 question4 = str(input("4. What's Java-Script? ")) ans4u = "programming language" ans4 = "Programming Language" if question4 == ans4u or question4 == ans4: print("Correct!!") score = score + 1 print("Your Updated Score Is: ", score) else: print("Wrong!!, the correct answer is",ans4,"/",ans4u) print("Thank You For Playing! You Scored: ", score) print("Credits: Arnav Naik") print("Check Out My GitHub: https://github.com/code643/Stable-Release-of-Trivia")
print('Welcome To The Trivia!!') total_q = 4 print('Total Questions: ', total_q) def question_1(): global score score = int(0) question1 = str(input("1. What's the best programming language? ")) ans1u = 'python' ans1 = 'Python' if question1 == ans1u or question1 == ans1: question_1() print('Correct!!') score = score + 1 print('Your Updated Score Is: ', score) else: print('Wrong!!, the correct answer is ', ans1u, '/', ans1) question2 = str(input("2. What's 2+2? ")) ans2 = '4' if question2 == ans2: print('Correct!!') score = score + 1 print('Your Updated Score Is: ', score) else: print('Wrong, the correct answer is: ', ans2) question3 = str(input("3. What's 4-5? ")) ans3 = '-1' if question3 == ans3: print('Correct!!') score = score + 1 print('Your Updated Score Is: ', score) else: print('Wrong, the correct answer is: ', ans3) question4 = str(input("4. What's Java-Script? ")) ans4u = 'programming language' ans4 = 'Programming Language' if question4 == ans4u or question4 == ans4: print('Correct!!') score = score + 1 print('Your Updated Score Is: ', score) else: print('Wrong!!, the correct answer is', ans4, '/', ans4u) print('Thank You For Playing! You Scored: ', score) print('Credits: Arnav Naik') print('Check Out My GitHub: https://github.com/code643/Stable-Release-of-Trivia')
""" # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten(self, head: 'Node') -> 'Node': if not head: return None cur = head stack = [cur] while stack: now = stack.pop(-1) if now != head: cur.next, now.prev = now, cur cur.child = None cur = now if now.next: stack.append(now.next) if now.child: stack.append(now.child) return head
""" # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten(self, head: 'Node') -> 'Node': if not head: return None cur = head stack = [cur] while stack: now = stack.pop(-1) if now != head: (cur.next, now.prev) = (now, cur) cur.child = None cur = now if now.next: stack.append(now.next) if now.child: stack.append(now.child) return head
class Solution: def toLowerCase(self, str: str) -> str: res = [] for i in range(len(str)): if 65 <= ord(str[i]) <= 92: res.append(chr(ord(str[i]) + 32)) else: res.append(str[i]) return "".join(res) def toLowerCase2(self, str: str) -> str: s = "".join([chr(i) for i in range(65, 91)]) t = "".join([chr(i) for i in range(97,123)]) res = [] for i in range(len(str)): # ind = s.index(str[i]) if str[i] in s: ind = s.index(str[i]) res.append(t[ind]) else: res.append(str[i]) return "".join(res) str = "Hello" str = "here" # str = "i797" str = "" s = Solution() print(s.toLowerCase(str)) print(s.toLowerCase2(str))
class Solution: def to_lower_case(self, str: str) -> str: res = [] for i in range(len(str)): if 65 <= ord(str[i]) <= 92: res.append(chr(ord(str[i]) + 32)) else: res.append(str[i]) return ''.join(res) def to_lower_case2(self, str: str) -> str: s = ''.join([chr(i) for i in range(65, 91)]) t = ''.join([chr(i) for i in range(97, 123)]) res = [] for i in range(len(str)): if str[i] in s: ind = s.index(str[i]) res.append(t[ind]) else: res.append(str[i]) return ''.join(res) str = 'Hello' str = 'here' str = '' s = solution() print(s.toLowerCase(str)) print(s.toLowerCase2(str))
class NotInitedException(Exception): """Deprecated! was used to state that the database in the general config was not inited yet""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class MissingUserException(Exception): """The requested User could not be found""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class AlreadyExistsException(Exception): """The thing that was tried to create already existed""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class TokenMissingException(Exception): """No token was provided even though it was needed""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class NotAnADUser(Exception): """the user is not an AD user so you cant log him in via the AD Login handler""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class ADLoginProhibited(Exception): """Ad Logins are disabled so you cant log him in via the AD Login handler""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs)
class Notinitedexception(Exception): """Deprecated! was used to state that the database in the general config was not inited yet""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class Missinguserexception(Exception): """The requested User could not be found""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class Alreadyexistsexception(Exception): """The thing that was tried to create already existed""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class Tokenmissingexception(Exception): """No token was provided even though it was needed""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class Notanaduser(Exception): """the user is not an AD user so you cant log him in via the AD Login handler""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) class Adloginprohibited(Exception): """Ad Logins are disabled so you cant log him in via the AD Login handler""" def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs)
# -------------- # Code starts here # Create the lists class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio' ] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] # Concatenate both the strings new_class = (class_1 + class_2) print (new_class) # Append the list new_class.append('Peter Warden') # Print updated list print(new_class) # Remove the element from the list new_class.remove('Carla Gentry') # Print the list print(new_class) # Code ends here # -------------- # Code starts here mathematics = {'Geoffrey Hinton' : 78,'Andrew Ng' : 95, 'Sebastian Raschka' : 65, 'Yoshua Benjio': 50, 'Hilary Mason' : 70, 'Corinna Cortes' : 66, 'Peter Warden' : 75} topper = max(mathematics,key = mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here #printing first name first_name = (topper.split()[0]) print(first_name) #printing last name last_name = (topper.split()[1]) print(last_name) # Displaying full name full_name = last_name + ' ' + first_name print(full_name) # Displaying Certificate Name certificate_name = full_name.upper() print(certificate_name) # Code ends here # -------------- # Code starts here courses = {'Math' : 65,'English' : 70, 'History' : 80, 'French': 70, 'Science' : 60} print(courses['Math']) print(courses['English']) print(courses['History']) print(courses['French']) print(courses['Science']) total = ((courses['Math']) + (courses['English']) + (courses['History']) + (courses['French']) + (courses['Science'])) print(total) percentage = (total *100 /500) print(percentage) # Code ends here
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 66, 'Peter Warden': 75} topper = max(mathematics, key=mathematics.get) print(topper) topper = 'andrew ng' first_name = topper.split()[0] print(first_name) last_name = topper.split()[1] print(last_name) full_name = last_name + ' ' + first_name print(full_name) certificate_name = full_name.upper() print(certificate_name) courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70, 'Science': 60} print(courses['Math']) print(courses['English']) print(courses['History']) print(courses['French']) print(courses['Science']) total = courses['Math'] + courses['English'] + courses['History'] + courses['French'] + courses['Science'] print(total) percentage = total * 100 / 500 print(percentage)
#!/usr/bin/env python3 # Created by Tiago Minuzzi, 2020. # Files in_fasta = "teste.fasta" in_ids = "ids.txt" out_fasta = "res_fas.fa" # Empty dictionary to store sequences fas_dict = {} # Read reference fasta file with open(in_fasta, "r") as fasta: fasta=fasta.readlines() for linha in fasta: linha = linha.strip() if linha.startswith(">"): kl = linha[1:] fas_dict[kl] = '' else: fas_dict[kl] = linha.upper() # Open ids file and create output file with open(in_ids,"r") as ides, open(out_fasta,'w') as fas_out: ides = ides.read() for sid, sseq in fas_dict.items(): # Search ids from dict in ids file if sid in ides: # Write wanted sequences to file fas_out.write(f'>{sid}'+'\n'+f'{sseq}'+'\n')
in_fasta = 'teste.fasta' in_ids = 'ids.txt' out_fasta = 'res_fas.fa' fas_dict = {} with open(in_fasta, 'r') as fasta: fasta = fasta.readlines() for linha in fasta: linha = linha.strip() if linha.startswith('>'): kl = linha[1:] fas_dict[kl] = '' else: fas_dict[kl] = linha.upper() with open(in_ids, 'r') as ides, open(out_fasta, 'w') as fas_out: ides = ides.read() for (sid, sseq) in fas_dict.items(): if sid in ides: fas_out.write(f'>{sid}' + '\n' + f'{sseq}' + '\n')
#strings = """ We love our mom she helps us is in varius ways. #She makes food for us. #She takes us to school. #She always takes care of us. #""" #multiline strings #print (strings) sentence1 = 'Tamim is a great player' sentence2 = "\"Bangldesh\" is a developing country" print (sentence1) print (sentence2) length = len(sentence1) sentence1 = 'Tamim is a great player' sentence2 = "\"Bangldesh\" is a developing country" length = len(sentence1) print (length) #print (length) pizza = 'We love pizza' pizza_slice = pizza[6:] print (pizza_slice) pizza_cap = pizza.upper() print (pizza_cap) pizza = 'We love pizza' pizza_cap = pizza.upper() print (pizza_cap) pizza = 'WE LOVE PIZZA' pizza_cap = pizza.lower() print (pizza_cap) pizza = 'WE LOVE PIZZA' pizza_cap = pizza.strip() print (pizza_cap) pizza = 'WE LOVE PIZZA' print (pizza.replace("LOVE","HATE")) name = 'My name is Zareef' print (name.replace("name","friend")) name = "Zareef likes video games" print (name[0:5])
sentence1 = 'Tamim is a great player' sentence2 = '"Bangldesh" is a developing country' print(sentence1) print(sentence2) length = len(sentence1) sentence1 = 'Tamim is a great player' sentence2 = '"Bangldesh" is a developing country' length = len(sentence1) print(length) pizza = 'We love pizza' pizza_slice = pizza[6:] print(pizza_slice) pizza_cap = pizza.upper() print(pizza_cap) pizza = 'We love pizza' pizza_cap = pizza.upper() print(pizza_cap) pizza = 'WE LOVE PIZZA' pizza_cap = pizza.lower() print(pizza_cap) pizza = 'WE LOVE PIZZA' pizza_cap = pizza.strip() print(pizza_cap) pizza = 'WE LOVE PIZZA' print(pizza.replace('LOVE', 'HATE')) name = 'My name is Zareef' print(name.replace('name', 'friend')) name = 'Zareef likes video games' print(name[0:5])
class State: def __init__(self, goal, task, visual, ): self.goal = None self.task = None self.visual = None self.features = None
class State: def __init__(self, goal, task, visual): self.goal = None self.task = None self.visual = None self.features = None
for i in range(1, 10): print(i, end=', ') print() for i in range(0, 10, 2): print(i, ' ', end='') print() for i in range(10, 1, -2): print(i, ' ', end='')
for i in range(1, 10): print(i, end=', ') print() for i in range(0, 10, 2): print(i, ' ', end='') print() for i in range(10, 1, -2): print(i, ' ', end='')
class BatchCancelled(Exception): """ Error used when a batch has been cancelled. """ pass
class Batchcancelled(Exception): """ Error used when a batch has been cancelled. """ pass
#!/usr/bin/env python """iexport.py: export the unallocated spaces.""" class Run: """Keeps track of a single run""" def __init__(self,start,len): self.start = start self.len = len self.end = start+len-1 def __str__(self): return "Run<%d--%d> (len %d)" % (self.start,self.end,self.len) def contains(self,b): """Returns true if b is inside self.""" print("%d <= %d <= %d = %s" % (self.start,b,self.end,(self.start <= b <= self.end))) return self.start <= b <= self.end def intersects_run(self,r): """Return true if self intersects r. This may be because r.start is inside the run, r.end is inside the run, or self is inside the run.""" return self.contains(r.start) or self.contains(r.end) or r.contains(self.start) def contains_run(self,r): """Returns true if self completely contains r""" return self.contains(r.start) and self.contains(r.end) class RunDB: """The RunDB maintains a list of all the runs in a disk image. The RunDB is created with a single run that represents all of the sectors in the disk image. Runs can then be removed, which causes existing runs to be split. Finally all of the remaining runs can be removed.""" def __init__(self,start,len): self.runs = [ Run(start,len) ] def __str__(self): return "RunDB\n" + "\n".join([str(p) for p in self.runs]) def intersecting_runs(self,r): """Return a list of all the Runs that intersect with r. This may be because r.start is inside the run, r.end is inside the run, because the run completely encloses r, or because r completely encloses the run.""" return filter(lambda x:x.intersects_run(r) , self.runs) def remove(self,r): """Remove run r""" for p in self.intersecting_runs(r): self.runs.remove(p) # if P is completely inside r, just remove it if r.contains_run(p): continue # Split p into before and after r; add the non-zero pieces before_len = r.start - p.start if before_len>0: self.runs.append(Run(p.start,before_len)) after_len = p.end - r.end if after_len>0: self.runs.append(Run(r.end,after_len))
"""iexport.py: export the unallocated spaces.""" class Run: """Keeps track of a single run""" def __init__(self, start, len): self.start = start self.len = len self.end = start + len - 1 def __str__(self): return 'Run<%d--%d> (len %d)' % (self.start, self.end, self.len) def contains(self, b): """Returns true if b is inside self.""" print('%d <= %d <= %d = %s' % (self.start, b, self.end, self.start <= b <= self.end)) return self.start <= b <= self.end def intersects_run(self, r): """Return true if self intersects r. This may be because r.start is inside the run, r.end is inside the run, or self is inside the run.""" return self.contains(r.start) or self.contains(r.end) or r.contains(self.start) def contains_run(self, r): """Returns true if self completely contains r""" return self.contains(r.start) and self.contains(r.end) class Rundb: """The RunDB maintains a list of all the runs in a disk image. The RunDB is created with a single run that represents all of the sectors in the disk image. Runs can then be removed, which causes existing runs to be split. Finally all of the remaining runs can be removed.""" def __init__(self, start, len): self.runs = [run(start, len)] def __str__(self): return 'RunDB\n' + '\n'.join([str(p) for p in self.runs]) def intersecting_runs(self, r): """Return a list of all the Runs that intersect with r. This may be because r.start is inside the run, r.end is inside the run, because the run completely encloses r, or because r completely encloses the run.""" return filter(lambda x: x.intersects_run(r), self.runs) def remove(self, r): """Remove run r""" for p in self.intersecting_runs(r): self.runs.remove(p) if r.contains_run(p): continue before_len = r.start - p.start if before_len > 0: self.runs.append(run(p.start, before_len)) after_len = p.end - r.end if after_len > 0: self.runs.append(run(r.end, after_len))
""" Union find algorithm """ def get_parent(arr, i): if arr[i] == i: return i arr[i] = get_parent(arr, arr[i]) return arr[i] def union_parent(arr, a, b): a = get_parent(arr, a) b = get_parent(arr, b) if a < b: arr[b] = a else: arr[a] = b def find_parent(arr, a, b): a = get_parent(arr, a) b = get_parent(arr, b) return 1 if a == b else 0 parent = [i for i in range(11)] union_parent(parent, 1, 2) print(parent) union_parent(parent, 2, 3) print(parent) union_parent(parent, 3, 4) print(parent) union_parent(parent, 5, 6) print(parent) union_parent(parent, 6, 7) print(parent) union_parent(parent, 7, 8) print(parent) print(find_parent(parent, 1, 5)) union_parent(parent, 1, 5) print(find_parent(parent, 1, 5))
""" Union find algorithm """ def get_parent(arr, i): if arr[i] == i: return i arr[i] = get_parent(arr, arr[i]) return arr[i] def union_parent(arr, a, b): a = get_parent(arr, a) b = get_parent(arr, b) if a < b: arr[b] = a else: arr[a] = b def find_parent(arr, a, b): a = get_parent(arr, a) b = get_parent(arr, b) return 1 if a == b else 0 parent = [i for i in range(11)] union_parent(parent, 1, 2) print(parent) union_parent(parent, 2, 3) print(parent) union_parent(parent, 3, 4) print(parent) union_parent(parent, 5, 6) print(parent) union_parent(parent, 6, 7) print(parent) union_parent(parent, 7, 8) print(parent) print(find_parent(parent, 1, 5)) union_parent(parent, 1, 5) print(find_parent(parent, 1, 5))
# Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko # Copyright 2019-2020 Intel Corporation # # SPDX-License-Identifier: AGPL-3.0-or-later HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[0;33m' FAIL = '\033[91m' ENDC = '\033[0m' CLRSCR = '\x1b[1;1H' REALCLRSCR = '\x1b[2J' BOLD = '\033[1m' FLUSH_LINE = '\r\x1b[K' def MOVE_CURSOR_UP(num): return "\033[" + str(num) + "A" def MOVE_CURSOR_DOWN(num): return "\033[" + str(num) + "B" def MOVE_CURSOR_LEFT(num): return "\033[" + str(num) + "C" def MOVE_CURSOR_RIGHT(num): return "\033[" + str(num) + "D" HLINE = chr(0x2500) VLINE = chr(0x2502) VLLINE = chr(0x2524) VRLINE = chr(0x251c) LBEDGE = chr(0x2514) RBEDGE = chr(0x2518) HULINE = chr(0x2534) HDLINE = chr(0x252c) LTEDGE = chr(0x250c) RTEDGE = chr(0x2510) INFO_PREFIX = "[INFO] " ERROR_PREFIX = "[ERROR] " WARNING_PREFIX = "[WARNING] "
header = '\x1b[95m' okblue = '\x1b[94m' okgreen = '\x1b[92m' warning = '\x1b[0;33m' fail = '\x1b[91m' endc = '\x1b[0m' clrscr = '\x1b[1;1H' realclrscr = '\x1b[2J' bold = '\x1b[1m' flush_line = '\r\x1b[K' def move_cursor_up(num): return '\x1b[' + str(num) + 'A' def move_cursor_down(num): return '\x1b[' + str(num) + 'B' def move_cursor_left(num): return '\x1b[' + str(num) + 'C' def move_cursor_right(num): return '\x1b[' + str(num) + 'D' hline = chr(9472) vline = chr(9474) vlline = chr(9508) vrline = chr(9500) lbedge = chr(9492) rbedge = chr(9496) huline = chr(9524) hdline = chr(9516) ltedge = chr(9484) rtedge = chr(9488) info_prefix = '[INFO] ' error_prefix = '[ERROR] ' warning_prefix = '[WARNING] '
# Longest Increasing Subsequence # We have discussed Overlapping Subproblems and Optimal Substructure properties. # Let us discuss Longest Increasing Subsequence (LIS) problem as an example # problem that can be solved using Dynamic Programming. # The Longest Increasing Subsequence (LIS) problem is to find the length of # the longest subsequence of a given sequence such that all elements of the # subsequence are sorted in increasing order. For example, the length of LIS # for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS # is {10, 22, 33, 50, 60, 80}. # longest-increasing-subsequence # More Examples: # Input : arr[] = {3, 10, 2, 1, 20} # Output : Length of LIS = 3 # The longest increasing subsequence is 3, 10, 20 # Input : arr[] = {3, 2} # Output : Length of LIS = 1 # The longest increasing subsequences are {3} and {2} # Input : arr[] = {50, 3, 10, 7, 40, 80} # Output : Length of LIS = 4 # The longest increasing subsequence is {3, 7, 40, 80} #Method 1 :https://youtu.be/Ns4LCeeOFS4 #(nlogn) def LongestIncreasingSequence(list1): n=len(list1) list2=[1 for i in range(n)] for i in range(1,n): for j in range(i): if list1[i]>list1[j] and list2[i]<list2[j]+1: list2[i]=list2[j]+1 return max(list2) print(LongestIncreasingSequence([50, 3, 10, 7, 40, 80]))
def longest_increasing_sequence(list1): n = len(list1) list2 = [1 for i in range(n)] for i in range(1, n): for j in range(i): if list1[i] > list1[j] and list2[i] < list2[j] + 1: list2[i] = list2[j] + 1 return max(list2) print(longest_increasing_sequence([50, 3, 10, 7, 40, 80]))
##Ejercicio 2 # el siguiente codigo busca la raiz entera de un numero dado usando BS # Busqueda Binaria # Entrada: # 16 (si se desea encontrar de un numero # mayor 20 incrementar el tamanio del array) # Salida: # Does not exist #or # "The element was found " +48 # # El ejercicio incluye el ordenamiento del array creado # Autor: Yeimy Huanca def binarySearch(list ,n): baja = 0 alta = len(list) - 1 while baja <= alta: middle = (alta + baja) // 2 middle_element = list[middle] cuadrado = middle_element*middle_element if cuadrado == n: return middle if cuadrado < n: baja = middle + 1 else: alta = middle - 1 return middle def createList(n): lst = [] for i in range(n+1): lst.append(i) return(lst) #length = int(input("length: ")) #list = list(range(length, 0, -1)) n = int(input("search?: ")) list = createList(20) #list = [1,5,9,7,15,19,20,40,48,50,90,91,100,150,151] print(list) #insertion_sort(list) #print(list) q= binarySearch(list, n) if q == -1: print("Does not exist") else: print("The element was found ",list[q])
def binary_search(list, n): baja = 0 alta = len(list) - 1 while baja <= alta: middle = (alta + baja) // 2 middle_element = list[middle] cuadrado = middle_element * middle_element if cuadrado == n: return middle if cuadrado < n: baja = middle + 1 else: alta = middle - 1 return middle def create_list(n): lst = [] for i in range(n + 1): lst.append(i) return lst n = int(input('search?: ')) list = create_list(20) print(list) q = binary_search(list, n) if q == -1: print('Does not exist') else: print('The element was found ', list[q])