content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
photos = Photo.objects.all()
captions = []
for idx, photo in enumerate(photos):
if idx > 2:
break
thumbnail_path = photo.thumbnail.url
with open("." + thumbnail_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
encoded_string = str(encoded_string)[2:-1]
resp_captions = requests.post("http://localhost:5000/", data=encoded_string)
captions.append(resp_captions.json()) | photos = Photo.objects.all()
captions = []
for (idx, photo) in enumerate(photos):
if idx > 2:
break
thumbnail_path = photo.thumbnail.url
with open('.' + thumbnail_path, 'rb') as image_file:
encoded_string = base64.b64encode(image_file.read())
encoded_string = str(encoded_string)[2:-1]
resp_captions = requests.post('http://localhost:5000/', data=encoded_string)
captions.append(resp_captions.json()) |
def quickSort(my_array):
qshelper(my_array, 0, len(my_array) - 1)
return my_array
def qshelper(my_array, start, end):
if start >= end:
return
pivot = start
left = start + 1
right = end
while right >= left:
if my_array[left] > my_array[pivot] and my_array[right] < my_array[pivot]:
my_array[left], my_array[right] = my_array[right], my_array[left]
if my_array[left] <= my_array[pivot]:
left += 1
if my_array[right] >= my_array[pivot]:
right -= 1
my_array[pivot], my_array[right] = my_array[right], my_array[pivot]
qshelper(my_array, start, right - 1)
qshelper(my_array, right + 1, end) | def quick_sort(my_array):
qshelper(my_array, 0, len(my_array) - 1)
return my_array
def qshelper(my_array, start, end):
if start >= end:
return
pivot = start
left = start + 1
right = end
while right >= left:
if my_array[left] > my_array[pivot] and my_array[right] < my_array[pivot]:
(my_array[left], my_array[right]) = (my_array[right], my_array[left])
if my_array[left] <= my_array[pivot]:
left += 1
if my_array[right] >= my_array[pivot]:
right -= 1
(my_array[pivot], my_array[right]) = (my_array[right], my_array[pivot])
qshelper(my_array, start, right - 1)
qshelper(my_array, right + 1, end) |
#!/usr/bin/env python
"""
MULTPOTS Multiply potentials into a single potential
newpot = multpots(pots)
multiply potentials : pots is a cell of potentials
potentials with empty tables are ignored
if a table of type 'zero' is encountered, the result is a table of type
'zero' with table 0, and empty variables.
"""
def multpots(pots):
# import copy
newpot = pots[0]
for i in range(1, len(pots)): # loop over all the potentials
#FIX ME: did not check dimension consistency
newpot = newpot*pots[i]
return newpot
| """
MULTPOTS Multiply potentials into a single potential
newpot = multpots(pots)
multiply potentials : pots is a cell of potentials
potentials with empty tables are ignored
if a table of type 'zero' is encountered, the result is a table of type
'zero' with table 0, and empty variables.
"""
def multpots(pots):
newpot = pots[0]
for i in range(1, len(pots)):
newpot = newpot * pots[i]
return newpot |
class Category:
def __init__(self, name):
self.name = name
self.ledger = []
def __str__(self):
l = len(self.name)
n1 = 15-int(l/2)
n2 = 30-(n1+l)
title = "*"*n1+self.name+"*"*n2+"\n"
summary = ""
for item in self.ledger:
a= format(item["amount"], '.2f')[0:6]
d = item["description"][0:23]
sl = 30 - len(a)-len(d)
summary = summary + d + " " * sl + a + "\n"
total = "Total: " + str(self.get_balance())
summary = title + summary + total
return summary
def deposit(self, amount, description=""):
self.ledger.append({"amount": amount, "description": description})
def withdraw(self, amount, description=""):
if amount <= self.get_balance():
self.ledger.append({"amount": amount*-1, "description": description})
return True
else: return False
def get_balance(self):
nums = [d["amount"] for d in self.ledger]
return float(sum(nums))
def transfer(self, amount, category): # transfers $ from this category to another
if self.check_funds(amount) == True:
wd = "Transfer to " + category.name
dd = "Transfer from " + self.name
self.withdraw(amount, wd)
category.deposit(amount, dd)
return True
else: return False
def check_funds(self, amount):
b = self.get_balance()
if amount > b :
return False
else:
return True
def check_spending(self):
nums = [d["amount"] for d in self.ledger]
spen = [num for num in nums if num < 0]
spending = -sum(spen)
return format(spending, '.2f')
def create_spend_chart(categories):
title = "Percentage spent by category"
dashes = " "*4 + "-"*(len(categories)*3+1)
width = 4+len(dashes)
y = reversed(range(0,101,10))
spending = []
name_max = 0
for category in categories:
num = float(category.check_spending())
spending.append(num)
if len(category.name) > name_max:
name_max = len(category.name)
total_spending = sum(spending)
chart = title + "\n"
for num in y:
nl = len(str(num))
p1 = " "*(3-nl)+str(num)+"| "
p2 = ""
for s in spending:
percent = int(s/total_spending*100/10)*10
if percent >= num:
p2 = p2 + "o "
else:
p2 = p2 + " "
line = p1 + p2 + "\n"
chart = chart + line
chart = chart + dashes + "\n"
for i in range(0, name_max):
line = " "*5
for c in categories:
if i > (len(c.name)-1):
line = line + " "
else:
l = c.name[i]
pi = l + " "
line = line + pi
if i < (name_max-1):
chart = chart + line + "\n"
else:
chart = chart + line
return chart
| class Category:
def __init__(self, name):
self.name = name
self.ledger = []
def __str__(self):
l = len(self.name)
n1 = 15 - int(l / 2)
n2 = 30 - (n1 + l)
title = '*' * n1 + self.name + '*' * n2 + '\n'
summary = ''
for item in self.ledger:
a = format(item['amount'], '.2f')[0:6]
d = item['description'][0:23]
sl = 30 - len(a) - len(d)
summary = summary + d + ' ' * sl + a + '\n'
total = 'Total: ' + str(self.get_balance())
summary = title + summary + total
return summary
def deposit(self, amount, description=''):
self.ledger.append({'amount': amount, 'description': description})
def withdraw(self, amount, description=''):
if amount <= self.get_balance():
self.ledger.append({'amount': amount * -1, 'description': description})
return True
else:
return False
def get_balance(self):
nums = [d['amount'] for d in self.ledger]
return float(sum(nums))
def transfer(self, amount, category):
if self.check_funds(amount) == True:
wd = 'Transfer to ' + category.name
dd = 'Transfer from ' + self.name
self.withdraw(amount, wd)
category.deposit(amount, dd)
return True
else:
return False
def check_funds(self, amount):
b = self.get_balance()
if amount > b:
return False
else:
return True
def check_spending(self):
nums = [d['amount'] for d in self.ledger]
spen = [num for num in nums if num < 0]
spending = -sum(spen)
return format(spending, '.2f')
def create_spend_chart(categories):
title = 'Percentage spent by category'
dashes = ' ' * 4 + '-' * (len(categories) * 3 + 1)
width = 4 + len(dashes)
y = reversed(range(0, 101, 10))
spending = []
name_max = 0
for category in categories:
num = float(category.check_spending())
spending.append(num)
if len(category.name) > name_max:
name_max = len(category.name)
total_spending = sum(spending)
chart = title + '\n'
for num in y:
nl = len(str(num))
p1 = ' ' * (3 - nl) + str(num) + '| '
p2 = ''
for s in spending:
percent = int(s / total_spending * 100 / 10) * 10
if percent >= num:
p2 = p2 + 'o '
else:
p2 = p2 + ' '
line = p1 + p2 + '\n'
chart = chart + line
chart = chart + dashes + '\n'
for i in range(0, name_max):
line = ' ' * 5
for c in categories:
if i > len(c.name) - 1:
line = line + ' '
else:
l = c.name[i]
pi = l + ' '
line = line + pi
if i < name_max - 1:
chart = chart + line + '\n'
else:
chart = chart + line
return chart |
#Max value from a list
numbers = []
lenght = int(input("Enter list lenght...\n"))
for i in range(lenght):
numbers.append(float(input("Enter an integer or decimal number...\n")))
print("The min value is: " + str(min(numbers)))
| numbers = []
lenght = int(input('Enter list lenght...\n'))
for i in range(lenght):
numbers.append(float(input('Enter an integer or decimal number...\n')))
print('The min value is: ' + str(min(numbers))) |
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Reconnect by Title
# COLOR: #6b4930
#
#----------------------------------------------------------------------------------------------------------
ns = [n for n in nuke.selectedNodes() if n.knob("identifier")]
for n in ns:
try:
n["reconnect_by_title_this"].execute()
except:
pass
| ns = [n for n in nuke.selectedNodes() if n.knob('identifier')]
for n in ns:
try:
n['reconnect_by_title_this'].execute()
except:
pass |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
# def __init__(self):
# self.curr_head = None
#
# def isPalindrome(self, head):
# """
# :type head: ListNode
# :rtype: bool
# """
# self.curr_head = head
# return self.check(head)
#
# def check(self, node):
# if node is None:
# return True
# isPal = self.check(node.next) and (self.curr_head.val == node.val)
# self.curr_head = self.curr_head.next
# return isPal
def isPalindrome(self, head):
# p2 is 2 times faster than p3
# p1 and pre is used to reverse the first half of the list
# so when the first while is over
# p1 is in the middle
# p3 is in middle + 1
# p2 is in the end
if head is None:
return True
p1, p2 = head, head
p3, pre = p1.next, p1
while p2.next is not None and p2.next.next is not None:
p2 = p2.next.next
pre = p1
p1 = p3
p3 = p3.next
p1.next = pre
if p2.next is None:
p1 = p1.next
while p3 is not None:
if p1.val != p3.val:
return False
p1 = p1.next
p3 = p3.next
return True | class Solution(object):
def is_palindrome(self, head):
if head is None:
return True
(p1, p2) = (head, head)
(p3, pre) = (p1.next, p1)
while p2.next is not None and p2.next.next is not None:
p2 = p2.next.next
pre = p1
p1 = p3
p3 = p3.next
p1.next = pre
if p2.next is None:
p1 = p1.next
while p3 is not None:
if p1.val != p3.val:
return False
p1 = p1.next
p3 = p3.next
return True |
class SisChkpointOpType(basestring):
"""
Checkpoint type
Possible values:
<ul>
<li> "scan" - Scanning volume for fingerprints,
<li> "start" - Starting a storage efficiency
operation,
<li> "check" - Checking for stale data in the
fingerprint database,
<li> "undo" - Undoing storage efficiency on the
volume,
<li> "downgrade" - Storage efficiency operations necessary
for downgrade activity,
<li> "post_transfer" - Starting a storage efficiency operation
post mirror transfer
</ul>
"""
@staticmethod
def get_api_name():
return "sis-chkpoint-op-type"
| class Sischkpointoptype(basestring):
"""
Checkpoint type
Possible values:
<ul>
<li> "scan" - Scanning volume for fingerprints,
<li> "start" - Starting a storage efficiency
operation,
<li> "check" - Checking for stale data in the
fingerprint database,
<li> "undo" - Undoing storage efficiency on the
volume,
<li> "downgrade" - Storage efficiency operations necessary
for downgrade activity,
<li> "post_transfer" - Starting a storage efficiency operation
post mirror transfer
</ul>
"""
@staticmethod
def get_api_name():
return 'sis-chkpoint-op-type' |
l = ["Camera", "Laptop", "Phone", "ipad", "Hard Disk", "Nvidia Graphic 3080 card"]
# sentence = "~~".join(l)
# sentence = "==".join(l)
sentence = "\n".join(l)
print(sentence)
print(type(sentence)) | l = ['Camera', 'Laptop', 'Phone', 'ipad', 'Hard Disk', 'Nvidia Graphic 3080 card']
sentence = '\n'.join(l)
print(sentence)
print(type(sentence)) |
# Linked List, Two Pointers
# Given a singly linked list, determine if it is a palindrome.
#
# Example 1:
#
# Input: 1->2
# Output: false
# Example 2:
#
# Input: 1->2->2->1
# Output: true
# Follow up:
# Could you do it in O(n) time and O(1) space?
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return True
slow, fast = head, head
# get the middle element
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
# reverse the first half of the linked list
p1 = None
p2 = head
while p2 != slow:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
# odd number case
if fast != None:
slow = slow.next
# check first half and second half
while p1 != None and slow != None:
if p1.val != slow.val:
return False
p1 = p1.next
slow = slow.next
return True
| class Solution(object):
def is_palindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return True
(slow, fast) = (head, head)
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
p1 = None
p2 = head
while p2 != slow:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
if fast != None:
slow = slow.next
while p1 != None and slow != None:
if p1.val != slow.val:
return False
p1 = p1.next
slow = slow.next
return True |
# Copyright 2021 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.
class SchemaMode:
Backend = "BE"
Frontend = "FE"
def make_type(typename, required):
if required:
return [typename]
else:
return ["null", typename]
def add_field(schema, name, field_type):
# schema["fields"].append({"name": name, "type": field_type, "default": "NONE"})
schema["fields"].append({"name": name, "type": field_type})
def add_string(schema, name, required):
add_field(schema, name, make_type("string", required))
def add_array(schema, name, typename, required):
add_field(schema, name, make_type({"type": "array", "items": typename}, required))
def add_int64_array(schema, name, required):
add_array(schema, name, "long", required)
def add_float64_array(schema, name, required):
add_array(schema, name, "double", required)
def add_string_array(schema, name, required):
add_array(schema, name, "string", required)
# add_field(schema, name, ["null", {"type": "array", "items": "string"}])
def add_bool(schema, name, required):
add_field(schema, name, make_type("boolean", required))
def add_int64(schema, name, required):
add_field(schema, name, make_type("long", required))
def add_timestamp(schema, name, required):
add_field(schema, name, make_type("string", required))
def add_fields(schema, table_columns):
debug = []
for table_column in table_columns:
ignore_field = False
required = False
if len(table_column) == 4:
func, col, required, ignore_field = table_column
elif len(table_column) == 3:
func, col, required = table_column
else:
func, col = table_column[:2]
debug.append((func, col, required, ignore_field))
if not ignore_field:
func(schema, col, required)
def oms_retail_schema(name, fields):
schema = dict()
schema["namespace"] = "google.retail.oms"
schema["type"] = "record"
schema["name"] = name
schema["fields"] = list()
add_fields(schema, fields)
return schema
def get_product_schema(mode=SchemaMode.Backend):
fields = [
(add_string, "id", True, mode == SchemaMode.Frontend), # NOFE
(add_string, "sku", mode == SchemaMode.Frontend),
(add_string, "title", mode == SchemaMode.Frontend),
(add_string, "name", mode == SchemaMode.Frontend),
(add_string, "description", mode == SchemaMode.Frontend),
(add_string, "pdp_link", mode == SchemaMode.Frontend),
(add_string, "main_image_link"),
(add_string_array, "additional_images"),
(add_int64, "gtin"),
(add_string, "mpn"),
(add_bool, "identifier_exists"),
(add_float64_array, "features", False, mode == SchemaMode.Frontend), # NOFE
(add_float64_array, "memory", False, mode == SchemaMode.Frontend), # NOFE
(add_string_array, "filters"),
(add_string_array, "item_groups", mode == SchemaMode.Frontend),
(add_timestamp, "created_at"),
(add_timestamp, "expires_at"),
(add_timestamp, "last_updated"),
(add_timestamp, "commit_timestamp", True, mode == SchemaMode.Frontend), # NOFE
]
return oms_retail_schema("product", fields)
| class Schemamode:
backend = 'BE'
frontend = 'FE'
def make_type(typename, required):
if required:
return [typename]
else:
return ['null', typename]
def add_field(schema, name, field_type):
schema['fields'].append({'name': name, 'type': field_type})
def add_string(schema, name, required):
add_field(schema, name, make_type('string', required))
def add_array(schema, name, typename, required):
add_field(schema, name, make_type({'type': 'array', 'items': typename}, required))
def add_int64_array(schema, name, required):
add_array(schema, name, 'long', required)
def add_float64_array(schema, name, required):
add_array(schema, name, 'double', required)
def add_string_array(schema, name, required):
add_array(schema, name, 'string', required)
def add_bool(schema, name, required):
add_field(schema, name, make_type('boolean', required))
def add_int64(schema, name, required):
add_field(schema, name, make_type('long', required))
def add_timestamp(schema, name, required):
add_field(schema, name, make_type('string', required))
def add_fields(schema, table_columns):
debug = []
for table_column in table_columns:
ignore_field = False
required = False
if len(table_column) == 4:
(func, col, required, ignore_field) = table_column
elif len(table_column) == 3:
(func, col, required) = table_column
else:
(func, col) = table_column[:2]
debug.append((func, col, required, ignore_field))
if not ignore_field:
func(schema, col, required)
def oms_retail_schema(name, fields):
schema = dict()
schema['namespace'] = 'google.retail.oms'
schema['type'] = 'record'
schema['name'] = name
schema['fields'] = list()
add_fields(schema, fields)
return schema
def get_product_schema(mode=SchemaMode.Backend):
fields = [(add_string, 'id', True, mode == SchemaMode.Frontend), (add_string, 'sku', mode == SchemaMode.Frontend), (add_string, 'title', mode == SchemaMode.Frontend), (add_string, 'name', mode == SchemaMode.Frontend), (add_string, 'description', mode == SchemaMode.Frontend), (add_string, 'pdp_link', mode == SchemaMode.Frontend), (add_string, 'main_image_link'), (add_string_array, 'additional_images'), (add_int64, 'gtin'), (add_string, 'mpn'), (add_bool, 'identifier_exists'), (add_float64_array, 'features', False, mode == SchemaMode.Frontend), (add_float64_array, 'memory', False, mode == SchemaMode.Frontend), (add_string_array, 'filters'), (add_string_array, 'item_groups', mode == SchemaMode.Frontend), (add_timestamp, 'created_at'), (add_timestamp, 'expires_at'), (add_timestamp, 'last_updated'), (add_timestamp, 'commit_timestamp', True, mode == SchemaMode.Frontend)]
return oms_retail_schema('product', fields) |
"""
Module to handle universal/general constants used across files.
"""
################################################################################
# Constants #
################################################################################
# GENERAL CONSTANTS:
VERY_SMALL_NUMBER = 1e-31
INF = 1e20
_PAD_TOKEN = '#pad#'
# _PAD_TOKEN = '<P>'
_UNK_TOKEN = '<unk>'
_SOS_TOKEN = '<s>'
_EOS_TOKEN = '</s>'
# LOG FILES ##
_CONFIG_FILE = "config.json"
_SAVED_WEIGHTS_FILE = "params.saved"
_PREDICTION_FILE = "test_pred.txt"
_REFERENCE_FILE = "test_ref.txt"
| """
Module to handle universal/general constants used across files.
"""
very_small_number = 1e-31
inf = 1e+20
_pad_token = '#pad#'
_unk_token = '<unk>'
_sos_token = '<s>'
_eos_token = '</s>'
_config_file = 'config.json'
_saved_weights_file = 'params.saved'
_prediction_file = 'test_pred.txt'
_reference_file = 'test_ref.txt' |
def test_catch_server__get(testdir):
testdir.makepyfile(
"""
import urllib.request
def test_get(catch_server):
url = "http://{cs.host}:{cs.port}/get_it".format(cs=catch_server)
request = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(request) as response:
assert response.status == 200
assert response.read() == b"OK"
assert catch_server.requests == [
{"method": "GET", "path": "/get_it", "data": b""},
]
"""
)
result = testdir.runpytest("-v")
result.stdout.fnmatch_lines(["*::test_get PASSED*"])
assert result.ret == 0
def test_catch_server__post(testdir):
testdir.makepyfile(
"""
import urllib.request
def test_post(catch_server):
url = "http://{cs.host}:{cs.port}/post_it".format(cs=catch_server)
request = urllib.request.Request(url, method="POST", data=b"something")
with urllib.request.urlopen(request) as response:
assert response.status == 200
assert response.read() == b"OK"
assert catch_server.requests == [
{"method": "POST", "path": "/post_it", "data": b"something"},
]
"""
)
result = testdir.runpytest("-v")
result.stdout.fnmatch_lines(["*::test_post PASSED*"])
assert result.ret == 0
def test_catch_server__put(testdir):
testdir.makepyfile(
"""
import urllib.request
def test_put(catch_server):
url = "http://{cs.host}:{cs.port}/put_it".format(cs=catch_server)
request = urllib.request.Request(url, method="PUT", data=b"other data")
with urllib.request.urlopen(request) as response:
assert response.status == 200
assert response.read() == b"OK"
assert catch_server.requests == [
{"method": "PUT", "path": "/put_it", "data": b"other data"},
]
"""
)
result = testdir.runpytest("-v")
result.stdout.fnmatch_lines(["*::test_put PASSED*"])
assert result.ret == 0
def test_catch_server__patch(testdir):
testdir.makepyfile(
"""
import urllib.request
def test_patch(catch_server):
url = "http://{cs.host}:{cs.port}/patch_it".format(cs=catch_server)
request = urllib.request.Request(url, method="PATCH", data=b'{"x": 42}')
with urllib.request.urlopen(request) as response:
assert response.status == 200
assert response.read() == b"OK"
assert catch_server.requests == [
{"method": "PATCH", "path": "/patch_it", "data": b'{"x": 42}'},
]
"""
)
result = testdir.runpytest("-v")
result.stdout.fnmatch_lines(["*::test_patch PASSED*"])
assert result.ret == 0
def test_catch_server__delete(testdir):
testdir.makepyfile(
"""
import urllib.request
def test_delete(catch_server):
url = "http://{cs.host}:{cs.port}/delete_it".format(cs=catch_server)
request = urllib.request.Request(url, method="DELETE")
with urllib.request.urlopen(request) as response:
assert response.status == 200
assert response.read() == b"OK"
assert catch_server.requests == [
{"method": "DELETE", "path": "/delete_it", "data": b""},
]
"""
)
result = testdir.runpytest("-v")
result.stdout.fnmatch_lines(["*::test_delete PASSED*"])
assert result.ret == 0
def test_catch_server__multiple_requests(testdir):
testdir.makepyfile(
"""
import urllib.request
def test_multiple_requests(catch_server):
for n, method in enumerate(["PUT", "POST", "PATCH"]):
url = "http://{cs.host}:{cs.port}/req_{n}".format(cs=catch_server, n=n)
data = "{} {}".format(n, method).encode("utf-8")
request = urllib.request.Request(url, method=method, data=data)
with urllib.request.urlopen(request) as response:
assert response.status == 200
assert response.read() == b"OK"
assert catch_server.requests == [
{"method": "PUT", "path": "/req_0", "data": b"0 PUT"},
{"method": "POST", "path": "/req_1", "data": b"1 POST"},
{"method": "PATCH", "path": "/req_2", "data": b"2 PATCH"},
]
"""
)
result = testdir.runpytest("-v")
result.stdout.fnmatch_lines(["*::test_multiple_requests PASSED*"])
assert result.ret == 0
| def test_catch_server__get(testdir):
testdir.makepyfile('\n import urllib.request\n\n def test_get(catch_server):\n url = "http://{cs.host}:{cs.port}/get_it".format(cs=catch_server)\n request = urllib.request.Request(url, method="GET")\n\n with urllib.request.urlopen(request) as response:\n assert response.status == 200\n assert response.read() == b"OK"\n\n assert catch_server.requests == [\n {"method": "GET", "path": "/get_it", "data": b""},\n ]\n ')
result = testdir.runpytest('-v')
result.stdout.fnmatch_lines(['*::test_get PASSED*'])
assert result.ret == 0
def test_catch_server__post(testdir):
testdir.makepyfile('\n import urllib.request\n\n def test_post(catch_server):\n url = "http://{cs.host}:{cs.port}/post_it".format(cs=catch_server)\n request = urllib.request.Request(url, method="POST", data=b"something")\n\n with urllib.request.urlopen(request) as response:\n assert response.status == 200\n assert response.read() == b"OK"\n\n assert catch_server.requests == [\n {"method": "POST", "path": "/post_it", "data": b"something"},\n ]\n ')
result = testdir.runpytest('-v')
result.stdout.fnmatch_lines(['*::test_post PASSED*'])
assert result.ret == 0
def test_catch_server__put(testdir):
testdir.makepyfile('\n import urllib.request\n\n def test_put(catch_server):\n url = "http://{cs.host}:{cs.port}/put_it".format(cs=catch_server)\n request = urllib.request.Request(url, method="PUT", data=b"other data")\n\n with urllib.request.urlopen(request) as response:\n assert response.status == 200\n assert response.read() == b"OK"\n\n assert catch_server.requests == [\n {"method": "PUT", "path": "/put_it", "data": b"other data"},\n ]\n ')
result = testdir.runpytest('-v')
result.stdout.fnmatch_lines(['*::test_put PASSED*'])
assert result.ret == 0
def test_catch_server__patch(testdir):
testdir.makepyfile('\n import urllib.request\n\n def test_patch(catch_server):\n url = "http://{cs.host}:{cs.port}/patch_it".format(cs=catch_server)\n request = urllib.request.Request(url, method="PATCH", data=b\'{"x": 42}\')\n\n with urllib.request.urlopen(request) as response:\n assert response.status == 200\n assert response.read() == b"OK"\n\n assert catch_server.requests == [\n {"method": "PATCH", "path": "/patch_it", "data": b\'{"x": 42}\'},\n ]\n ')
result = testdir.runpytest('-v')
result.stdout.fnmatch_lines(['*::test_patch PASSED*'])
assert result.ret == 0
def test_catch_server__delete(testdir):
testdir.makepyfile('\n import urllib.request\n\n def test_delete(catch_server):\n url = "http://{cs.host}:{cs.port}/delete_it".format(cs=catch_server)\n request = urllib.request.Request(url, method="DELETE")\n\n with urllib.request.urlopen(request) as response:\n assert response.status == 200\n assert response.read() == b"OK"\n\n assert catch_server.requests == [\n {"method": "DELETE", "path": "/delete_it", "data": b""},\n ]\n ')
result = testdir.runpytest('-v')
result.stdout.fnmatch_lines(['*::test_delete PASSED*'])
assert result.ret == 0
def test_catch_server__multiple_requests(testdir):
testdir.makepyfile('\n import urllib.request\n\n def test_multiple_requests(catch_server):\n for n, method in enumerate(["PUT", "POST", "PATCH"]):\n url = "http://{cs.host}:{cs.port}/req_{n}".format(cs=catch_server, n=n)\n data = "{} {}".format(n, method).encode("utf-8")\n request = urllib.request.Request(url, method=method, data=data)\n\n with urllib.request.urlopen(request) as response:\n assert response.status == 200\n assert response.read() == b"OK"\n\n assert catch_server.requests == [\n {"method": "PUT", "path": "/req_0", "data": b"0 PUT"},\n {"method": "POST", "path": "/req_1", "data": b"1 POST"},\n {"method": "PATCH", "path": "/req_2", "data": b"2 PATCH"},\n ]\n ')
result = testdir.runpytest('-v')
result.stdout.fnmatch_lines(['*::test_multiple_requests PASSED*'])
assert result.ret == 0 |
# Roll the Dice #
# November 17, 2018
# By Robin Nash
n = int(input())
m = int(input())
if n > 10:
n = 9
if m > 10:
m = 9
ways = 0
for n in range (1,n+1):
for m in range(1,m+1):
if n + m == 10:
ways+=1
if ways == 1:
print("There is 1 way to get the sum 10.")
else:
print("There are",ways,"ways to get the sum 10.")
#1542488930.0 | n = int(input())
m = int(input())
if n > 10:
n = 9
if m > 10:
m = 9
ways = 0
for n in range(1, n + 1):
for m in range(1, m + 1):
if n + m == 10:
ways += 1
if ways == 1:
print('There is 1 way to get the sum 10.')
else:
print('There are', ways, 'ways to get the sum 10.') |
Carros = ['HRV', 'Polo', 'Jetta', 'Palio', 'Fusca']
itCarros = iter(Carros)
while itCarros:
try:
print(next(itCarros))
except StopIteration:
print('Fim da Lista.')
break | carros = ['HRV', 'Polo', 'Jetta', 'Palio', 'Fusca']
it_carros = iter(Carros)
while itCarros:
try:
print(next(itCarros))
except StopIteration:
print('Fim da Lista.')
break |
def default_colors(n):
n = max(n, 8)
clist = ["#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e", "#e6ab02",
"#a6761d", "#666666"]
return clist[:n]
| def default_colors(n):
n = max(n, 8)
clist = ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666']
return clist[:n] |
def nth_fibonacci_using_recursion(n):
if n < 0:
raise ValueError("n should be a positive number or zero")
else:
if n == 1:
return 0
elif n == 2:
return 1
else:
return nth_fibonacci_using_recursion(n - 2) + nth_fibonacci_using_recursion(n - 1)
# Implement the following function using iteration i.e. loop
# You can use any loop constructs
def nth_fibonacci_using_iteration(n):
# You can completely remove the following code if needed
if n < 0:
raise ValueError("n should be a positive number or zero")
elif n == 1:
return 0
elif n == 2:
return 1
elif n > 2:
i=0
first_number = 0
second_number = 1
sum = second_number
for i in range(n-2):
sum = first_number + second_number
first_number = second_number
second_number= sum
return sum
| def nth_fibonacci_using_recursion(n):
if n < 0:
raise value_error('n should be a positive number or zero')
elif n == 1:
return 0
elif n == 2:
return 1
else:
return nth_fibonacci_using_recursion(n - 2) + nth_fibonacci_using_recursion(n - 1)
def nth_fibonacci_using_iteration(n):
if n < 0:
raise value_error('n should be a positive number or zero')
elif n == 1:
return 0
elif n == 2:
return 1
elif n > 2:
i = 0
first_number = 0
second_number = 1
sum = second_number
for i in range(n - 2):
sum = first_number + second_number
first_number = second_number
second_number = sum
return sum |
class OpenInterest:
def __init__(self):
self.symbol = ""
self.openInterest = 0.0
@staticmethod
def json_parse(json_data):
result = OpenInterest()
result.symbol = json_data.get_string("symbol")
result.openInterest = json_data.get_float("openInterest")
return result
| class Openinterest:
def __init__(self):
self.symbol = ''
self.openInterest = 0.0
@staticmethod
def json_parse(json_data):
result = open_interest()
result.symbol = json_data.get_string('symbol')
result.openInterest = json_data.get_float('openInterest')
return result |
with open("input.txt") as input_file:
time = int(input_file.readline().strip())
busses = input_file.readline().strip().split(",")
def departures(bus):
multiplier = 0
while True:
multiplier += 1
yield multiplier * bus
def next_after(bus, time):
for departure in departures(bus):
if departure >= time:
return departure
future_departures = []
for bus in busses:
if bus == "x":
continue
bus = int(bus)
future_departures.append((next_after(bus, time), bus))
departure, bus = min(future_departures)
print((departure - time) * bus)
| with open('input.txt') as input_file:
time = int(input_file.readline().strip())
busses = input_file.readline().strip().split(',')
def departures(bus):
multiplier = 0
while True:
multiplier += 1
yield (multiplier * bus)
def next_after(bus, time):
for departure in departures(bus):
if departure >= time:
return departure
future_departures = []
for bus in busses:
if bus == 'x':
continue
bus = int(bus)
future_departures.append((next_after(bus, time), bus))
(departure, bus) = min(future_departures)
print((departure - time) * bus) |
# -*- coding: utf-8 -*-
maior = -1
index_maior = -1
for i in range(1, 101):
n = int(input())
if n > maior:
maior = n
index_maior = i
print(maior)
print(index_maior)
| maior = -1
index_maior = -1
for i in range(1, 101):
n = int(input())
if n > maior:
maior = n
index_maior = i
print(maior)
print(index_maior) |
# This sample tests a particularly difficult set of dependent
# assignments that involve tuple packing and unpacking.
# pyright: strict
v1 = ""
v3 = ""
v2, _ = v1, v3
v4 = v2
for _ in range(1):
v1 = v4
v2, v3 = v1, ""
| v1 = ''
v3 = ''
(v2, _) = (v1, v3)
v4 = v2
for _ in range(1):
v1 = v4
(v2, v3) = (v1, '') |
class DNABattleCell:
COMPONENT_CODE = 21
def __init__(self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
def setWidth(self, width):
self.width = width
def setHeight(self, height):
self.height = height
def setWidthHeight(self, width, height):
self.setWidth(width)
self.setHeight(height)
def setPos(self, pos):
self.pos = pos
| class Dnabattlecell:
component_code = 21
def __init__(self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def set_width_height(self, width, height):
self.setWidth(width)
self.setHeight(height)
def set_pos(self, pos):
self.pos = pos |
def median(a):
a = sorted(a)
list_length = len(a)
num = list_length//2
if list_length % 2 == 0:
median_num = (a[num] + a[num + 1])/2
else:
median_num = a[num]
return median_num
| def median(a):
a = sorted(a)
list_length = len(a)
num = list_length // 2
if list_length % 2 == 0:
median_num = (a[num] + a[num + 1]) / 2
else:
median_num = a[num]
return median_num |
class DeviceGroup:
def __init__(self, name):
self.name = name
self.devices = []
def addDevice(self, newDevice):
self.devices.append(newDevice)
# Just thinking through how I want the program to work.
# A diskgroup should be initialized once every time the service is started. This way it doesn't have to keep
# reading from the json file.
# If the user adds/modifies disks.json, the simple way to update the ipmifan instance would be to just restart
# the systemd service.
# Diskgroups will basically be defined in the disks.json file. A diskgroup json object will be created, and all
# of its child disks will be defined under it.
# Will need a constructor function that goes through the disks.json file to extract all disks from there groups and add them to an instance.
# OR, could define a static factory method that reads through the file and returns an array of DiskGroup objects.
# Maybe a factory method that grabs the json, and for each json diskgroup object defined, create a new diskgroup object,
# this constructor would just accept the json, and these instances would just read the serial numbers from the json objects,
# rather than using raw data structures to avoid complexity.
# Would it be practical to instead generalize this?
# I.e., make a devices.json file where all devices are defined.
# A disk group is defined with temperature thresholds, etc.
# Here's another idea:
# While I think that recording temperature data should be easy enough, it would be nice to have these endpoints made available to me in
# case I'd ever want to record them in something like prometheus. Soooo, while I could build out a little flask application that would serve up temperature data,
# and build adapters for different data providers (that work via the command line), might just be easier to set that up with netdata.
# THEN, just build out a fan controller script that uses that data to control the script.
# The only reason that this is a little scary is because it depends on a large application like netdata running. Now granted, if I'm building up my own
# shaky service, you could make that same argument, but the controller script could always just default to MAX fan values if it can't contact it's data provider.
# Maybe that's what I can do: I can build out a data provider that collects data for all of the devices that you want to keep track of. So, here's how it's laid out:
# Data Provider Microservice
# - Data provider flask application that serves up json sensor data for various devices.
# - Data provider will have no knowledge of the actual machine it's on, it'll just execute commands to get sensor data.
# - The Data provider will NOT have hard-coded cli commands to get sensor data, but will rather have various PROVIDER-ADAPTERS (json files)
# that will specificy a command to be run in order to get the type of data that they're meant for.
# - In a more advanced application, they coulld also provide meta-data about the data they're returning. These could be interpretted by the controller/receiver
# based on how they're being used.
# This way, when the controller script requests data, it will send the provider service a json request that will specify the type of provider to use.
# This endpoint will then grab the command from the corresponding provider-adapter specified in the GET request and will return the data provided by the specified command.
# - In a more (advanced) netdata-style implementation, it would also be cool to have an endpoint that enables the tracking of certain devices (that the consumer program (like ipmifan))
# data in something like a mongo database. This way, there would be more uniform access to both current and past readings.
# ------------------------------------
# OR, MOST SIMPLY: DataProviderSource object entries added to a "source.json" file. Basically, these entries would just maintain the commands needed to return the desired data.
# Then, the controller just has to hit a generic endpoint on the provider where they specify the name of the Source entry, and they get the data from the commands of that entry back.
# OR, the controller requests data (with the commands as the GET json), and then the provider returns the results. Again, not sure which is better.
# ------------------------------------
# THIS COULD ALSO BE IMPLEMENTED AS AN MQTT application where these values are published on topics. OR some data-providers could just constantly broadcast their responses over mqtt as well.
# IPMI-FAN controller Microservice
# - This service will just implement the logic outlined in my notebook regarding how to set fan speeds, but ultimately at that point will just be
# a primitive consumer of the data from the Data Provider Microservice.
# - This could just be one of many services that get their data from the provider microservice.
# - Long term, it would be nice to implement modules that define the same functions for retrieving the sensor data that they need, but just from different sources.
# - In other words, define a "DataSource" interface that is unique to this controller application that requires the classes to implement methods for retrieving
# (in the same format) hdd temps, cpu temps, ambient temps, etc., etc.
# - Based on some configurable value (maybe in a yaml file along with other options), this controller can just instantiate a data-provider according to where
# it's getting its data from.
#
# - Additionally, this program will have a devices.json file that specifies all of the different disk groups, cpus, sensors, etc. that the user wishes to monitor
# temperatures of--in this case to control fan speeds.
# device_types.json will contain various types of devices and the general form of the commands needed to extract the data from them.
# Will also include a device type "custom" that will accept custom commands in case it requires specialized commands due to some issue.]
# I may also include
# devices.json will contain actual device definitions that allow the user to specify the actual devices (and any relevant details needed).
# Upon initialization, the data provider will take the devices specified in devices.json and load them into a dictionary.
# Subsequently, it will match the serial numbers of the drives to their current /dev/ location and store that in a new dictionary field it creates.
# Some vocabulary for the system:
# device_group: A device group defines the group of devices whose temperatures are all factored in to calculate the overall temperature / state of that group.
# - This is useful, for instanace, for a group of hard drives, as you might not want to just look at the temperature of each drive all the time,
# (assuming no extreme conditions for one device) but rather just the overall state of that group.
#
# zone: A zone is what device_groups and devices are assigned to that fans control the temperature of. Fans, for instance, are assigned to a particular zone.
# The fans that are assigned to a particular zone then are controlled according to the temperatures/states of the device_groups that have been
# assigned to that zone.
# Zones exist because, while you could assign fans to multiple device groups, you don't necessarily want the desired fan speed required for one
# device group (say CPUs) to fight over the fan control.
# While I could implement some logic to just take the highest fan speed calculated across the device_groups, I think it would be cleaner to loop through
# zones and set the fans in that zone.
# Still more efficient though to calculate all of the device_groups temps/state all in a row, as if you do it by zone, in theory a device_group could
# be assigned to multiple zones, so you'd be calculating it unecessarily more than once. | class Devicegroup:
def __init__(self, name):
self.name = name
self.devices = []
def add_device(self, newDevice):
self.devices.append(newDevice) |
#!/usr/bin/env python3
def read_text():
"""Reads a line of text, stripping whitespace."""
return input().strip()
def distance(s, t):
"""Wagner-Fischer algorithm"""
if len(s) < len(t):
s, t = t, s
pre = [None] * (len(t) + 1)
cur = list(range(len(pre)))
for i, sc in enumerate(s, 1):
pre, cur = cur, pre
cur[0] = i
for j, tc in enumerate(t, 1):
if sc == tc:
cur[j] = pre[j - 1]
else:
cur[j] = 1 + min(cur[j - 1], pre[j], pre[j - 1])
return cur[-1]
for _ in range(int(input())):
print(distance(read_text(), read_text()))
| def read_text():
"""Reads a line of text, stripping whitespace."""
return input().strip()
def distance(s, t):
"""Wagner-Fischer algorithm"""
if len(s) < len(t):
(s, t) = (t, s)
pre = [None] * (len(t) + 1)
cur = list(range(len(pre)))
for (i, sc) in enumerate(s, 1):
(pre, cur) = (cur, pre)
cur[0] = i
for (j, tc) in enumerate(t, 1):
if sc == tc:
cur[j] = pre[j - 1]
else:
cur[j] = 1 + min(cur[j - 1], pre[j], pre[j - 1])
return cur[-1]
for _ in range(int(input())):
print(distance(read_text(), read_text())) |
# -*- coding: utf-8 -*-
"""
665. Non-decreasing Array
Given an array nums with n integers, your task is to check if it could become non-decreasing
by modifying at most 1 element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Constraints:
1 <= n <= 10 ^ 4
- 10 ^ 5 <= nums[i] <= 10 ^ 5
"""
class Solution:
def checkPossibility(self, nums):
ind_set = set()
for ind in range(1, len(nums)):
if nums[ind] - nums[ind - 1] < 0:
ind_set.add(ind)
if not ind_set:
return True
elif len(ind_set) > 1:
return False
else:
wrong_ind = ind_set.pop()
if wrong_ind == 1 or wrong_ind == len(nums) - 1:
return True
else:
return nums[wrong_ind] >= nums[wrong_ind - 2] or nums[wrong_ind + 1] >= nums[wrong_ind - 1]
| """
665. Non-decreasing Array
Given an array nums with n integers, your task is to check if it could become non-decreasing
by modifying at most 1 element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Constraints:
1 <= n <= 10 ^ 4
- 10 ^ 5 <= nums[i] <= 10 ^ 5
"""
class Solution:
def check_possibility(self, nums):
ind_set = set()
for ind in range(1, len(nums)):
if nums[ind] - nums[ind - 1] < 0:
ind_set.add(ind)
if not ind_set:
return True
elif len(ind_set) > 1:
return False
else:
wrong_ind = ind_set.pop()
if wrong_ind == 1 or wrong_ind == len(nums) - 1:
return True
else:
return nums[wrong_ind] >= nums[wrong_ind - 2] or nums[wrong_ind + 1] >= nums[wrong_ind - 1] |
# -*- coding: utf-8 -*-
USER_ROLE = {
'USER': 0,
'MODERATOR': 1,
'ADMINISTRATOR': 2,
} | user_role = {'USER': 0, 'MODERATOR': 1, 'ADMINISTRATOR': 2} |
a = 1
print("a_module: Hi from my_package/" + __name__ + ".py!")
if __name__ == "__main__":
print("a_module: I was invoked from a script.")
else:
print("a_module: I was invoked from a Pyton module (probably using 'import').")
print("a_module: My name is =", __name__)
| a = 1
print('a_module: Hi from my_package/' + __name__ + '.py!')
if __name__ == '__main__':
print('a_module: I was invoked from a script.')
else:
print("a_module: I was invoked from a Pyton module (probably using 'import').")
print('a_module: My name is =', __name__) |
#
# PySNMP MIB module ZYXEL-MES2110-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-MES2110-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:50:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
enterprises, NotificationType, NotificationType, Bits, Gauge32, ObjectIdentity, ModuleIdentity, Counter64, Unsigned32, MibIdentifier, iso, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, IpAddress, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "NotificationType", "NotificationType", "Bits", "Gauge32", "ObjectIdentity", "ModuleIdentity", "Counter64", "Unsigned32", "MibIdentifier", "iso", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "IpAddress", "Counter32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
zyxel = MibIdentifier((1, 3, 6, 1, 4, 1, 890))
products = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1))
accessSwitch = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 5))
esSeries = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8))
mes2110_MIB = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110))
mes2110_SystemInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 1))
mes2110_Mgt = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2))
mes2110_Port = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3))
mes2110_Traps = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4))
mes2110_SystemContact = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mes2110_SystemContact.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_SystemContact.setDescription('The contact person of this system.')
mes2110_SystemName = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mes2110_SystemName.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_SystemName.setDescription('The name of this system.')
mes2110_SystemLocation = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mes2110_SystemLocation.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_SystemLocation.setDescription('The location of this system.')
mes2110_MgtSnmpVer = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mes2110_MgtSnmpVer.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_MgtSnmpVer.setDescription('This object specifies the SNMP version(s) supported by the module.')
mes2110_MgtModPN = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mes2110_MgtModPN.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_MgtModPN.setDescription('This object specifies the managemnt module part number.')
mes2110_MgtModSN = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mes2110_MgtModSN.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_MgtModSN.setDescription('This object specifies the managemnt module serial number.')
mes2110_MgtModManuDate = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mes2110_MgtModManuDate.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_MgtModManuDate.setDescription('This object specifies the management module manufacture date.')
mes2110_MgtModRev = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mes2110_MgtModRev.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_MgtModRev.setDescription('This object specifies the managemnt module fireware revision number.')
mes2110_MgtModDesc = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mes2110_MgtModDesc.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_MgtModDesc.setDescription('This object describes the management module.')
communityStringRO = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: communityStringRO.setStatus('mandatory')
if mibBuilder.loadTexts: communityStringRO.setDescription('This is the community string required to authenticate a read access to all MIB objects except for the read-write objects.')
communityStringRW = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: communityStringRW.setStatus('mandatory')
if mibBuilder.loadTexts: communityStringRW.setDescription('This is the community string required to authenticate a read or write access to all MIB objects.')
defaultGateway = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 9), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: defaultGateway.setStatus('mandatory')
if mibBuilder.loadTexts: defaultGateway.setDescription('This object specifies the default gateway address.')
interfaceIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 10), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: interfaceIpAddress.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceIpAddress.setDescription('This object identifies the IP address of the MIB-II interface on the management module.')
interfaceSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 11), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: interfaceSubnetMask.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceSubnetMask.setDescription('This object specifies the subnet mask associated with the interface address of the module.')
mgtStp = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mgtStp.setStatus('mandatory')
if mibBuilder.loadTexts: mgtStp.setDescription('This object specifies the switch STP function.')
trapManagerTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13), )
if mibBuilder.loadTexts: trapManagerTable.setStatus('mandatory')
if mibBuilder.loadTexts: trapManagerTable.setDescription('This object contains the entries of Network Management Systems to which traps will be sent.')
trapManagerTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1), ).setIndexNames((0, "ZYXEL-MES2110-MIB", "trapManagerIndex"))
if mibBuilder.loadTexts: trapManagerTableEntry.setStatus('mandatory')
if mibBuilder.loadTexts: trapManagerTableEntry.setDescription('This object specifies an entry in the trap manager table.')
trapManagerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: trapManagerIndex.setStatus('mandatory')
trapManagerIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: trapManagerIpAddress.setStatus('mandatory')
if mibBuilder.loadTexts: trapManagerIpAddress.setDescription('This object specifies the IP address of the destination of a network management system to which traps will be sent.')
trapManagerName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: trapManagerName.setStatus('mandatory')
if mibBuilder.loadTexts: trapManagerName.setDescription('This object identifies the name of the destination of a network management system to which traps will be sent.')
trapManagerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: trapManagerStatus.setStatus('mandatory')
if mibBuilder.loadTexts: trapManagerStatus.setDescription('This object specifies a trap manager entry status in the trap manager table. (1) -- Enabled or (2) -- Disabled.')
mes2110_PortTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1), )
if mibBuilder.loadTexts: mes2110_PortTable.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_PortTable.setDescription('This object lists port entries on the mes2110 module.')
mes2110_PortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1), ).setIndexNames((0, "ZYXEL-MES2110-MIB", "portIndex"))
if mibBuilder.loadTexts: mes2110_PortEntry.setStatus('mandatory')
if mibBuilder.loadTexts: mes2110_PortEntry.setDescription('This object specifies a port entry in the port table, mes2110_PortTable. The port entry contains the information about a single port.')
portIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 256))).setMaxAccess("readonly")
if mibBuilder.loadTexts: portIndex.setStatus('mandatory')
if mibBuilder.loadTexts: portIndex.setDescription('This object is the port index, which uniquely identifies a port. It ranges from 1 to the total port number.')
portName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portName.setStatus('mandatory')
if mibBuilder.loadTexts: portName.setDescription('This object specifies the user defined descriptive name for the port.')
portAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 4))).clone(namedValues=NamedValues(("disable", 1), ("enable", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portAdminStatus.setStatus('mandatory')
if mibBuilder.loadTexts: portAdminStatus.setDescription('This object specifies the port admin state. Setting this object to disable(1) disables the port. Setting this object to enable(4) enables the port.')
portLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("down", 1), ("up", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: portLinkStatus.setStatus('mandatory')
if mibBuilder.loadTexts: portLinkStatus.setDescription('This object indicates the link status attached to the port.')
portSpeedMode = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("speed-10M", 1), ("speed-100M", 2), ("speed-1000M", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portSpeedMode.setStatus('mandatory')
if mibBuilder.loadTexts: portSpeedMode.setDescription('This object specifies the speed of the port, 10M(1) or 100M(2) or 100M(3).')
portDuplexMode = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("half", 1), ("full", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portDuplexMode.setStatus('mandatory')
if mibBuilder.loadTexts: portDuplexMode.setDescription('This object specifies the duplex mode of the port, half duplex(1) or full duplex(2).')
portAuto = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portAuto.setStatus('mandatory')
if mibBuilder.loadTexts: portAuto.setDescription('This object specifies the auto negotiation status of the port.')
portFfc = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portFfc.setStatus('mandatory')
if mibBuilder.loadTexts: portFfc.setDescription('This object specifies the force flow control status of a port.')
almColdStart = NotificationType((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0,1))
if mibBuilder.loadTexts: almColdStart.setDescription('This trap is sent when the system is started from power down.')
almWarmStart = NotificationType((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0,2))
if mibBuilder.loadTexts: almWarmStart.setDescription('This trap is sent when the system is reset.')
almLinkUp = NotificationType((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0,3))
if mibBuilder.loadTexts: almLinkUp.setDescription("This trap is sent when the link associated with the port indexed 'portIndex' changes its 'portLinkStatus' from down(2) to up(1).")
almLinkDown = NotificationType((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0,4))
if mibBuilder.loadTexts: almLinkDown.setDescription("This trap is sent when the link associated with the port indexed 'portIndex' changes its 'portLinkStatus' from up(1) to down(2).")
almConfChange = NotificationType((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0,5))
if mibBuilder.loadTexts: almConfChange.setDescription('This trap is sent when the system configuration has been changed.')
mibBuilder.exportSymbols("ZYXEL-MES2110-MIB", mes2110_MgtSnmpVer=mes2110_MgtSnmpVer, portSpeedMode=portSpeedMode, communityStringRW=communityStringRW, portName=portName, trapManagerIpAddress=trapManagerIpAddress, accessSwitch=accessSwitch, mes2110_MgtModDesc=mes2110_MgtModDesc, mes2110_SystemInfo=mes2110_SystemInfo, trapManagerTable=trapManagerTable, trapManagerIndex=trapManagerIndex, mes2110_SystemContact=mes2110_SystemContact, portIndex=portIndex, communityStringRO=communityStringRO, portLinkStatus=portLinkStatus, esSeries=esSeries, mes2110_MgtModManuDate=mes2110_MgtModManuDate, mes2110_MgtModPN=mes2110_MgtModPN, mes2110_SystemName=mes2110_SystemName, trapManagerName=trapManagerName, almLinkDown=almLinkDown, mes2110_PortTable=mes2110_PortTable, almWarmStart=almWarmStart, mgtStp=mgtStp, trapManagerStatus=trapManagerStatus, zyxel=zyxel, mes2110_Port=mes2110_Port, almConfChange=almConfChange, almLinkUp=almLinkUp, portAuto=portAuto, mes2110_MgtModSN=mes2110_MgtModSN, trapManagerTableEntry=trapManagerTableEntry, mes2110_Traps=mes2110_Traps, mes2110_MIB=mes2110_MIB, defaultGateway=defaultGateway, portFfc=portFfc, products=products, almColdStart=almColdStart, mes2110_Mgt=mes2110_Mgt, portAdminStatus=portAdminStatus, mes2110_MgtModRev=mes2110_MgtModRev, interfaceIpAddress=interfaceIpAddress, mes2110_SystemLocation=mes2110_SystemLocation, mes2110_PortEntry=mes2110_PortEntry, portDuplexMode=portDuplexMode, interfaceSubnetMask=interfaceSubnetMask)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(enterprises, notification_type, notification_type, bits, gauge32, object_identity, module_identity, counter64, unsigned32, mib_identifier, iso, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, integer32, ip_address, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'enterprises', 'NotificationType', 'NotificationType', 'Bits', 'Gauge32', 'ObjectIdentity', 'ModuleIdentity', 'Counter64', 'Unsigned32', 'MibIdentifier', 'iso', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32', 'IpAddress', 'Counter32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
zyxel = mib_identifier((1, 3, 6, 1, 4, 1, 890))
products = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1))
access_switch = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 5))
es_series = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8))
mes2110_mib = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110))
mes2110__system_info = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 1))
mes2110__mgt = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2))
mes2110__port = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3))
mes2110__traps = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4))
mes2110__system_contact = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mes2110_SystemContact.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_SystemContact.setDescription('The contact person of this system.')
mes2110__system_name = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mes2110_SystemName.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_SystemName.setDescription('The name of this system.')
mes2110__system_location = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(1, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mes2110_SystemLocation.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_SystemLocation.setDescription('The location of this system.')
mes2110__mgt_snmp_ver = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('v1', 1), ('v2c', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mes2110_MgtSnmpVer.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_MgtSnmpVer.setDescription('This object specifies the SNMP version(s) supported by the module.')
mes2110__mgt_mod_pn = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mes2110_MgtModPN.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_MgtModPN.setDescription('This object specifies the managemnt module part number.')
mes2110__mgt_mod_sn = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 3), display_string().subtype(subtypeSpec=value_size_constraint(1, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mes2110_MgtModSN.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_MgtModSN.setDescription('This object specifies the managemnt module serial number.')
mes2110__mgt_mod_manu_date = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 4), display_string().subtype(subtypeSpec=value_size_constraint(1, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mes2110_MgtModManuDate.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_MgtModManuDate.setDescription('This object specifies the management module manufacture date.')
mes2110__mgt_mod_rev = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 5), display_string().subtype(subtypeSpec=value_size_constraint(1, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mes2110_MgtModRev.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_MgtModRev.setDescription('This object specifies the managemnt module fireware revision number.')
mes2110__mgt_mod_desc = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 6), display_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mes2110_MgtModDesc.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_MgtModDesc.setDescription('This object describes the management module.')
community_string_ro = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 7), display_string().subtype(subtypeSpec=value_size_constraint(1, 32))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
communityStringRO.setStatus('mandatory')
if mibBuilder.loadTexts:
communityStringRO.setDescription('This is the community string required to authenticate a read access to all MIB objects except for the read-write objects.')
community_string_rw = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 8), display_string().subtype(subtypeSpec=value_size_constraint(1, 32))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
communityStringRW.setStatus('mandatory')
if mibBuilder.loadTexts:
communityStringRW.setDescription('This is the community string required to authenticate a read or write access to all MIB objects.')
default_gateway = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 9), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
defaultGateway.setStatus('mandatory')
if mibBuilder.loadTexts:
defaultGateway.setDescription('This object specifies the default gateway address.')
interface_ip_address = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 10), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
interfaceIpAddress.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceIpAddress.setDescription('This object identifies the IP address of the MIB-II interface on the management module.')
interface_subnet_mask = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 11), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
interfaceSubnetMask.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceSubnetMask.setDescription('This object specifies the subnet mask associated with the interface address of the module.')
mgt_stp = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mgtStp.setStatus('mandatory')
if mibBuilder.loadTexts:
mgtStp.setDescription('This object specifies the switch STP function.')
trap_manager_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13))
if mibBuilder.loadTexts:
trapManagerTable.setStatus('mandatory')
if mibBuilder.loadTexts:
trapManagerTable.setDescription('This object contains the entries of Network Management Systems to which traps will be sent.')
trap_manager_table_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1)).setIndexNames((0, 'ZYXEL-MES2110-MIB', 'trapManagerIndex'))
if mibBuilder.loadTexts:
trapManagerTableEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
trapManagerTableEntry.setDescription('This object specifies an entry in the trap manager table.')
trap_manager_index = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
trapManagerIndex.setStatus('mandatory')
trap_manager_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1, 2), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
trapManagerIpAddress.setStatus('mandatory')
if mibBuilder.loadTexts:
trapManagerIpAddress.setDescription('This object specifies the IP address of the destination of a network management system to which traps will be sent.')
trap_manager_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(1, 32))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
trapManagerName.setStatus('mandatory')
if mibBuilder.loadTexts:
trapManagerName.setDescription('This object identifies the name of the destination of a network management system to which traps will be sent.')
trap_manager_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 2, 13, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
trapManagerStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
trapManagerStatus.setDescription('This object specifies a trap manager entry status in the trap manager table. (1) -- Enabled or (2) -- Disabled.')
mes2110__port_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1))
if mibBuilder.loadTexts:
mes2110_PortTable.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_PortTable.setDescription('This object lists port entries on the mes2110 module.')
mes2110__port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1)).setIndexNames((0, 'ZYXEL-MES2110-MIB', 'portIndex'))
if mibBuilder.loadTexts:
mes2110_PortEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
mes2110_PortEntry.setDescription('This object specifies a port entry in the port table, mes2110_PortTable. The port entry contains the information about a single port.')
port_index = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 256))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
portIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
portIndex.setDescription('This object is the port index, which uniquely identifies a port. It ranges from 1 to the total port number.')
port_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
portName.setStatus('mandatory')
if mibBuilder.loadTexts:
portName.setDescription('This object specifies the user defined descriptive name for the port.')
port_admin_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 4))).clone(namedValues=named_values(('disable', 1), ('enable', 4)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
portAdminStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
portAdminStatus.setDescription('This object specifies the port admin state. Setting this object to disable(1) disables the port. Setting this object to enable(4) enables the port.')
port_link_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('down', 1), ('up', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
portLinkStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
portLinkStatus.setDescription('This object indicates the link status attached to the port.')
port_speed_mode = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('speed-10M', 1), ('speed-100M', 2), ('speed-1000M', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
portSpeedMode.setStatus('mandatory')
if mibBuilder.loadTexts:
portSpeedMode.setDescription('This object specifies the speed of the port, 10M(1) or 100M(2) or 100M(3).')
port_duplex_mode = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('half', 1), ('full', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
portDuplexMode.setStatus('mandatory')
if mibBuilder.loadTexts:
portDuplexMode.setDescription('This object specifies the duplex mode of the port, half duplex(1) or full duplex(2).')
port_auto = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disable', 1), ('enable', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
portAuto.setStatus('mandatory')
if mibBuilder.loadTexts:
portAuto.setDescription('This object specifies the auto negotiation status of the port.')
port_ffc = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 3, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disable', 1), ('enable', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
portFfc.setStatus('mandatory')
if mibBuilder.loadTexts:
portFfc.setDescription('This object specifies the force flow control status of a port.')
alm_cold_start = notification_type((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0, 1))
if mibBuilder.loadTexts:
almColdStart.setDescription('This trap is sent when the system is started from power down.')
alm_warm_start = notification_type((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0, 2))
if mibBuilder.loadTexts:
almWarmStart.setDescription('This trap is sent when the system is reset.')
alm_link_up = notification_type((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0, 3))
if mibBuilder.loadTexts:
almLinkUp.setDescription("This trap is sent when the link associated with the port indexed 'portIndex' changes its 'portLinkStatus' from down(2) to up(1).")
alm_link_down = notification_type((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0, 4))
if mibBuilder.loadTexts:
almLinkDown.setDescription("This trap is sent when the link associated with the port indexed 'portIndex' changes its 'portLinkStatus' from up(1) to down(2).")
alm_conf_change = notification_type((1, 3, 6, 1, 4, 1, 890, 1, 5, 8, 2110, 4) + (0, 5))
if mibBuilder.loadTexts:
almConfChange.setDescription('This trap is sent when the system configuration has been changed.')
mibBuilder.exportSymbols('ZYXEL-MES2110-MIB', mes2110_MgtSnmpVer=mes2110_MgtSnmpVer, portSpeedMode=portSpeedMode, communityStringRW=communityStringRW, portName=portName, trapManagerIpAddress=trapManagerIpAddress, accessSwitch=accessSwitch, mes2110_MgtModDesc=mes2110_MgtModDesc, mes2110_SystemInfo=mes2110_SystemInfo, trapManagerTable=trapManagerTable, trapManagerIndex=trapManagerIndex, mes2110_SystemContact=mes2110_SystemContact, portIndex=portIndex, communityStringRO=communityStringRO, portLinkStatus=portLinkStatus, esSeries=esSeries, mes2110_MgtModManuDate=mes2110_MgtModManuDate, mes2110_MgtModPN=mes2110_MgtModPN, mes2110_SystemName=mes2110_SystemName, trapManagerName=trapManagerName, almLinkDown=almLinkDown, mes2110_PortTable=mes2110_PortTable, almWarmStart=almWarmStart, mgtStp=mgtStp, trapManagerStatus=trapManagerStatus, zyxel=zyxel, mes2110_Port=mes2110_Port, almConfChange=almConfChange, almLinkUp=almLinkUp, portAuto=portAuto, mes2110_MgtModSN=mes2110_MgtModSN, trapManagerTableEntry=trapManagerTableEntry, mes2110_Traps=mes2110_Traps, mes2110_MIB=mes2110_MIB, defaultGateway=defaultGateway, portFfc=portFfc, products=products, almColdStart=almColdStart, mes2110_Mgt=mes2110_Mgt, portAdminStatus=portAdminStatus, mes2110_MgtModRev=mes2110_MgtModRev, interfaceIpAddress=interfaceIpAddress, mes2110_SystemLocation=mes2110_SystemLocation, mes2110_PortEntry=mes2110_PortEntry, portDuplexMode=portDuplexMode, interfaceSubnetMask=interfaceSubnetMask) |
userNum = int(input("Input a number: "))
out = ""
numeralArr = [(1000, "M"), (500, "D"), (100, "C"), (50, "L"), (10, "X"), (5, "V"), (1, "I"), (0, ""), (0, "")]
def convert(num, nums, iters, halfs):
global out
if num >= nums[0] - iters[0]:
out += iters[1] + nums[1]
num -= nums[0] - iters[0]
elif num < nums[0] - iters[0]:
if halfs[0]: out += halfs[2]; num -= halfs[1]
out += iters[1] * (num // iters[0] if iters[0] > 0 else 1)
num -= iters[0] * (num // iters[0] if iters[0] > 0 else 1)
elif num == nums[0]:
out += nums[1]
num -= nums[0]
return num
for x in range(0, len(numeralArr) - 2, 2):
number, numeral = numeralArr[x]
halfNumber, halfNumeral = numeralArr[x + 1]
iterNumber, iterNumeral = numeralArr[x + 2]
out += numeral * (userNum // number)
userNum -= number * (userNum // number)
userNum = convert(userNum, (number, numeral) if userNum >= halfNumber else (halfNumber, halfNumeral), (iterNumber, iterNumeral), [userNum >= halfNumber, halfNumber, halfNumeral])
print(out) | user_num = int(input('Input a number: '))
out = ''
numeral_arr = [(1000, 'M'), (500, 'D'), (100, 'C'), (50, 'L'), (10, 'X'), (5, 'V'), (1, 'I'), (0, ''), (0, '')]
def convert(num, nums, iters, halfs):
global out
if num >= nums[0] - iters[0]:
out += iters[1] + nums[1]
num -= nums[0] - iters[0]
elif num < nums[0] - iters[0]:
if halfs[0]:
out += halfs[2]
num -= halfs[1]
out += iters[1] * (num // iters[0] if iters[0] > 0 else 1)
num -= iters[0] * (num // iters[0] if iters[0] > 0 else 1)
elif num == nums[0]:
out += nums[1]
num -= nums[0]
return num
for x in range(0, len(numeralArr) - 2, 2):
(number, numeral) = numeralArr[x]
(half_number, half_numeral) = numeralArr[x + 1]
(iter_number, iter_numeral) = numeralArr[x + 2]
out += numeral * (userNum // number)
user_num -= number * (userNum // number)
user_num = convert(userNum, (number, numeral) if userNum >= halfNumber else (halfNumber, halfNumeral), (iterNumber, iterNumeral), [userNum >= halfNumber, halfNumber, halfNumeral])
print(out) |
d = {}
palavra = 'Felipe Schmaedecke'
for l in palavra:
if l in d:
d[l] = d[l] + 1
else:
d[l] = 1
print(d)
| d = {}
palavra = 'Felipe Schmaedecke'
for l in palavra:
if l in d:
d[l] = d[l] + 1
else:
d[l] = 1
print(d) |
class ECA:
def __init__(self, id):
self.id = bin(id)[2:].zfill(8)
self.dict = {}
for i in range(8):
self.dict[bin(7 - i)[2:].zfill(3)] = self.id[i]
self.array = [0 for x in range(199)]
self.array[99] = 1
def step(self):
arr = [0 for x in range(len(self.array))]
for i in range(len(self.array)):
s = ""
if i == 0:
s += "0"
else:
s += str(self.array[i - 1])
s += str(self.array[i])
if i == len(self.array) - 1:
s += "0"
else:
s += str(self.array[i + 1])
arr[i] = int(self.dict[s])
self.array = arr
| class Eca:
def __init__(self, id):
self.id = bin(id)[2:].zfill(8)
self.dict = {}
for i in range(8):
self.dict[bin(7 - i)[2:].zfill(3)] = self.id[i]
self.array = [0 for x in range(199)]
self.array[99] = 1
def step(self):
arr = [0 for x in range(len(self.array))]
for i in range(len(self.array)):
s = ''
if i == 0:
s += '0'
else:
s += str(self.array[i - 1])
s += str(self.array[i])
if i == len(self.array) - 1:
s += '0'
else:
s += str(self.array[i + 1])
arr[i] = int(self.dict[s])
self.array = arr |
expected_output = {
"service_instance": {
501: {
"interfaces": {
"TenGigabitEthernet0/3/0": {"state": "Up", "type": "Static"},
"TenGigabitEthernet0/1/0": {"state": "Up", "type": "Static"},
}
},
502: {
"interfaces": {"TenGigabitEthernet0/3/0": {"state": "Up", "type": "Static"}}
},
}
}
| expected_output = {'service_instance': {501: {'interfaces': {'TenGigabitEthernet0/3/0': {'state': 'Up', 'type': 'Static'}, 'TenGigabitEthernet0/1/0': {'state': 'Up', 'type': 'Static'}}}, 502: {'interfaces': {'TenGigabitEthernet0/3/0': {'state': 'Up', 'type': 'Static'}}}}} |
class KNNClassifier(object):
def __init__(self, k=3, distance=None):
self.k = k
self.distance = distance
def fit(self, x, y):
pass
def predict(self, x):
pass
def __decision_function(self):
pass
| class Knnclassifier(object):
def __init__(self, k=3, distance=None):
self.k = k
self.distance = distance
def fit(self, x, y):
pass
def predict(self, x):
pass
def __decision_function(self):
pass |
'''
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
#edge case
if not head or not head.next:
return head
#get pre_node and dummy point to node 0
pre_node = dummy = ListNode(0)
#link dummy to head
dummy.next = head
while head and head.next:
#set next_node node after head each time
next_node = head.next
#swapping
head.next = next_node.next
next_node.next = head
pre_node.next = next_node
#after swapping
#move head to one node next becasue head is at node 1
head = head.next
#move pre_node to one node before head which is next_node.next node
pre_node = next_node.next
return dummy.next
| """
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
"""
class Solution(object):
def swap_pairs(self, head):
if not head or not head.next:
return head
pre_node = dummy = list_node(0)
dummy.next = head
while head and head.next:
next_node = head.next
head.next = next_node.next
next_node.next = head
pre_node.next = next_node
head = head.next
pre_node = next_node.next
return dummy.next |
with open("Prob03.in.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
nola = content.pop(0)
for x in content:
x = x.strip(" ")
x = x.split()
add = int(x[0]) + int(x[1])
multi = int(x[0]) * int(x[1])
print( str(add) + " " + str(multi))
| with open('Prob03.in.txt') as f:
content = f.readlines()
content = [x.strip() for x in content]
nola = content.pop(0)
for x in content:
x = x.strip(' ')
x = x.split()
add = int(x[0]) + int(x[1])
multi = int(x[0]) * int(x[1])
print(str(add) + ' ' + str(multi)) |
## Script (Python) "getFotoCapa"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Retorna um nome de arquivo para ser usado como foto da capa
padrao = [ 'capa01.jpg','capa02.jpg','capa03.jpg','capa04.jpg','capa05.jpg', \
'capa06.jpg','capa07.jpg', ]
ultimo = context.portal_catalog.searchResults(portal_type='Programa', sort_on='getData', sort_order='reverse', review_state='published')[0]
imagem = ultimo.getImagem
if not imagem:
imagem = context.portal_url() + '/' + padrao[random.randint(0,6)]
else:
imagem = ultimo.getURL() + "/imagem"
return imagem | padrao = ['capa01.jpg', 'capa02.jpg', 'capa03.jpg', 'capa04.jpg', 'capa05.jpg', 'capa06.jpg', 'capa07.jpg']
ultimo = context.portal_catalog.searchResults(portal_type='Programa', sort_on='getData', sort_order='reverse', review_state='published')[0]
imagem = ultimo.getImagem
if not imagem:
imagem = context.portal_url() + '/' + padrao[random.randint(0, 6)]
else:
imagem = ultimo.getURL() + '/imagem'
return imagem |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class DoubanPipeline(object):
# def __init__(self, server, port):
# pass
# @classmethod
# def from_crawler(cls, crawler):
# return cls(crawler.settings['MONGO_SERVER'],
# crawler.settings['MONGO_PORT'])
def process_item(self, item, spider):
return item
| class Doubanpipeline(object):
def process_item(self, item, spider):
return item |
#
# PySNMP MIB module CISCO-LAG-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LAG-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:47:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection")
ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability")
NotificationGroup, ModuleCompliance, AgentCapabilities = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "AgentCapabilities")
Gauge32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Counter32, ObjectIdentity, MibIdentifier, iso, Bits, ModuleIdentity, IpAddress, TimeTicks, Unsigned32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Counter32", "ObjectIdentity", "MibIdentifier", "iso", "Bits", "ModuleIdentity", "IpAddress", "TimeTicks", "Unsigned32", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoLagCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 332))
ciscoLagCapability.setRevisions(('2012-04-02 00:00', '2011-09-27 00:00', '2010-11-01 00:00', '2009-11-19 00:00', '2007-07-10 10:00', '2006-06-15 12:00', '2004-02-04 00:00',))
if mibBuilder.loadTexts: ciscoLagCapability.setLastUpdated('201204020000Z')
if mibBuilder.loadTexts: ciscoLagCapability.setOrganization('Cisco Systems, Inc.')
clagCapV12R0111bEXCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0111bEXCat6K = clagCapV12R0111bEXCat6K.setProductRelease('Cisco IOS 12.1(11b)EX on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0111bEXCat6K = clagCapV12R0111bEXCat6K.setStatus('current')
clagCapV12R0217SXCat6KPfc2 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0217SXCat6KPfc2 = clagCapV12R0217SXCat6KPfc2.setProductRelease('Cisco IOS 12.2(17)SX on Catalyst 6000/6500\n and Cisco 7600 series devices with PFC2 card.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0217SXCat6KPfc2 = clagCapV12R0217SXCat6KPfc2.setStatus('current')
clagCapV12R0217SXCat6KPfc3 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0217SXCat6KPfc3 = clagCapV12R0217SXCat6KPfc3.setProductRelease('Cisco IOS 12.2(17)SX on Catalyst 6000/6500\n and Cisco 7600 series devices with PFC3 card.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0217SXCat6KPfc3 = clagCapV12R0217SXCat6KPfc3.setStatus('current')
clagCapCatOSV08R0101 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapCatOSV08R0101 = clagCapCatOSV08R0101.setProductRelease('Cisco CatOS 8.1(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapCatOSV08R0101 = clagCapCatOSV08R0101.setStatus('current')
clagCapV12R0218SXF5PCat6KPfc2 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 5))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0218SXF5PCat6KPfc2 = clagCapV12R0218SXF5PCat6KPfc2.setProductRelease('Cisco IOS 12.2(18)SXF5 on Catalyst 6000/6500\n and Cisco 7600 series devices with PFC2 card.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0218SXF5PCat6KPfc2 = clagCapV12R0218SXF5PCat6KPfc2.setStatus('current')
clagCapV12R0218SXF5PCat6KPfc3 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 6))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0218SXF5PCat6KPfc3 = clagCapV12R0218SXF5PCat6KPfc3.setProductRelease('Cisco IOS 12.2(18)SXF5 on Catalyst 6000/6500\n and Cisco 7600 series devices with PFC3 card.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0218SXF5PCat6KPfc3 = clagCapV12R0218SXF5PCat6KPfc3.setStatus('current')
clagCapV12R0233SXHPCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 7))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0233SXHPCat6K = clagCapV12R0233SXHPCat6K.setProductRelease('Cisco IOS 12.2(33)SXH on Catalyst 6000/6500\n devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0233SXHPCat6K = clagCapV12R0233SXHPCat6K.setStatus('current')
clagCapV12R0252SGPCat4K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 8))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0252SGPCat4K = clagCapV12R0252SGPCat4K.setProductRelease('Cisco IOS 12.2(52)SG on Cat4K family devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0252SGPCat4K = clagCapV12R0252SGPCat4K.setStatus('current')
clagCapV12R0250SYPCat6K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 9))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0250SYPCat6K = clagCapV12R0250SYPCat6K.setProductRelease('Cisco IOS 12.2(50)SY on Catalyst 6000/6500\n devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV12R0250SYPCat6K = clagCapV12R0250SYPCat6K.setStatus('current')
clagCapV15R0001SYPCat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 10))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV15R0001SYPCat6k = clagCapV15R0001SYPCat6k.setProductRelease('Cisco IOS 15.0(1)SY on Catalyst 6000/6500\n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV15R0001SYPCat6k = clagCapV15R0001SYPCat6k.setStatus('current')
clagCapV15R0101SGPCat4K = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 11))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV15R0101SGPCat4K = clagCapV15R0101SGPCat4K.setProductRelease('Cisco IOS 15.1(1)SG on Cat4K family devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clagCapV15R0101SGPCat4K = clagCapV15R0101SGPCat4K.setStatus('current')
mibBuilder.exportSymbols("CISCO-LAG-CAPABILITY", clagCapV12R0111bEXCat6K=clagCapV12R0111bEXCat6K, clagCapV12R0217SXCat6KPfc3=clagCapV12R0217SXCat6KPfc3, ciscoLagCapability=ciscoLagCapability, clagCapCatOSV08R0101=clagCapCatOSV08R0101, clagCapV12R0233SXHPCat6K=clagCapV12R0233SXHPCat6K, clagCapV15R0101SGPCat4K=clagCapV15R0101SGPCat4K, clagCapV12R0218SXF5PCat6KPfc2=clagCapV12R0218SXF5PCat6KPfc2, clagCapV12R0217SXCat6KPfc2=clagCapV12R0217SXCat6KPfc2, clagCapV12R0252SGPCat4K=clagCapV12R0252SGPCat4K, clagCapV15R0001SYPCat6k=clagCapV15R0001SYPCat6k, clagCapV12R0250SYPCat6K=clagCapV12R0250SYPCat6K, PYSNMP_MODULE_ID=ciscoLagCapability, clagCapV12R0218SXF5PCat6KPfc3=clagCapV12R0218SXF5PCat6KPfc3)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection')
(cisco_agent_capability,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoAgentCapability')
(notification_group, module_compliance, agent_capabilities) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'AgentCapabilities')
(gauge32, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, counter32, object_identity, mib_identifier, iso, bits, module_identity, ip_address, time_ticks, unsigned32, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'Counter32', 'ObjectIdentity', 'MibIdentifier', 'iso', 'Bits', 'ModuleIdentity', 'IpAddress', 'TimeTicks', 'Unsigned32', 'Integer32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
cisco_lag_capability = module_identity((1, 3, 6, 1, 4, 1, 9, 7, 332))
ciscoLagCapability.setRevisions(('2012-04-02 00:00', '2011-09-27 00:00', '2010-11-01 00:00', '2009-11-19 00:00', '2007-07-10 10:00', '2006-06-15 12:00', '2004-02-04 00:00'))
if mibBuilder.loadTexts:
ciscoLagCapability.setLastUpdated('201204020000Z')
if mibBuilder.loadTexts:
ciscoLagCapability.setOrganization('Cisco Systems, Inc.')
clag_cap_v12_r0111b_ex_cat6_k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0111b_ex_cat6_k = clagCapV12R0111bEXCat6K.setProductRelease('Cisco IOS 12.1(11b)EX on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0111b_ex_cat6_k = clagCapV12R0111bEXCat6K.setStatus('current')
clag_cap_v12_r0217_sx_cat6_k_pfc2 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0217_sx_cat6_k_pfc2 = clagCapV12R0217SXCat6KPfc2.setProductRelease('Cisco IOS 12.2(17)SX on Catalyst 6000/6500\n and Cisco 7600 series devices with PFC2 card.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0217_sx_cat6_k_pfc2 = clagCapV12R0217SXCat6KPfc2.setStatus('current')
clag_cap_v12_r0217_sx_cat6_k_pfc3 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0217_sx_cat6_k_pfc3 = clagCapV12R0217SXCat6KPfc3.setProductRelease('Cisco IOS 12.2(17)SX on Catalyst 6000/6500\n and Cisco 7600 series devices with PFC3 card.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0217_sx_cat6_k_pfc3 = clagCapV12R0217SXCat6KPfc3.setStatus('current')
clag_cap_cat_osv08_r0101 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_cat_osv08_r0101 = clagCapCatOSV08R0101.setProductRelease('Cisco CatOS 8.1(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_cat_osv08_r0101 = clagCapCatOSV08R0101.setStatus('current')
clag_cap_v12_r0218_sxf5_p_cat6_k_pfc2 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 5))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0218_sxf5_p_cat6_k_pfc2 = clagCapV12R0218SXF5PCat6KPfc2.setProductRelease('Cisco IOS 12.2(18)SXF5 on Catalyst 6000/6500\n and Cisco 7600 series devices with PFC2 card.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0218_sxf5_p_cat6_k_pfc2 = clagCapV12R0218SXF5PCat6KPfc2.setStatus('current')
clag_cap_v12_r0218_sxf5_p_cat6_k_pfc3 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 6))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0218_sxf5_p_cat6_k_pfc3 = clagCapV12R0218SXF5PCat6KPfc3.setProductRelease('Cisco IOS 12.2(18)SXF5 on Catalyst 6000/6500\n and Cisco 7600 series devices with PFC3 card.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0218_sxf5_p_cat6_k_pfc3 = clagCapV12R0218SXF5PCat6KPfc3.setStatus('current')
clag_cap_v12_r0233_sxhp_cat6_k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 7))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0233_sxhp_cat6_k = clagCapV12R0233SXHPCat6K.setProductRelease('Cisco IOS 12.2(33)SXH on Catalyst 6000/6500\n devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0233_sxhp_cat6_k = clagCapV12R0233SXHPCat6K.setStatus('current')
clag_cap_v12_r0252_sgp_cat4_k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 8))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0252_sgp_cat4_k = clagCapV12R0252SGPCat4K.setProductRelease('Cisco IOS 12.2(52)SG on Cat4K family devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0252_sgp_cat4_k = clagCapV12R0252SGPCat4K.setStatus('current')
clag_cap_v12_r0250_syp_cat6_k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 9))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0250_syp_cat6_k = clagCapV12R0250SYPCat6K.setProductRelease('Cisco IOS 12.2(50)SY on Catalyst 6000/6500\n devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v12_r0250_syp_cat6_k = clagCapV12R0250SYPCat6K.setStatus('current')
clag_cap_v15_r0001_syp_cat6k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 10))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v15_r0001_syp_cat6k = clagCapV15R0001SYPCat6k.setProductRelease('Cisco IOS 15.0(1)SY on Catalyst 6000/6500\n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v15_r0001_syp_cat6k = clagCapV15R0001SYPCat6k.setStatus('current')
clag_cap_v15_r0101_sgp_cat4_k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 332, 11))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v15_r0101_sgp_cat4_k = clagCapV15R0101SGPCat4K.setProductRelease('Cisco IOS 15.1(1)SG on Cat4K family devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
clag_cap_v15_r0101_sgp_cat4_k = clagCapV15R0101SGPCat4K.setStatus('current')
mibBuilder.exportSymbols('CISCO-LAG-CAPABILITY', clagCapV12R0111bEXCat6K=clagCapV12R0111bEXCat6K, clagCapV12R0217SXCat6KPfc3=clagCapV12R0217SXCat6KPfc3, ciscoLagCapability=ciscoLagCapability, clagCapCatOSV08R0101=clagCapCatOSV08R0101, clagCapV12R0233SXHPCat6K=clagCapV12R0233SXHPCat6K, clagCapV15R0101SGPCat4K=clagCapV15R0101SGPCat4K, clagCapV12R0218SXF5PCat6KPfc2=clagCapV12R0218SXF5PCat6KPfc2, clagCapV12R0217SXCat6KPfc2=clagCapV12R0217SXCat6KPfc2, clagCapV12R0252SGPCat4K=clagCapV12R0252SGPCat4K, clagCapV15R0001SYPCat6k=clagCapV15R0001SYPCat6k, clagCapV12R0250SYPCat6K=clagCapV12R0250SYPCat6K, PYSNMP_MODULE_ID=ciscoLagCapability, clagCapV12R0218SXF5PCat6KPfc3=clagCapV12R0218SXF5PCat6KPfc3) |
def test_epl_single_year_mtl(style_checker):
"""Style check test against epl_single_year.mtl
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml',
'whatever', 'epl_single_year.mtl')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
# Try the same test, but without the --config file.
# It should fail, because we no longer include the module's
# config which allows EPL copyright notices.
p = style_checker.run_style_checker('whatever', 'epl_single_year.mtl')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
epl_single_year.mtl:2: Copyright notice is not correctly formatted
It must look like...
Copyright (C) 1992-2017, <copyright holder>
... where <copyright holder> can be any of:
- `AdaCore'
- `Altran Praxis'
- `Altran UK Limited'
- `Free Software Foundation, Inc.'
- `AdaCore, Altran Praxis'
- `AdaCore and Altran UK Limited'
- `AdaCore, Altran UK Limited'
- `AdaCore and Altran UK'
- `AdaCore, Altran UK'
""")
def test_epl_range_mtl(style_checker):
"""Style check test against epl_range.mtl
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml',
'whatever', 'epl_range.mtl')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
# Try the same test, but without the --config file.
# It should fail, because we no longer include the module's
# config which allows EPL copyright notices.
p = style_checker.run_style_checker('whatever', 'epl_range.mtl')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
epl_range.mtl:2: Copyright notice is not correctly formatted
It must look like...
Copyright (C) 1992-2017, <copyright holder>
... where <copyright holder> can be any of:
- `AdaCore'
- `Altran Praxis'
- `Altran UK Limited'
- `Free Software Foundation, Inc.'
- `AdaCore, Altran Praxis'
- `AdaCore and Altran UK Limited'
- `AdaCore, Altran UK Limited'
- `AdaCore and Altran UK'
- `AdaCore, Altran UK'
""")
def test_relpath_m(style_checker):
"""Style check test against relpath.m
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml',
'whatever', 'relpath.m')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
relpath.m:5: Copyright notice has unexpected copyright holder:
`AdaCore'
Expected either of:
- `Someone Inc'
- `Second Holder SARL'
""")
# Try the same test, but without the --config file.
p = style_checker.run_style_checker('whatever', 'relpath.m')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
def test_deep_notice(style_checker):
"""Style check test against deep_notice.m
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml',
'whatever', 'deep_notice.m')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
# Try the same test, but without the --config file.
p = style_checker.run_style_checker('whatever', 'deep_notice.m')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
deep_notice.m:100: Copyright notice must occur before line 24
""")
def test_notice_too_deep_m(style_checker):
"""Style check test against notice_too_deep.m
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml',
'whatever', 'notice_too_deep.m')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
notice_too_deep.m:101: Copyright notice must occur before line 100
""")
# Try the same test, but without the --config file.
p = style_checker.run_style_checker('whatever', 'notice_too_deep.m')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
notice_too_deep.m:101: Copyright notice must occur before line 24
""")
| def test_epl_single_year_mtl(style_checker):
"""Style check test against epl_single_year.mtl
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml', 'whatever', 'epl_single_year.mtl')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
p = style_checker.run_style_checker('whatever', 'epl_single_year.mtl')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, "epl_single_year.mtl:2: Copyright notice is not correctly formatted\nIt must look like...\n\n Copyright (C) 1992-2017, <copyright holder>\n\n... where <copyright holder> can be any of:\n - `AdaCore'\n - `Altran Praxis'\n - `Altran UK Limited'\n - `Free Software Foundation, Inc.'\n - `AdaCore, Altran Praxis'\n - `AdaCore and Altran UK Limited'\n - `AdaCore, Altran UK Limited'\n - `AdaCore and Altran UK'\n - `AdaCore, Altran UK'\n")
def test_epl_range_mtl(style_checker):
"""Style check test against epl_range.mtl
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml', 'whatever', 'epl_range.mtl')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
p = style_checker.run_style_checker('whatever', 'epl_range.mtl')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, "epl_range.mtl:2: Copyright notice is not correctly formatted\nIt must look like...\n\n Copyright (C) 1992-2017, <copyright holder>\n\n... where <copyright holder> can be any of:\n - `AdaCore'\n - `Altran Praxis'\n - `Altran UK Limited'\n - `Free Software Foundation, Inc.'\n - `AdaCore, Altran Praxis'\n - `AdaCore and Altran UK Limited'\n - `AdaCore, Altran UK Limited'\n - `AdaCore and Altran UK'\n - `AdaCore, Altran UK'\n")
def test_relpath_m(style_checker):
"""Style check test against relpath.m
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml', 'whatever', 'relpath.m')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, "relpath.m:5: Copyright notice has unexpected copyright holder:\n `AdaCore'\nExpected either of:\n - `Someone Inc'\n - `Second Holder SARL'\n")
p = style_checker.run_style_checker('whatever', 'relpath.m')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
def test_deep_notice(style_checker):
"""Style check test against deep_notice.m
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml', 'whatever', 'deep_notice.m')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
p = style_checker.run_style_checker('whatever', 'deep_notice.m')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, 'deep_notice.m:100: Copyright notice must occur before line 24\n')
def test_notice_too_deep_m(style_checker):
"""Style check test against notice_too_deep.m
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml', 'whatever', 'notice_too_deep.m')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, 'notice_too_deep.m:101: Copyright notice must occur before line 100\n')
p = style_checker.run_style_checker('whatever', 'notice_too_deep.m')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, 'notice_too_deep.m:101: Copyright notice must occur before line 24\n') |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 14 07:44:37 2020
@author: ucobiz
"""
values = [] # initialize the list to be empty
userVal = 1 # give our loop variable a value
while userVal != 0:
userVal = int(input("Enter a number, 0 to stop: "))
if userVal != 0: # only append if it's valid
values.append(userVal) # add value to the list
print("Stopped!")
print(values)
| """
Created on Wed Oct 14 07:44:37 2020
@author: ucobiz
"""
values = []
user_val = 1
while userVal != 0:
user_val = int(input('Enter a number, 0 to stop: '))
if userVal != 0:
values.append(userVal)
print('Stopped!')
print(values) |
mylist = ["banana", "apple", "pineapple"]
print(mylist)
item = mylist[2]
print(item)
if "banana" in mylist:
print("yes")
else:
print("no")
mylist.append("lemon")
print(mylist)
mylist.insert(2, "grapes")
print(mylist)
# /item = [0] * 5
# print(item)
| mylist = ['banana', 'apple', 'pineapple']
print(mylist)
item = mylist[2]
print(item)
if 'banana' in mylist:
print('yes')
else:
print('no')
mylist.append('lemon')
print(mylist)
mylist.insert(2, 'grapes')
print(mylist) |
# These functions deal with displaying information in CLI
## Check Payment Display
def display_lessons(lessons):
print('displaying lesson payment info')
unpaid_lessons = []
paid_lessons = []
for lesson in lessons:
if lesson['paid'] == 'n':
unpaid_lessons.append(lesson)
elif lesson['paid'] == 'y':
paid_lessons.append(lesson)
for lesson in unpaid_lessons:
print(f'Lesson #{lesson["id"]} remains unpaid.')
for lesson in paid_lessons:
print(f'Lesson #{lesson["id"]} has been paid for.')
print('OK!')
| def display_lessons(lessons):
print('displaying lesson payment info')
unpaid_lessons = []
paid_lessons = []
for lesson in lessons:
if lesson['paid'] == 'n':
unpaid_lessons.append(lesson)
elif lesson['paid'] == 'y':
paid_lessons.append(lesson)
for lesson in unpaid_lessons:
print(f"Lesson #{lesson['id']} remains unpaid.")
for lesson in paid_lessons:
print(f"Lesson #{lesson['id']} has been paid for.")
print('OK!') |
city = input("Enter city name = ")
sales = int(input("Enter sales volume = "))
cities = ["Sofia", "Varna", "Plovdiv"]
index = 4
#Discounts by cities
if 0 <= sales and sales <= 500:
comision = [0.05,0.045,0.055]
elif 500 < sales and sales <= 1000:
comision = [0.07,0.075,0.08]
elif 1000 < sales and sales <= 10001:
comision = [0.08,0.1,0.12]
else:
comision = [0.12,0.13,0.145]
#Indexing
if city in cities:
index = cities.index(city)
discount = sales * comision[index]
print("{0:.2f}".format(discount)) #rounding
| city = input('Enter city name = ')
sales = int(input('Enter sales volume = '))
cities = ['Sofia', 'Varna', 'Plovdiv']
index = 4
if 0 <= sales and sales <= 500:
comision = [0.05, 0.045, 0.055]
elif 500 < sales and sales <= 1000:
comision = [0.07, 0.075, 0.08]
elif 1000 < sales and sales <= 10001:
comision = [0.08, 0.1, 0.12]
else:
comision = [0.12, 0.13, 0.145]
if city in cities:
index = cities.index(city)
discount = sales * comision[index]
print('{0:.2f}'.format(discount)) |
#! /usr/bin/python3
# -*- coding: utf-8 -*-S
def crypt(line: str) -> str:
result = str()
for symbol in line:
result += chr(ord(symbol) + 1)
return result
print(crypt(input()))
| def crypt(line: str) -> str:
result = str()
for symbol in line:
result += chr(ord(symbol) + 1)
return result
print(crypt(input())) |
class Solution:
# not my soln but its very cool
def threeSum(self, nums: List[int]) -> List[List[int]]:
triplets = set()
neg, pos, zeros = [], [], 0
for num in nums:
if num > 0:
pos.append(num)
elif num < 0:
neg.append(num)
else:
zeros += 1
neg_set, pos_set = set(neg), set(pos) # for O(1) lookup
# if there's zero in list, add cases where -x is in neg and x is in pos
if zeros > 0:
for num in pos_set:
if -num in neg_set:
triplets.add((-num, 0, num))
# if at least 3 zeros in list, add 0, 0, 0
if zeros >= 3:
triplets.add((0, 0, 0))
# for all pairs of negative numbers, check if their complement is in positive set
for i in range(len(neg)):
for j in range(i + 1, len(neg)):
target = -1 * (neg[i] + neg[j])
if target in pos_set:
triplets.add(tuple(sorted([neg[i], neg[j], target])))
# do the same for positive numbers
for i in range(len(pos)):
for j in range(i + 1, len(pos)):
target = -1 * (pos[i] + pos[j])
if target in neg_set:
triplets.add(tuple(sorted([pos[i], pos[j], target])))
return triplets
| class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
triplets = set()
(neg, pos, zeros) = ([], [], 0)
for num in nums:
if num > 0:
pos.append(num)
elif num < 0:
neg.append(num)
else:
zeros += 1
(neg_set, pos_set) = (set(neg), set(pos))
if zeros > 0:
for num in pos_set:
if -num in neg_set:
triplets.add((-num, 0, num))
if zeros >= 3:
triplets.add((0, 0, 0))
for i in range(len(neg)):
for j in range(i + 1, len(neg)):
target = -1 * (neg[i] + neg[j])
if target in pos_set:
triplets.add(tuple(sorted([neg[i], neg[j], target])))
for i in range(len(pos)):
for j in range(i + 1, len(pos)):
target = -1 * (pos[i] + pos[j])
if target in neg_set:
triplets.add(tuple(sorted([pos[i], pos[j], target])))
return triplets |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 09:38:16 2021
@author: gregoryvanbeek
"""
#%%INPUT
flag = 1040
verbose=True
#%%
def samflags(flag=0, verbose=True):
"""This script converts a decimal flag to binary and get the corresponding properties according to the sam-flag standard.
The code is based on the explanation given here https://davetang.org/muse/2014/03/06/understanding-bam-flags/
For manual checking sam flags, check https://broadinstitute.github.io/picard/explain-flags.html
The input is a decimal number.
Parameters
----------
flag : int, optional
by default 0
verbose : bool, optional
by default True
"""
flag_binary = format(flag, '012b') # '#012b' to start the string with '0b'. 12 indicated that the string has length 12.
prop_dict = {1: 'read paired',
2: 'read mapped in proper pair',
3: 'read unmapped',
4: 'mate unmapped',
5: 'read reverse strand',
6: 'mate reverse strand',
7: 'first in pair',
8: 'second in pair',
9: 'not primary alignment',
10: 'read fails platform/vendor quality checks',
11: 'read is PCR or optical duplicate',
12: 'supplementary alignment'}
counter = 1
flagprop_list = []
for b in reversed(flag_binary):
if int(b) == 1:
flagprop_list.append(prop_dict.get(counter))
counter += 1
if verbose == True:
print('Entered decimal flag = %i' % flag)
print('Corresponding binary flag = %s' % flag_binary)
print(flagprop_list)
print('')
return(flag_binary, flagprop_list)
#%%
if __name__ == '__main__':
flag_binary, flagproperties = samflags(flag=flag, verbose=verbose)
| """
Created on Mon Jan 4 09:38:16 2021
@author: gregoryvanbeek
"""
flag = 1040
verbose = True
def samflags(flag=0, verbose=True):
"""This script converts a decimal flag to binary and get the corresponding properties according to the sam-flag standard.
The code is based on the explanation given here https://davetang.org/muse/2014/03/06/understanding-bam-flags/
For manual checking sam flags, check https://broadinstitute.github.io/picard/explain-flags.html
The input is a decimal number.
Parameters
----------
flag : int, optional
by default 0
verbose : bool, optional
by default True
"""
flag_binary = format(flag, '012b')
prop_dict = {1: 'read paired', 2: 'read mapped in proper pair', 3: 'read unmapped', 4: 'mate unmapped', 5: 'read reverse strand', 6: 'mate reverse strand', 7: 'first in pair', 8: 'second in pair', 9: 'not primary alignment', 10: 'read fails platform/vendor quality checks', 11: 'read is PCR or optical duplicate', 12: 'supplementary alignment'}
counter = 1
flagprop_list = []
for b in reversed(flag_binary):
if int(b) == 1:
flagprop_list.append(prop_dict.get(counter))
counter += 1
if verbose == True:
print('Entered decimal flag = %i' % flag)
print('Corresponding binary flag = %s' % flag_binary)
print(flagprop_list)
print('')
return (flag_binary, flagprop_list)
if __name__ == '__main__':
(flag_binary, flagproperties) = samflags(flag=flag, verbose=verbose) |
# -*- coding: utf-8 -*-
#
# Copyright 2016 Continuum Analytics, Inc.
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
#
"""
Custom errors on Anaconda Navigator.
"""
class AnacondaNavigatorException(Exception):
pass
| """
Custom errors on Anaconda Navigator.
"""
class Anacondanavigatorexception(Exception):
pass |
def change_return(amount,currency):
currency.sort(reverse = True)
counter = 0
amount_counter = [0]*len(currency)
while amount> 0:
amount_counter[counter] = int(amount/currency[counter])
amount -= amount_counter[counter]*currency[counter]
counter += 1
return [(currency[i],amount_counter[i]) for i in range(len(currency))]
if __name__ == '__main__':
currency = [1,5,10,25]
currency_name = ['quarter','dime','nickel','pennies']
amount = int(input('Enter a amount: '))
change = change_return(amount,currency)
for i in range(len(currency)-1,-1,-1):
print(currency_name[i] + f'({change[i][0]}) - {change[i][1]}')
| def change_return(amount, currency):
currency.sort(reverse=True)
counter = 0
amount_counter = [0] * len(currency)
while amount > 0:
amount_counter[counter] = int(amount / currency[counter])
amount -= amount_counter[counter] * currency[counter]
counter += 1
return [(currency[i], amount_counter[i]) for i in range(len(currency))]
if __name__ == '__main__':
currency = [1, 5, 10, 25]
currency_name = ['quarter', 'dime', 'nickel', 'pennies']
amount = int(input('Enter a amount: '))
change = change_return(amount, currency)
for i in range(len(currency) - 1, -1, -1):
print(currency_name[i] + f'({change[i][0]}) - {change[i][1]}') |
# helpers.py, useful helper functions for wikipedia analysis
# We want to represent known symbols (starting with //) as words, the rest characters
def extract_tokens(tex):
'''walk through a LaTeX string, and grab chunks that correspond with known
identifiers, meaning anything that starts with \ and ends with one or
more whitespaces, a bracket, a ^ or underscore.
'''
regexp = r'\\(.*?)(\w+|\{|\(|\_|\^)'
tokens = []
while re.search(regexp, tex) and len(tex) > 0:
match = re.search(regexp, tex)
# Only take the chunk if it's starting at 0
if match.start() == 0:
tokens.append(tex[match.start():match.end()])
# And update the string
tex = tex[match.end():]
# Otherwise, add the next character to the tokens list
else:
tokens.append(tex[0])
tex = tex[1:]
# When we get down here, the regexp doesn't match anymore! Add remaining
if len(tex) > 0:
tokens = tokens + [t for t in tex]
return tokens
def update_method_name(methods, old_name, new_name):
'''update the set by removing an old name (usually a disambuguation error)
with a new name
Parameters
==========
methods: the set of methods
oldName: the name to remove
newName: the name to add
'''
if old_name in methods:
methods.remove(old_name)
methods.add(new_name)
return methods
| def extract_tokens(tex):
"""walk through a LaTeX string, and grab chunks that correspond with known
identifiers, meaning anything that starts with \\ and ends with one or
more whitespaces, a bracket, a ^ or underscore.
"""
regexp = '\\\\(.*?)(\\w+|\\{|\\(|\\_|\\^)'
tokens = []
while re.search(regexp, tex) and len(tex) > 0:
match = re.search(regexp, tex)
if match.start() == 0:
tokens.append(tex[match.start():match.end()])
tex = tex[match.end():]
else:
tokens.append(tex[0])
tex = tex[1:]
if len(tex) > 0:
tokens = tokens + [t for t in tex]
return tokens
def update_method_name(methods, old_name, new_name):
"""update the set by removing an old name (usually a disambuguation error)
with a new name
Parameters
==========
methods: the set of methods
oldName: the name to remove
newName: the name to add
"""
if old_name in methods:
methods.remove(old_name)
methods.add(new_name)
return methods |
# -*- coding: utf-8 -*-
# 0xCCCCCCCC
# Like Q153 but with possible duplicates.
def find_min(nums):
"""
:type nums: List[int]
:rtype: int
"""
l, r = 0, len(nums) - 1
while l < r and nums[l] >= nums[r]:
m = (l + r) // 2
if nums[m] > nums[r]:
l = m + 1
elif nums[m] < nums[r]:
r = m
else:
# When nums[m] == nums[r], we have only few cases.
# Try to prune cases as possible.
if nums[m] < nums[l]:
l += 1
r = m
# nums[l] = nums[m] = nums[r]
# Rules out one of same elements, and properties of array are preserved.
else:
r -= 1
return nums[l]
nums = [4,5,6,7,0,1,2]
print(find_min(nums))
nums = [3,4,5,1,2]
print(find_min(nums))
nums = [5,1,2]
print(find_min(nums))
nums = [5,2]
print(find_min(nums))
nums = [2,3,4,5,1]
print(find_min(nums))
nums = [1, 3, 5]
print(find_min(nums))
nums = [2,2,2,0,1]
print(find_min(nums))
nums = [3,3,1,3]
print(find_min(nums))
nums = [3,1,3,3,3]
print(find_min(nums))
nums = [4,4,4,4,4,4]
print(find_min(nums)) | def find_min(nums):
"""
:type nums: List[int]
:rtype: int
"""
(l, r) = (0, len(nums) - 1)
while l < r and nums[l] >= nums[r]:
m = (l + r) // 2
if nums[m] > nums[r]:
l = m + 1
elif nums[m] < nums[r]:
r = m
elif nums[m] < nums[l]:
l += 1
r = m
else:
r -= 1
return nums[l]
nums = [4, 5, 6, 7, 0, 1, 2]
print(find_min(nums))
nums = [3, 4, 5, 1, 2]
print(find_min(nums))
nums = [5, 1, 2]
print(find_min(nums))
nums = [5, 2]
print(find_min(nums))
nums = [2, 3, 4, 5, 1]
print(find_min(nums))
nums = [1, 3, 5]
print(find_min(nums))
nums = [2, 2, 2, 0, 1]
print(find_min(nums))
nums = [3, 3, 1, 3]
print(find_min(nums))
nums = [3, 1, 3, 3, 3]
print(find_min(nums))
nums = [4, 4, 4, 4, 4, 4]
print(find_min(nums)) |
def seed_everything(seed=2020):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
seed_everything(42) | def seed_everything(seed=2020):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
seed_everything(42) |
"""Tabler."""
__title__ = "enigma"
__description__ = "Enigma emulator"
__url__ = ""
__version__ = "0.1"
__author__ = "Luke Shiner"
__author_email__ = "luke@lukeshiner.com"
__license__ = "MIT"
__copyright__ = "Copyright 2019 Luke Shiner"
| """Tabler."""
__title__ = 'enigma'
__description__ = 'Enigma emulator'
__url__ = ''
__version__ = '0.1'
__author__ = 'Luke Shiner'
__author_email__ = 'luke@lukeshiner.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 Luke Shiner' |
class Solution:
def XXX(self, root: TreeNode) -> int:
if not root:
return 0
self.min_depth = float('inf')
def dfs(root, depth):
if not root:
return
if not root.left and not root.right:
self.min_depth = min(self.min_depth, depth)
dfs(root.left, depth+1)
dfs(root.right, depth+1)
dfs(root, 1)
return self.min_depth
| class Solution:
def xxx(self, root: TreeNode) -> int:
if not root:
return 0
self.min_depth = float('inf')
def dfs(root, depth):
if not root:
return
if not root.left and (not root.right):
self.min_depth = min(self.min_depth, depth)
dfs(root.left, depth + 1)
dfs(root.right, depth + 1)
dfs(root, 1)
return self.min_depth |
#!/usr/bin/env python3
# Find the middle element in the list.
# Create a function called middle_element that has one parameter named lst.
# If there are an odd number of elements in lst, the function
# should return the middle element.
# If there are an even number of elements, the function should
# return the average of the middle two elements.
def middle_element(lst):
if len(lst) % 2 == 0:
sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]
return sum / 2
else:
return lst[int(len(lst)/2)]
print(middle_element([5, 2, -10, -4, 4, 5]))
| def middle_element(lst):
if len(lst) % 2 == 0:
sum = lst[int(len(lst) / 2)] + lst[int(len(lst) / 2) - 1]
return sum / 2
else:
return lst[int(len(lst) / 2)]
print(middle_element([5, 2, -10, -4, 4, 5])) |
INPUT = """1919 2959 82 507 3219 239 3494 1440 3107 259 3544 683 207 562 276 2963
587 878 229 2465 2575 1367 2017 154 152 157 2420 2480 138 2512 2605 876
744 6916 1853 1044 2831 4797 213 4874 187 6051 6086 7768 5571 6203 247 285
1210 1207 1130 116 1141 563 1056 155 227 1085 697 735 192 1236 1065 156
682 883 187 307 269 673 290 693 199 132 505 206 231 200 760 612
1520 95 1664 1256 685 1446 253 88 92 313 754 1402 734 716 342 107
146 1169 159 3045 163 3192 1543 312 161 3504 3346 3231 771 3430 3355 3537
177 2129 3507 3635 2588 3735 3130 980 324 266 1130 3753 175 229 517 3893
4532 164 191 5169 4960 3349 3784 3130 5348 5036 2110 151 5356 193 1380 3580
2544 3199 3284 3009 3400 953 3344 3513 102 1532 161 143 2172 2845 136 2092
194 5189 3610 4019 210 256 5178 4485 5815 5329 5457 248 5204 4863 5880 3754
3140 4431 4534 4782 3043 209 216 5209 174 161 3313 5046 1160 160 4036 111
2533 140 4383 1581 139 141 2151 2104 2753 4524 4712 866 3338 2189 116 4677
1240 45 254 1008 1186 306 633 1232 1457 808 248 1166 775 1418 1175 287
851 132 939 1563 539 1351 1147 117 1484 100 123 490 152 798 1476 543
1158 2832 697 113 121 397 1508 118 2181 2122 809 2917 134 2824 3154 2791"""
def calc_checksum(num_list):
return max(num_list) - min(num_list)
def calc_checksum_two(num_list):
for i, first in enumerate(num_list):
for j, second in enumerate(num_list):
if i == j:
continue
if first % second == 0 and first / second > 0:
return first / second
checksums = []
new_checksums = []
for line in INPUT.split("\n"):
checksums.append(calc_checksum([int(x) for x in line.strip().split()]))
new_checksums.append(calc_checksum_two([int(x) for x in line.strip().split()]))
print("Line checksums: %r" % checksums)
print("New line checksums: %r" % new_checksums)
print("Total checksum: %d" % sum(checksums))
print("Total new checksum: %d" % sum(new_checksums)) | input = '1919\t2959\t82\t507\t3219\t239\t3494\t1440\t3107\t259\t3544\t683\t207\t562\t276\t2963\n587\t878\t229\t2465\t2575\t1367\t2017\t154\t152\t157\t2420\t2480\t138\t2512\t2605\t876\n744\t6916\t1853\t1044\t2831\t4797\t213\t4874\t187\t6051\t6086\t7768\t5571\t6203\t247\t285\n1210\t1207\t1130\t116\t1141\t563\t1056\t155\t227\t1085\t697\t735\t192\t1236\t1065\t156\n682\t883\t187\t307\t269\t673\t290\t693\t199\t132\t505\t206\t231\t200\t760\t612\n1520\t95\t1664\t1256\t685\t1446\t253\t88\t92\t313\t754\t1402\t734\t716\t342\t107\n146\t1169\t159\t3045\t163\t3192\t1543\t312\t161\t3504\t3346\t3231\t771\t3430\t3355\t3537\n177\t2129\t3507\t3635\t2588\t3735\t3130\t980\t324\t266\t1130\t3753\t175\t229\t517\t3893\n4532\t164\t191\t5169\t4960\t3349\t3784\t3130\t5348\t5036\t2110\t151\t5356\t193\t1380\t3580\n2544\t3199\t3284\t3009\t3400\t953\t3344\t3513\t102\t1532\t161\t143\t2172\t2845\t136\t2092\n194\t5189\t3610\t4019\t210\t256\t5178\t4485\t5815\t5329\t5457\t248\t5204\t4863\t5880\t3754\n3140\t4431\t4534\t4782\t3043\t209\t216\t5209\t174\t161\t3313\t5046\t1160\t160\t4036\t111\n2533\t140\t4383\t1581\t139\t141\t2151\t2104\t2753\t4524\t4712\t866\t3338\t2189\t116\t4677\n1240\t45\t254\t1008\t1186\t306\t633\t1232\t1457\t808\t248\t1166\t775\t1418\t1175\t287\n851\t132\t939\t1563\t539\t1351\t1147\t117\t1484\t100\t123\t490\t152\t798\t1476\t543\n1158\t2832\t697\t113\t121\t397\t1508\t118\t2181\t2122\t809\t2917\t134\t2824\t3154\t2791'
def calc_checksum(num_list):
return max(num_list) - min(num_list)
def calc_checksum_two(num_list):
for (i, first) in enumerate(num_list):
for (j, second) in enumerate(num_list):
if i == j:
continue
if first % second == 0 and first / second > 0:
return first / second
checksums = []
new_checksums = []
for line in INPUT.split('\n'):
checksums.append(calc_checksum([int(x) for x in line.strip().split()]))
new_checksums.append(calc_checksum_two([int(x) for x in line.strip().split()]))
print('Line checksums: %r' % checksums)
print('New line checksums: %r' % new_checksums)
print('Total checksum: %d' % sum(checksums))
print('Total new checksum: %d' % sum(new_checksums)) |
class Microstate():
def __init__(self):
self.index = None
self.label = None
self.weight = 0.0
self.probability = 0.0
self.basin = None
self.coordinates = None
self.color = None
self.size = None
| class Microstate:
def __init__(self):
self.index = None
self.label = None
self.weight = 0.0
self.probability = 0.0
self.basin = None
self.coordinates = None
self.color = None
self.size = None |
intraband_incharge = {
"WEIMIN": None,
"EBREAK": None,
"DEPER": None,
"TIME": None,
}
| intraband_incharge = {'WEIMIN': None, 'EBREAK': None, 'DEPER': None, 'TIME': None} |
program_name = 'giraf'
program_desc = 'A command line utility to access imgur.com.'
| program_name = 'giraf'
program_desc = 'A command line utility to access imgur.com.' |
def profile_likelihood_maximization(U, n_elbows, threshold):
"""
Inputs
U - An ordered or unordered list of eigenvalues
n - The number of elbows to return
Return
elbows - A numpy array containing elbows
"""
if type(U) == list: # cast to array for functionality later
U = np.array(U)
if type(U) is not np.ndarray: # only support arrays, lists
return np.array([])
if n_elbows == 0: # nothing to do..
return np.array([])
if U.ndim == 2:
U = np.std(U, axis = 0)
U = U[U > threshold]
if len(U) == 0:
return np.array([])
elbows = []
if len(U) == 1:
return np.array(elbows.append(U[0]))
# select values greater than the threshold
U.sort() # sort
U = U[::-1] # reverse array so that it is sorted in descending order
while len(elbows) < n_elbows and len(U) > 1:
d = 1
sample_var = np.var(U, ddof = 1)
sample_scale = sample_var**(1/2)
elbow = 0
likelihood_elbow = 0
while d < len(U):
mean_sig = np.mean(U[:d])
mean_noise = np.mean(U[d:])
sig_likelihood = 0
noise_likelihood = 0
for i in range(d):
sig_likelihood += norm.pdf(U[i], mean_sig, sample_scale)
for i in range(d, len(U)):
noise_likelihood += norm.pdf(U[i], mean_noise, sample_scale)
likelihood = noise_likelihood + sig_likelihood
if likelihood > likelihood_elbow:
likelihood_elbow = likelihood
elbow = d
d += 1
elbows.append(U[elbow - 1])
U = U[elbow:]
if len(elbows) == n_elbows:
return np.array(elbows)
if len(U) == 0:
return np.array(elbows)
else:
elbows.append(U[0])
return np.array(elbows) | def profile_likelihood_maximization(U, n_elbows, threshold):
"""
Inputs
U - An ordered or unordered list of eigenvalues
n - The number of elbows to return
Return
elbows - A numpy array containing elbows
"""
if type(U) == list:
u = np.array(U)
if type(U) is not np.ndarray:
return np.array([])
if n_elbows == 0:
return np.array([])
if U.ndim == 2:
u = np.std(U, axis=0)
u = U[U > threshold]
if len(U) == 0:
return np.array([])
elbows = []
if len(U) == 1:
return np.array(elbows.append(U[0]))
U.sort()
u = U[::-1]
while len(elbows) < n_elbows and len(U) > 1:
d = 1
sample_var = np.var(U, ddof=1)
sample_scale = sample_var ** (1 / 2)
elbow = 0
likelihood_elbow = 0
while d < len(U):
mean_sig = np.mean(U[:d])
mean_noise = np.mean(U[d:])
sig_likelihood = 0
noise_likelihood = 0
for i in range(d):
sig_likelihood += norm.pdf(U[i], mean_sig, sample_scale)
for i in range(d, len(U)):
noise_likelihood += norm.pdf(U[i], mean_noise, sample_scale)
likelihood = noise_likelihood + sig_likelihood
if likelihood > likelihood_elbow:
likelihood_elbow = likelihood
elbow = d
d += 1
elbows.append(U[elbow - 1])
u = U[elbow:]
if len(elbows) == n_elbows:
return np.array(elbows)
if len(U) == 0:
return np.array(elbows)
else:
elbows.append(U[0])
return np.array(elbows) |