content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
load("//third_party:common.bzl", "err_out", "execute")
_LLVM_BINARIES = [
"clang",
"clang-cpp",
"ld.lld",
"llvm-ar",
"llvm-as",
"llvm-nm",
"llvm-objcopy",
"llvm-objdump",
"llvm-profdata",
"llvm-dwp",
"llvm-ranlib",
"llvm-readelf",
"llvm-strip",
"llvm-symbolizer",
]
_LLVM_VERSION_MINIMAL = "10.0.0"
def _label(filename):
return Label("//third_party/llvm_toolchain:{}".format(filename))
def _check_llvm_binaries(repository_ctx, llvm_dir):
for binary in _LLVM_BINARIES:
binary_path = "{}/bin/{}".format(llvm_dir, binary)
if not repository_ctx.path(binary_path).exists:
fail("{} doesn't exist".format(binary_path))
def _retrieve_clang_version(repository_ctx, clang_binary):
script_path = repository_ctx.path(Label("//third_party/llvm_toolchain:find_clang_version.py"))
python_bin = repository_ctx.which("python3")
result = execute(repository_ctx, [python_bin, script_path, clang_binary])
if result.return_code:
fail("Failed to run find_clang_version.py: {}".format(err_out(result)))
llvm_version = result.stdout.strip()
actual_version = [int(m) for m in llvm_version.split(".")]
minimal_version = [int(m) for m in _LLVM_VERSION_MINIMAL.split(".")]
if actual_version < minimal_version:
fail("Minimal llvm version supported is {}, got: {}".format(_LLVM_VERSION_MINIMAL, llvm_version))
return result.stdout.strip()
def _local_config_llvm_impl(repository_ctx):
llvm_dir = repository_ctx.os.environ.get("LLVM_DIR", None)
if not llvm_dir:
fail("LLVM_DIR not set.")
if llvm_dir.endswith("/"):
llvm_dir = llvm_dir[:-1]
_check_llvm_binaries(repository_ctx, llvm_dir)
clang_binary = "{}/bin/clang".format(llvm_dir)
llvm_version = _retrieve_clang_version(repository_ctx, clang_binary)
repository_ctx.symlink(_label("cc_toolchain_config.bzl"), "cc_toolchain_config.bzl")
arch = repository_ctx.execute(["uname", "-m"]).stdout.strip()
repository_ctx.template(
"toolchains.bzl",
_label("toolchains.bzl.tpl"),
{
"%{arch}": arch,
},
)
repository_ctx.template(
"BUILD",
_label("BUILD.tpl"),
{
"%{arch}": arch,
"%{llvm_dir}": llvm_dir,
"%{llvm_version}": llvm_version,
},
)
local_config_llvm = repository_rule(
implementation = _local_config_llvm_impl,
environ = ["LLVM_DIR"],
local = True,
configure = True,
)
| load('//third_party:common.bzl', 'err_out', 'execute')
_llvm_binaries = ['clang', 'clang-cpp', 'ld.lld', 'llvm-ar', 'llvm-as', 'llvm-nm', 'llvm-objcopy', 'llvm-objdump', 'llvm-profdata', 'llvm-dwp', 'llvm-ranlib', 'llvm-readelf', 'llvm-strip', 'llvm-symbolizer']
_llvm_version_minimal = '10.0.0'
def _label(filename):
return label('//third_party/llvm_toolchain:{}'.format(filename))
def _check_llvm_binaries(repository_ctx, llvm_dir):
for binary in _LLVM_BINARIES:
binary_path = '{}/bin/{}'.format(llvm_dir, binary)
if not repository_ctx.path(binary_path).exists:
fail("{} doesn't exist".format(binary_path))
def _retrieve_clang_version(repository_ctx, clang_binary):
script_path = repository_ctx.path(label('//third_party/llvm_toolchain:find_clang_version.py'))
python_bin = repository_ctx.which('python3')
result = execute(repository_ctx, [python_bin, script_path, clang_binary])
if result.return_code:
fail('Failed to run find_clang_version.py: {}'.format(err_out(result)))
llvm_version = result.stdout.strip()
actual_version = [int(m) for m in llvm_version.split('.')]
minimal_version = [int(m) for m in _LLVM_VERSION_MINIMAL.split('.')]
if actual_version < minimal_version:
fail('Minimal llvm version supported is {}, got: {}'.format(_LLVM_VERSION_MINIMAL, llvm_version))
return result.stdout.strip()
def _local_config_llvm_impl(repository_ctx):
llvm_dir = repository_ctx.os.environ.get('LLVM_DIR', None)
if not llvm_dir:
fail('LLVM_DIR not set.')
if llvm_dir.endswith('/'):
llvm_dir = llvm_dir[:-1]
_check_llvm_binaries(repository_ctx, llvm_dir)
clang_binary = '{}/bin/clang'.format(llvm_dir)
llvm_version = _retrieve_clang_version(repository_ctx, clang_binary)
repository_ctx.symlink(_label('cc_toolchain_config.bzl'), 'cc_toolchain_config.bzl')
arch = repository_ctx.execute(['uname', '-m']).stdout.strip()
repository_ctx.template('toolchains.bzl', _label('toolchains.bzl.tpl'), {'%{arch}': arch})
repository_ctx.template('BUILD', _label('BUILD.tpl'), {'%{arch}': arch, '%{llvm_dir}': llvm_dir, '%{llvm_version}': llvm_version})
local_config_llvm = repository_rule(implementation=_local_config_llvm_impl, environ=['LLVM_DIR'], local=True, configure=True) |
valid=False
def marray(arr,*args,**kwargs):
return arr
def unitsDict(*args,**kwargs):
return None
def varMeta(*args,**kwargs):
return None
| valid = False
def marray(arr, *args, **kwargs):
return arr
def units_dict(*args, **kwargs):
return None
def var_meta(*args, **kwargs):
return None |
{
'OS-EXT-STS:task_state': None,
'addresses':
{'int-net':
[
{'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22',
'version': 4,
'addr': '192.168.1.8',
'OS-EXT-IPS:type': 'fixed'
},
{'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22',
'version': 4,
'addr': '192.168.166.23',
'OS-EXT-IPS:type': 'floating'
}
]
},
'OS-EXT-STS:vm_state': 'active',
'OS-EXT-SRV-ATTR:instance_name': 'instance-00000002',
'OS-SRV-USG:launched_at': '2018-10-26T09:36:46.000000',
'id': '61205745-b2bf-4db0-ad50-e7a60bf08bd5',
'security_groups': [{'name': 'defalt'}],
'user_id': 'd2fcc0c45a134de28dba429dbef2c3ba',
'progress': 0,
'OS-EXT-STS:power_state': 1,
'OS-EXT-AZ:availability_zone': 'nova',
'status': 'ACTIVE',
'updated': '2018-10-26T09:36:46Z',
'hostId': '1b6fa73a7ea8e40dc812954fe751d3aa812e6b52489ddb5360f5d36e',
'OS-EXT-SRV-ATTR:host': 'control-node',
'OS-SRV-USG:terminated_at': None,
'OS-EXT-SRV-ATTR:hypervisor_hostname': 'control-node',
'name': 'test',
'created': '2018-10-26T09:36:38Z',
'tenant_id': 'a95424bbdca6410092073d564f1f4012',
}
# ip netns add ns1
# ovs-vsctl add-port br-int tap0 tag=1 -- set Interface tap0 type=internal
# ip a
# ovs-vsctl show
# ip link set tap0 netns ns1
# ip netns exec ns1 ip addr add 192.168.1.3/24 dev tap0
# ip netns exec ns1 ifconfig tap0 promisc up
# ip netns exec ns1 ip a
# ip netns exec ns1 ping 192.168.1.1
# ip netns add ns1
# ip netns show
# ip netns exec ns1 ip a
# ip netns exec ns1 ip tuntap add tap0 mode tap
# ip netns exec ns1 ip a
# ip netns exec ns1 ip aadr add 192.168.1.3/24 dev tap0
# ip netns exec ns1 ip addr add 192.168.1.3/24 dev tap0
# ip netns exec ns1 ip a
# ip netns exec ns1 ip set tap0 up
# ip netns exec ns1 ip link set tap0 up
# ovs-ofctl dump-ports br-int qvo3ef787ad-67
# ovs-vsctl list interface br-ex
| {'OS-EXT-STS:task_state': None, 'addresses': {'int-net': [{'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22', 'version': 4, 'addr': '192.168.1.8', 'OS-EXT-IPS:type': 'fixed'}, {'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22', 'version': 4, 'addr': '192.168.166.23', 'OS-EXT-IPS:type': 'floating'}]}, 'OS-EXT-STS:vm_state': 'active', 'OS-EXT-SRV-ATTR:instance_name': 'instance-00000002', 'OS-SRV-USG:launched_at': '2018-10-26T09:36:46.000000', 'id': '61205745-b2bf-4db0-ad50-e7a60bf08bd5', 'security_groups': [{'name': 'defalt'}], 'user_id': 'd2fcc0c45a134de28dba429dbef2c3ba', 'progress': 0, 'OS-EXT-STS:power_state': 1, 'OS-EXT-AZ:availability_zone': 'nova', 'status': 'ACTIVE', 'updated': '2018-10-26T09:36:46Z', 'hostId': '1b6fa73a7ea8e40dc812954fe751d3aa812e6b52489ddb5360f5d36e', 'OS-EXT-SRV-ATTR:host': 'control-node', 'OS-SRV-USG:terminated_at': None, 'OS-EXT-SRV-ATTR:hypervisor_hostname': 'control-node', 'name': 'test', 'created': '2018-10-26T09:36:38Z', 'tenant_id': 'a95424bbdca6410092073d564f1f4012'} |
with open('input.txt') as f:
lines = f.readlines()
count = 0
curDepth = 0
for line in lines:
newDepth = int(line)
if curDepth != 0:
if newDepth > curDepth:
count += 1
curDepth = newDepth
print(count)
| with open('input.txt') as f:
lines = f.readlines()
count = 0
cur_depth = 0
for line in lines:
new_depth = int(line)
if curDepth != 0:
if newDepth > curDepth:
count += 1
cur_depth = newDepth
print(count) |
def add(x, y=3):
print(x + y)
add(5) # 8
add(5, 8) # 13
add(y=3) # Error, missing x
# -- Order of default parameters --
# def add(x=5, y): # Not OK, default parameters must go after non-default
# print(x + y)
# -- Usually don't use variables as default value --
default_y = 3
def add(x, y=default_y):
sum = x + y
print(sum)
add(2) # 5
default_y = 4
print(default_y) # 4
add(2) # 5, even though we re-defined default_y
| def add(x, y=3):
print(x + y)
add(5)
add(5, 8)
add(y=3)
default_y = 3
def add(x, y=default_y):
sum = x + y
print(sum)
add(2)
default_y = 4
print(default_y)
add(2) |
'''
Filippo Aleotti
filippo.aleotti2@unibo.it
29 November 2019
I PROFESSIONAL MASTER'S PROGRAM, II LEVEL "SIMUR", Imola 2019
Given a list of integer, store the frequency of each value in a dict, where the key is the value.
'''
def are_equals(dict1, dict2):
''' check if two dict are equal.
Both the dicts have str keys and integer values
'''
for k,v in dict1.items():
if k not in dict2.keys():
return False
if dict2[k] != v:
return False
return True
def frequency_extractor(input_list):
output_dict = {}
for element in input_list:
if str(element) not in output_dict.keys():
output_dict[str(element)] = 1
else:
output_dict[str(element)] += 1
return output_dict
frequency_1 = frequency_extractor([0,1,0,2,2,1,2,1,0,0,2,1,1])
frequency_2 = frequency_extractor([1,2,2,2,0,5,3])
assert are_equals(frequency_1, {'0':4,'1':5,'2':4})
assert are_equals(frequency_2, {'0':1,'1':1,'2':3,'3':1,'5':1})
| """
Filippo Aleotti
filippo.aleotti2@unibo.it
29 November 2019
I PROFESSIONAL MASTER'S PROGRAM, II LEVEL "SIMUR", Imola 2019
Given a list of integer, store the frequency of each value in a dict, where the key is the value.
"""
def are_equals(dict1, dict2):
""" check if two dict are equal.
Both the dicts have str keys and integer values
"""
for (k, v) in dict1.items():
if k not in dict2.keys():
return False
if dict2[k] != v:
return False
return True
def frequency_extractor(input_list):
output_dict = {}
for element in input_list:
if str(element) not in output_dict.keys():
output_dict[str(element)] = 1
else:
output_dict[str(element)] += 1
return output_dict
frequency_1 = frequency_extractor([0, 1, 0, 2, 2, 1, 2, 1, 0, 0, 2, 1, 1])
frequency_2 = frequency_extractor([1, 2, 2, 2, 0, 5, 3])
assert are_equals(frequency_1, {'0': 4, '1': 5, '2': 4})
assert are_equals(frequency_2, {'0': 1, '1': 1, '2': 3, '3': 1, '5': 1}) |
#!/usr/bin/env python
print("Hello from cx_Freeze Advanced #1\n")
module = __import__("testfreeze_1")
| print('Hello from cx_Freeze Advanced #1\n')
module = __import__('testfreeze_1') |
# Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
def even_or_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
assert (even_or_odd(2)) == "Even", "Debe devolver Even"
assert (even_or_odd(0)) == "Even", "Debe devolver Even"
assert (even_or_odd(7)) == "Odd", "Debe devolver Odd"
assert (even_or_odd(1)) == "Odd", "Debe devolver Odd" | def even_or_odd(number):
if number % 2 == 0:
return 'Even'
else:
return 'Odd'
assert even_or_odd(2) == 'Even', 'Debe devolver Even'
assert even_or_odd(0) == 'Even', 'Debe devolver Even'
assert even_or_odd(7) == 'Odd', 'Debe devolver Odd'
assert even_or_odd(1) == 'Odd', 'Debe devolver Odd' |
n = int(input())
L = list(map(int,input().split()))
A = list(set(L[:]))
d = {}
A.sort()
for i in range(len(A)):
d[A[i]] = i
for i in L:
print(d[i],end = " ") | n = int(input())
l = list(map(int, input().split()))
a = list(set(L[:]))
d = {}
A.sort()
for i in range(len(A)):
d[A[i]] = i
for i in L:
print(d[i], end=' ') |
# Url https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
class Solution:
def subtractProductAndSum(self, n):
prod, sum_n, curr = 1, 0, 0
while n != 0:
curr = n % 10
prod = prod * curr
sum_n = sum_n + curr
n = n//10
return prod - sum_n
if __name__ == '__main__':
a = Solution()
print(a.subtractProductAndSum(234))
| class Solution:
def subtract_product_and_sum(self, n):
(prod, sum_n, curr) = (1, 0, 0)
while n != 0:
curr = n % 10
prod = prod * curr
sum_n = sum_n + curr
n = n // 10
return prod - sum_n
if __name__ == '__main__':
a = solution()
print(a.subtractProductAndSum(234)) |
# Work out the first ten digits of the sum of N 50 digit numbers.
total = 0
for x in range(int(input())):
total += int(input().rstrip())
print(str(total)[:10])
| total = 0
for x in range(int(input())):
total += int(input().rstrip())
print(str(total)[:10]) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:
class TaskName():
Classify_Task = "classify"
Detect2d_Task = "detect2d"
Segment_Task = "segment"
PC_Classify_Task = "pc_classify"
| class Taskname:
classify__task = 'classify'
detect2d__task = 'detect2d'
segment__task = 'segment'
pc__classify__task = 'pc_classify' |
class TheEquation:
def leastSum(self, X, Y, P):
m = 2*P
for i in xrange(1, P+1):
for j in xrange(1, P+1):
if (X*i + Y*j)%P == 0:
m = min(m, i+j)
return m
| class Theequation:
def least_sum(self, X, Y, P):
m = 2 * P
for i in xrange(1, P + 1):
for j in xrange(1, P + 1):
if (X * i + Y * j) % P == 0:
m = min(m, i + j)
return m |
#!/usr/bin/env python3
class FakeSerial:
def __init__(self):
self._last_written_data = None
self._response = None
self.read_data = []
@property
def last_written_data(self):
return self._last_written_data
@property
def response(self):
return self._response
@response.setter
def response(self, value):
self._response = bytearray(value)
def write(self, data):
self._last_written_data = data
def read(self):
while self._response:
yield bytes([self._response.pop(0)])
def read_until(self, expected):
output = b''
for b in self.read():
if b == expected:
break
output += b
return output
| class Fakeserial:
def __init__(self):
self._last_written_data = None
self._response = None
self.read_data = []
@property
def last_written_data(self):
return self._last_written_data
@property
def response(self):
return self._response
@response.setter
def response(self, value):
self._response = bytearray(value)
def write(self, data):
self._last_written_data = data
def read(self):
while self._response:
yield bytes([self._response.pop(0)])
def read_until(self, expected):
output = b''
for b in self.read():
if b == expected:
break
output += b
return output |
# coding=utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x, next=None):
self.val = x
self.next = next
class DoubleNode(object):
def __init__(self, key, val, pre=None, next=None):
self.key = key
self.val = val
self.pre = pre
self.next = next
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class TrieNode(object):
def __init__(self, end=False):
self.children = []
for i in range(26):
self.children.append(None)
self.end = end
def set_end(self):
self.end = True
@property
def is_end(self):
return self.end
class RandomNode(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
class GraphNode(object):
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
class QuadTreeNode(object):
def __init__(self, val, is_leaf, top_left,
top_right, bottom_left, bottom_right):
self.val = val
self.is_leaf = is_leaf
self.top_left = top_left
self.top_right = top_right
self.bottom_left = bottom_left
self.bottom_right = bottom_right
| class Listnode(object):
def __init__(self, x, next=None):
self.val = x
self.next = next
class Doublenode(object):
def __init__(self, key, val, pre=None, next=None):
self.key = key
self.val = val
self.pre = pre
self.next = next
class Treenode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Trienode(object):
def __init__(self, end=False):
self.children = []
for i in range(26):
self.children.append(None)
self.end = end
def set_end(self):
self.end = True
@property
def is_end(self):
return self.end
class Randomnode(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
class Graphnode(object):
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
class Quadtreenode(object):
def __init__(self, val, is_leaf, top_left, top_right, bottom_left, bottom_right):
self.val = val
self.is_leaf = is_leaf
self.top_left = top_left
self.top_right = top_right
self.bottom_left = bottom_left
self.bottom_right = bottom_right |
seen = []
# Prduces the length of the longest Substring
# thats comprised of just unique characters
def max_diff(string):
seen = [0]*256
curr_start = 0
max_start = 0
unique = 0
max_unique = 0
for n,i in enumerate(string):
if seen[assn_num(i)] == 0:
unique += 1
else:
if unique > max_unique:
max_unique = unique
while unique > 1:
if seen[assn_num(string[curr_start])] == 1:
unique -= 1
seen[assn_num(string[curr_start])] -= 1
curr_start += 1
else:
seen[assn_num(string[curr_start])] -= 1
curr_start += 1
seen[assn_num(i)] += 1
if unique > max_unique:
max_unique = unique
return max_unique
def assn_num(char):
num = ord(char)-ord('a')
return num | seen = []
def max_diff(string):
seen = [0] * 256
curr_start = 0
max_start = 0
unique = 0
max_unique = 0
for (n, i) in enumerate(string):
if seen[assn_num(i)] == 0:
unique += 1
else:
if unique > max_unique:
max_unique = unique
while unique > 1:
if seen[assn_num(string[curr_start])] == 1:
unique -= 1
seen[assn_num(string[curr_start])] -= 1
curr_start += 1
else:
seen[assn_num(string[curr_start])] -= 1
curr_start += 1
seen[assn_num(i)] += 1
if unique > max_unique:
max_unique = unique
return max_unique
def assn_num(char):
num = ord(char) - ord('a')
return num |
def _test_sources_aspect_impl(target, ctx):
result = depset()
if hasattr(ctx.rule.attr, "tags") and "NODE_MODULE_MARKER" in ctx.rule.attr.tags:
return struct(node_test_sources=result)
if hasattr(ctx.rule.attr, "deps"):
for dep in ctx.rule.attr.deps:
if hasattr(dep, "node_test_sources"):
result = depset(transitive=[result, dep.node_test_sources])
elif hasattr(target, "files"):
result = depset([f for f in target.files.to_list() if f.path.endswith(".test.js")],
transitive=[result])
return struct(node_test_sources=result)
test_sources_aspect = aspect(
_test_sources_aspect_impl,
attr_aspects=["deps"],
)
| def _test_sources_aspect_impl(target, ctx):
result = depset()
if hasattr(ctx.rule.attr, 'tags') and 'NODE_MODULE_MARKER' in ctx.rule.attr.tags:
return struct(node_test_sources=result)
if hasattr(ctx.rule.attr, 'deps'):
for dep in ctx.rule.attr.deps:
if hasattr(dep, 'node_test_sources'):
result = depset(transitive=[result, dep.node_test_sources])
elif hasattr(target, 'files'):
result = depset([f for f in target.files.to_list() if f.path.endswith('.test.js')], transitive=[result])
return struct(node_test_sources=result)
test_sources_aspect = aspect(_test_sources_aspect_impl, attr_aspects=['deps']) |
def is_prime(n):
if n > 1:
for i in range(2, n // 2 + 1):
if (n % i) == 0:
return False
else:
return True
else:
return False
def fibonacci(n):
n1, n2 = 1, 1
count = 0
if n == 1:
print(n1)
else:
while count < n:
if not is_prime(n1) and n1 % 5 != 0:
print(n1, end=' ')
else:
print(0, end=' ')
n3 = n1 + n2
n1 = n2
n2 = n3
count += 1
n = int(input("Enter the number:"))
fibonacci(n)
| def is_prime(n):
if n > 1:
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
else:
return True
else:
return False
def fibonacci(n):
(n1, n2) = (1, 1)
count = 0
if n == 1:
print(n1)
else:
while count < n:
if not is_prime(n1) and n1 % 5 != 0:
print(n1, end=' ')
else:
print(0, end=' ')
n3 = n1 + n2
n1 = n2
n2 = n3
count += 1
n = int(input('Enter the number:'))
fibonacci(n) |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
running_min = prices[0]
best_trans1 = [0]
for p in prices[1:]:
if p < running_min:
running_min = p
best_trans1.append(max(p - running_min, best_trans1[-1]))
running_max = prices[-1]
best = best_trans1.pop()
best_trans2 = 0
for p in prices[:0:-1]:
if p > running_max:
running_max = p
if running_max - p > best_trans2:
best_trans2 = running_max - p
trans1 = best_trans1.pop()
if best_trans2 + trans1 > best:
best = best_trans2 + trans1
return best
| class Solution:
def max_profit(self, prices: List[int]) -> int:
running_min = prices[0]
best_trans1 = [0]
for p in prices[1:]:
if p < running_min:
running_min = p
best_trans1.append(max(p - running_min, best_trans1[-1]))
running_max = prices[-1]
best = best_trans1.pop()
best_trans2 = 0
for p in prices[:0:-1]:
if p > running_max:
running_max = p
if running_max - p > best_trans2:
best_trans2 = running_max - p
trans1 = best_trans1.pop()
if best_trans2 + trans1 > best:
best = best_trans2 + trans1
return best |
version = "dev 0.0"
running = False
def init():
global running
if not running:
print("JFUtils-python \"" + version + "\" by jonnelafin")
running = True
| version = 'dev 0.0'
running = False
def init():
global running
if not running:
print('JFUtils-python "' + version + '" by jonnelafin')
running = True |
class FiniteAutomataState:
def __init__(self, structure):
self.states = []
self.alphabet = []
self.initial = []
self.finals = []
self.transitions = {}
self._file = open(structure, "r")
self._load()
# print(self.validate())
def _load(self):
reading = "none"
reading = "none"
line = self._file.readline()
def classify(mode, probe):
if mode == "states":
spec = probe.split(', ')
self.states.extend(spec)
elif mode == "initial":
spec = probe.split(', ')
self.initial.extend(spec)
elif mode == "alpha":
spec = probe.split(', ')
self.alphabet.extend(spec)
elif mode == "trans":
values = probe.split(", ")
if (values[0], values[1]) in self.transitions.keys():
self.transitions[(values[0], values[1])].append(values[2])
else:
self.transitions[(values[0], values[1])] = [values[2]]
elif mode == "final":
tokens = probe.split(", ")
self.finals.extend(tokens)
while line:
if line.strip()[0] == '#':
reading = line.strip()[1:]
else:
classify(reading, line.strip())
line = self._file.readline()
def validate(self):
if self.initial[0] not in self.states:
return False
for final in self.finals:
if final not in self.states:
return False
for key in self.transitions.keys():
state = key[0]
symbol = key[1]
if state not in self.states or symbol not in self.alphabet:
return False
for dest in self.transitions[key]:
if dest not in self.states:
return False
return True
def dfa(self):
for key in self.transitions.keys():
if len(self.transitions[key]) > 1:
return False
return True
def accepted(self, sequence):
if self.dfa():
crt = self.initial[0]
for symbol in sequence:
if (crt, symbol) in self.transitions.keys():
crt = self.transitions[(crt, symbol)][0]
else:
return False
return crt in self.finals
return False | class Finiteautomatastate:
def __init__(self, structure):
self.states = []
self.alphabet = []
self.initial = []
self.finals = []
self.transitions = {}
self._file = open(structure, 'r')
self._load()
def _load(self):
reading = 'none'
reading = 'none'
line = self._file.readline()
def classify(mode, probe):
if mode == 'states':
spec = probe.split(', ')
self.states.extend(spec)
elif mode == 'initial':
spec = probe.split(', ')
self.initial.extend(spec)
elif mode == 'alpha':
spec = probe.split(', ')
self.alphabet.extend(spec)
elif mode == 'trans':
values = probe.split(', ')
if (values[0], values[1]) in self.transitions.keys():
self.transitions[values[0], values[1]].append(values[2])
else:
self.transitions[values[0], values[1]] = [values[2]]
elif mode == 'final':
tokens = probe.split(', ')
self.finals.extend(tokens)
while line:
if line.strip()[0] == '#':
reading = line.strip()[1:]
else:
classify(reading, line.strip())
line = self._file.readline()
def validate(self):
if self.initial[0] not in self.states:
return False
for final in self.finals:
if final not in self.states:
return False
for key in self.transitions.keys():
state = key[0]
symbol = key[1]
if state not in self.states or symbol not in self.alphabet:
return False
for dest in self.transitions[key]:
if dest not in self.states:
return False
return True
def dfa(self):
for key in self.transitions.keys():
if len(self.transitions[key]) > 1:
return False
return True
def accepted(self, sequence):
if self.dfa():
crt = self.initial[0]
for symbol in sequence:
if (crt, symbol) in self.transitions.keys():
crt = self.transitions[crt, symbol][0]
else:
return False
return crt in self.finals
return False |
#!/usr/bin/python
compteur = 0
i,j = 3,1
terrain = []
fichier = open('day3_input.txt')
for l in fichier:
terrain.append(fichier.readline().strip('\n'))
nblig = len(terrain)
nbcol = len(terrain[0])
print('nblig : %s / nbcol : %s' % (nblig,nbcol))
for f in terrain:
print(f)
while j<nblig:
#print(i,j,terrain[j][i],compteur)
if terrain[j][i] == '#':
compteur = compteur +1
print(terrain[j][0:i-1]+'X'+terrain[j][i+1:nbcol-1])
else:
print(terrain[j][0:i-1]+'O'+terrain[j][i+1:nbcol-1])
i = (i+3)%nbcol
j = j+1
print(compteur) | compteur = 0
(i, j) = (3, 1)
terrain = []
fichier = open('day3_input.txt')
for l in fichier:
terrain.append(fichier.readline().strip('\n'))
nblig = len(terrain)
nbcol = len(terrain[0])
print('nblig : %s / nbcol : %s' % (nblig, nbcol))
for f in terrain:
print(f)
while j < nblig:
if terrain[j][i] == '#':
compteur = compteur + 1
print(terrain[j][0:i - 1] + 'X' + terrain[j][i + 1:nbcol - 1])
else:
print(terrain[j][0:i - 1] + 'O' + terrain[j][i + 1:nbcol - 1])
i = (i + 3) % nbcol
j = j + 1
print(compteur) |
dicionario_sites = {"Diego": "diegomariano.com"}
print(dicionario_sites['Diego'])
dicionario_sites = {"Diego": "diegomariano.com", "Google": "google.com", "Udemy": "udemy.com", "Luiz Carlin" : "luizcarlin.com.br"}
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for chave in dicionario_sites:
print (chave + " -:- " +dicionario_sites[chave])
print(dicionario_sites[chave])
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for i in dicionario_sites.items():
print(i)
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for i in dicionario_sites.values():
print(i)
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for i in dicionario_sites.keys():
print(i) | dicionario_sites = {'Diego': 'diegomariano.com'}
print(dicionario_sites['Diego'])
dicionario_sites = {'Diego': 'diegomariano.com', 'Google': 'google.com', 'Udemy': 'udemy.com', 'Luiz Carlin': 'luizcarlin.com.br'}
print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=')
for chave in dicionario_sites:
print(chave + ' -:- ' + dicionario_sites[chave])
print(dicionario_sites[chave])
print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=')
for i in dicionario_sites.items():
print(i)
print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=')
for i in dicionario_sites.values():
print(i)
print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=')
for i in dicionario_sites.keys():
print(i) |
# -*- coding: utf-8 -*-
# Author: Tonio Teran <tonio@stateoftheart.ai>
# Copyright: Stateoftheart AI PBC 2021.
'''RLlib's library wrapper.'''
SOURCE_METADATA = {
'name': 'rllib',
'original_name': 'RLlib',
'url': 'https://docs.ray.io/en/master/rllib.html'
}
MODELS = {
'discrete': [
'A2C', 'A3C', 'ARS', 'BC', 'ES', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA',
'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'SlateQ', 'LinUCB',
'LinTS', 'AlphaZero', 'QMIX', 'MADDPG', 'Curiosity'
],
'continuous': [
'A2C',
'A3C',
'ARS',
'BC',
'CQL',
'ES',
# 'DDPG',
'TD3',
'APEX-DDPG',
'Dreamer',
'IMPALA',
'MAML',
'MARWIL',
'MBMPO',
'PG',
'PPO',
'APPO',
'SAC',
'MADDPG'
],
'multi-agent': [
'A2C',
'A3C',
'BC',
# 'DDPG',
'TD3',
'APEX-DDPG',
'DQN',
'Rainbow',
'APEX-DQN',
'IMPALA',
'MARWIL',
'PG',
'PPO',
'APPO',
'R2D2',
'SAC',
'LinUCB',
'LinTS',
'QMIX',
'MADDPG',
'Curiosity'
],
'unknown': [
'ParameterSharing', 'FullyIndependentLearning', 'SharedCriticMethods'
],
}
def load_model(name: str) -> dict:
return {'name': name, 'source': 'rllib'}
| """RLlib's library wrapper."""
source_metadata = {'name': 'rllib', 'original_name': 'RLlib', 'url': 'https://docs.ray.io/en/master/rllib.html'}
models = {'discrete': ['A2C', 'A3C', 'ARS', 'BC', 'ES', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA', 'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'SlateQ', 'LinUCB', 'LinTS', 'AlphaZero', 'QMIX', 'MADDPG', 'Curiosity'], 'continuous': ['A2C', 'A3C', 'ARS', 'BC', 'CQL', 'ES', 'TD3', 'APEX-DDPG', 'Dreamer', 'IMPALA', 'MAML', 'MARWIL', 'MBMPO', 'PG', 'PPO', 'APPO', 'SAC', 'MADDPG'], 'multi-agent': ['A2C', 'A3C', 'BC', 'TD3', 'APEX-DDPG', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA', 'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'LinUCB', 'LinTS', 'QMIX', 'MADDPG', 'Curiosity'], 'unknown': ['ParameterSharing', 'FullyIndependentLearning', 'SharedCriticMethods']}
def load_model(name: str) -> dict:
return {'name': name, 'source': 'rllib'} |
# Recursive, O(2^n)
def LCS(X, Y, m, n):
if m == 0 or n == 0:
return 0
elif X[m - 1] == Y[n - 1]:
return 1 + LCS(X, Y, m - 1, n - 1)
else:
return max(LCS(X, Y, m - 1, n), LCS(X, Y, m, n - 1))
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", LCS(X, Y, len(X), len(Y)))
# Overlapping Substructure, Tabulation, O(mn)
def LCS(X, Y):
m = len(X)
n = len(Y)
L = [[None] * (n + 1) for i in range(m + 1)]
# build L[m+1][n+1] bottom up
# L[i][j] contains length of LCS of X[0..i-1]
# and Y[0..j-1]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
# L[m][n] contains LCS of X[0..m-1] & Y[0..n-1]
return L[m][n]
X = "ABCDGH"
Y = "AEDFHR"
print("Length of LCS is ", LCS(X, Y))
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", LCS(X, Y))
| def lcs(X, Y, m, n):
if m == 0 or n == 0:
return 0
elif X[m - 1] == Y[n - 1]:
return 1 + lcs(X, Y, m - 1, n - 1)
else:
return max(lcs(X, Y, m - 1, n), lcs(X, Y, m, n - 1))
x = 'AGGTAB'
y = 'GXTXAYB'
print('Length of LCS is ', lcs(X, Y, len(X), len(Y)))
def lcs(X, Y):
m = len(X)
n = len(Y)
l = [[None] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
return L[m][n]
x = 'ABCDGH'
y = 'AEDFHR'
print('Length of LCS is ', lcs(X, Y))
x = 'AGGTAB'
y = 'GXTXAYB'
print('Length of LCS is ', lcs(X, Y)) |
class CalculoZ():
def calcular_z(self, n1, n2, x, y, ux, uy, ox, oy):
arriba = (x-y)-(ux-uy)
abajo = (((ox)**2/(n1))+((oy)**2/(n2)))**0.5
z = arriba/abajo
return z | class Calculoz:
def calcular_z(self, n1, n2, x, y, ux, uy, ox, oy):
arriba = x - y - (ux - uy)
abajo = (ox ** 2 / n1 + oy ** 2 / n2) ** 0.5
z = arriba / abajo
return z |
class Solution:
def intToRoman(self, num: int) -> str:
res = ""
s = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
index = 0
while num > 0:
x = num % 10
if x < 5:
if x == 4:
temp = s[index] + s[index + 1]
else:
temp = ""
while x > 0:
temp += s[index]
x -= 1
else:
if x == 9:
temp = s[index] + s[index + 2]
else:
temp = s[index + 1]
while x > 5:
temp += s[index]
x -= 1
index += 2
res = temp + res
num = num // 10
return res
if __name__ == '__main__':
print(
Solution().intToRoman(3), "III",
Solution().intToRoman(4), "IV",
Solution().intToRoman(9), "IX",
Solution().intToRoman(58), "LVIII",
Solution().intToRoman(1994), "MCMXCIV",
)
| class Solution:
def int_to_roman(self, num: int) -> str:
res = ''
s = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
index = 0
while num > 0:
x = num % 10
if x < 5:
if x == 4:
temp = s[index] + s[index + 1]
else:
temp = ''
while x > 0:
temp += s[index]
x -= 1
elif x == 9:
temp = s[index] + s[index + 2]
else:
temp = s[index + 1]
while x > 5:
temp += s[index]
x -= 1
index += 2
res = temp + res
num = num // 10
return res
if __name__ == '__main__':
print(solution().intToRoman(3), 'III', solution().intToRoman(4), 'IV', solution().intToRoman(9), 'IX', solution().intToRoman(58), 'LVIII', solution().intToRoman(1994), 'MCMXCIV') |
N, X, T = map(int, input().split())
time = N // X
if(N%X == 0):
print(time * T)
else:
print((time+1) * T) | (n, x, t) = map(int, input().split())
time = N // X
if N % X == 0:
print(time * T)
else:
print((time + 1) * T) |
class Token:
__slots__ = ('start', 'end')
def __init__(self, start: int=None, end: int=None):
self.start = start
self.end = end
@property
def type(self):
"Type of current token"
return self.__class__.__name__
def to_json(self):
return dict([(k, self.__getattribute__(k)) for k in dir(self) if not k.startswith('__') and k != 'to_json'])
class Chars:
Hash = '#'
Dollar = '$'
Dash = '-'
Dot = '.'
Colon = ':'
Comma = ','
Excl = '!'
At = '@'
Percent = '%'
Underscore = '_'
RoundBracketOpen = '('
RoundBracketClose = ')'
CurlyBracketOpen = '{'
CurlyBracketClose = '}'
Sibling = '+'
SingleQuote = "'"
DoubleQuote = '"'
Transparent = 't'
class OperatorType:
Sibling = '+'
Important = '!'
ArgumentDelimiter = ','
ValueDelimiter = '-'
PropertyDelimiter = ':'
class Operator(Token):
__slots__ = ('operator',)
def __init__(self, operator: OperatorType, *args):
super(Operator, self).__init__(*args)
self.operator = operator
class Bracket(Token):
__slots__ = ('open',)
def __init__(self, is_open: bool, *args):
super(Bracket, self).__init__(*args)
self.open = is_open
class Literal(Token):
__slots__ = ('value',)
def __init__(self, value: str, *args):
super(Literal, self).__init__(*args)
self.value = value
class NumberValue(Token):
__slots__ = ('value', 'raw_value', 'unit')
def __init__(self, value: int, raw_value: str, unit='', *args):
super(NumberValue, self).__init__(*args)
self.value = value
self.raw_value = raw_value
self.unit = unit
class ColorValue(Token):
__slots__ = ('r', 'g', 'b', 'a', 'raw')
def __init__(self, r=0, g=0, b=0, a=None, raw='', *args):
super(ColorValue, self).__init__(*args)
self.r = r
self.g = g
self.b = b
self.a = a if a is not None else 1
self.raw = raw
class StringValue(Token):
__slots__ = ('value', 'quote')
def __init__(self, value: str, quote='', *args):
super(StringValue, self).__init__(*args)
self.value = value
self.quote = quote
class Field(Token):
__slots__ = ('name', 'index')
def __init__(self, name: str, index: int=None, *args):
super(Field, self).__init__(*args)
self.index = index
self.name = name
class WhiteSpace(Token): pass
| class Token:
__slots__ = ('start', 'end')
def __init__(self, start: int=None, end: int=None):
self.start = start
self.end = end
@property
def type(self):
"""Type of current token"""
return self.__class__.__name__
def to_json(self):
return dict([(k, self.__getattribute__(k)) for k in dir(self) if not k.startswith('__') and k != 'to_json'])
class Chars:
hash = '#'
dollar = '$'
dash = '-'
dot = '.'
colon = ':'
comma = ','
excl = '!'
at = '@'
percent = '%'
underscore = '_'
round_bracket_open = '('
round_bracket_close = ')'
curly_bracket_open = '{'
curly_bracket_close = '}'
sibling = '+'
single_quote = "'"
double_quote = '"'
transparent = 't'
class Operatortype:
sibling = '+'
important = '!'
argument_delimiter = ','
value_delimiter = '-'
property_delimiter = ':'
class Operator(Token):
__slots__ = ('operator',)
def __init__(self, operator: OperatorType, *args):
super(Operator, self).__init__(*args)
self.operator = operator
class Bracket(Token):
__slots__ = ('open',)
def __init__(self, is_open: bool, *args):
super(Bracket, self).__init__(*args)
self.open = is_open
class Literal(Token):
__slots__ = ('value',)
def __init__(self, value: str, *args):
super(Literal, self).__init__(*args)
self.value = value
class Numbervalue(Token):
__slots__ = ('value', 'raw_value', 'unit')
def __init__(self, value: int, raw_value: str, unit='', *args):
super(NumberValue, self).__init__(*args)
self.value = value
self.raw_value = raw_value
self.unit = unit
class Colorvalue(Token):
__slots__ = ('r', 'g', 'b', 'a', 'raw')
def __init__(self, r=0, g=0, b=0, a=None, raw='', *args):
super(ColorValue, self).__init__(*args)
self.r = r
self.g = g
self.b = b
self.a = a if a is not None else 1
self.raw = raw
class Stringvalue(Token):
__slots__ = ('value', 'quote')
def __init__(self, value: str, quote='', *args):
super(StringValue, self).__init__(*args)
self.value = value
self.quote = quote
class Field(Token):
__slots__ = ('name', 'index')
def __init__(self, name: str, index: int=None, *args):
super(Field, self).__init__(*args)
self.index = index
self.name = name
class Whitespace(Token):
pass |
literals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()"
#obfuscated
literals = "tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX"
key = 7
def shuffle(plaintext):
shuffled = ""
# shuffle plaintext
for i in range(int(len(plaintext) / 3)):
block = plaintext[i*3] + plaintext[i*3 + 1] + plaintext[i*3 + 2]
old0 = block[0]
old1 = block[1]
old2 = block[2]
block = old2 + old0 + old1
shuffled += block
shuffled += plaintext[len(plaintext) - (len(plaintext) % 3):len(plaintext)]
return shuffled
def unshuffle(ciphertext):
unshuffled = ""
# unshuffle plaintext
for i in range(int(len(ciphertext) / 3)):
block = ciphertext[i*3] + ciphertext[i*3 + 1] + ciphertext[i*3 + 2]
old0 = block[0]
old1 = block[1]
old2 = block[2]
block = old1 + old2 + old0
unshuffled += block
unshuffled += ciphertext[len(ciphertext) - (len(ciphertext) % 3):len(ciphertext)]
return unshuffled
def shift(plaintext):
shifted = ""
# Cipher shift
tmp = []
for i in range(len(plaintext)):
pos = literals.find(plaintext[i])
if pos >= 0:
if pos + key > len(literals):
pos = (pos + key) - len(literals)
res = literals[pos + key]
else:
res = plaintext[i]
tmp.append(res)
# reconstruct ciphertext
for i in range(len(tmp)):
shifted += tmp[i]
return shifted
def unshift(ciphertext):
unshifted = ""
tmp = []
for i in range(len(ciphertext)):
pos = literals.find(ciphertext[i])
if pos >= 0:
if pos - key < 0:
pos = (pos - key) + len(literals)
res = literals[pos - key]
else:
res = ciphertext[i]
tmp.append(res)
#reconstruct ciphertext
for i in range(len(tmp)):
unshifted += tmp[i]
return unshifted
def encrypt(msg):
msg = shuffle(msg)
msg = shift(msg)
return msg
def decrypt(msg):
#msg = unshuffle(msg)
msg = unshift(msg)
msg = unshuffle(msg)
return msg
def test():
test = "This is my plaintext"
test = "\nThis is a long paragraph with lots of exciting things\nI could go on and on about all of this stuff.\nLove, Zach!"
test = "abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%^&*()"
print ("Testing: " + test)
print ("Shuffle: " + shuffle(test))
print ("Shift: " + shift(shuffle(test)))
print ("Unshift: " + unshift(shift(shuffle(test))))
print ("Unshuffle: " + unshuffle(unshift(shift(shuffle(test)))))
print ("")
print ("Encrypt: " + encrypt(test))
print ("Decrypt: " + decrypt(encrypt(test)))
if __name__ == "__main__":
test()
| literals = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()'
literals = 'tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX'
key = 7
def shuffle(plaintext):
shuffled = ''
for i in range(int(len(plaintext) / 3)):
block = plaintext[i * 3] + plaintext[i * 3 + 1] + plaintext[i * 3 + 2]
old0 = block[0]
old1 = block[1]
old2 = block[2]
block = old2 + old0 + old1
shuffled += block
shuffled += plaintext[len(plaintext) - len(plaintext) % 3:len(plaintext)]
return shuffled
def unshuffle(ciphertext):
unshuffled = ''
for i in range(int(len(ciphertext) / 3)):
block = ciphertext[i * 3] + ciphertext[i * 3 + 1] + ciphertext[i * 3 + 2]
old0 = block[0]
old1 = block[1]
old2 = block[2]
block = old1 + old2 + old0
unshuffled += block
unshuffled += ciphertext[len(ciphertext) - len(ciphertext) % 3:len(ciphertext)]
return unshuffled
def shift(plaintext):
shifted = ''
tmp = []
for i in range(len(plaintext)):
pos = literals.find(plaintext[i])
if pos >= 0:
if pos + key > len(literals):
pos = pos + key - len(literals)
res = literals[pos + key]
else:
res = plaintext[i]
tmp.append(res)
for i in range(len(tmp)):
shifted += tmp[i]
return shifted
def unshift(ciphertext):
unshifted = ''
tmp = []
for i in range(len(ciphertext)):
pos = literals.find(ciphertext[i])
if pos >= 0:
if pos - key < 0:
pos = pos - key + len(literals)
res = literals[pos - key]
else:
res = ciphertext[i]
tmp.append(res)
for i in range(len(tmp)):
unshifted += tmp[i]
return unshifted
def encrypt(msg):
msg = shuffle(msg)
msg = shift(msg)
return msg
def decrypt(msg):
msg = unshift(msg)
msg = unshuffle(msg)
return msg
def test():
test = 'This is my plaintext'
test = '\nThis is a long paragraph with lots of exciting things\nI could go on and on about all of this stuff.\nLove, Zach!'
test = 'abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%^&*()'
print('Testing: ' + test)
print('Shuffle: ' + shuffle(test))
print('Shift: ' + shift(shuffle(test)))
print('Unshift: ' + unshift(shift(shuffle(test))))
print('Unshuffle: ' + unshuffle(unshift(shift(shuffle(test)))))
print('')
print('Encrypt: ' + encrypt(test))
print('Decrypt: ' + decrypt(encrypt(test)))
if __name__ == '__main__':
test() |
curupira = int(input())
boitata = int(input())
boto = int(input())
mapinguari = int(input())
lara = int(input())
total = 225 + (curupira * 300) + (boitata *1500) + (boto * 600) + (mapinguari * 1000)+(lara*150)
print(total) | curupira = int(input())
boitata = int(input())
boto = int(input())
mapinguari = int(input())
lara = int(input())
total = 225 + curupira * 300 + boitata * 1500 + boto * 600 + mapinguari * 1000 + lara * 150
print(total) |
class Sibling:
pass
| class Sibling:
pass |
if True:
foo = 42
else:
foo = None
| if True:
foo = 42
else:
foo = None |
#!/usr/bin/python3
print("Sum of even-valued terms less than four million in the Fibonacci sequence:")
a, b, sum = 1, 1, 0
while b < 4000000:
sum += b if b % 2 == 0 else 0
a, b = b, a + b
print(sum)
| print('Sum of even-valued terms less than four million in the Fibonacci sequence:')
(a, b, sum) = (1, 1, 0)
while b < 4000000:
sum += b if b % 2 == 0 else 0
(a, b) = (b, a + b)
print(sum) |
#LeetCode problem 200: Number of Islands
class Solution:
def check(self,grid,nodesVisited,row,col,m,n):
return (row>=0 and row<m and col>=0 and col<n and grid[row][col]=="1" and nodesVisited[row][col]==0)
def dfs(self,grid,nodesVisited,row,col,m,n):
a=[-1,1,0,0]
b=[0,0,1,-1]
nodesVisited[row][col]=1
for k in range(4):
if self.check(grid,nodesVisited,row+a[k],col+b[k],m,n):
self.dfs(grid,nodesVisited,row+a[k],col+b[k],m,n)
def numIslands(self, grid: List[List[str]]) -> int:
nodesVisited=[[0 for i in range(len(grid[0]))] for i in range(len(grid))]
count=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]=="0":
continue
elif grid[i][j]=="1" and nodesVisited[i][j]==0:
count+=1
self.dfs(grid,nodesVisited,i,j,len(grid),len(grid[0]))
return count | class Solution:
def check(self, grid, nodesVisited, row, col, m, n):
return row >= 0 and row < m and (col >= 0) and (col < n) and (grid[row][col] == '1') and (nodesVisited[row][col] == 0)
def dfs(self, grid, nodesVisited, row, col, m, n):
a = [-1, 1, 0, 0]
b = [0, 0, 1, -1]
nodesVisited[row][col] = 1
for k in range(4):
if self.check(grid, nodesVisited, row + a[k], col + b[k], m, n):
self.dfs(grid, nodesVisited, row + a[k], col + b[k], m, n)
def num_islands(self, grid: List[List[str]]) -> int:
nodes_visited = [[0 for i in range(len(grid[0]))] for i in range(len(grid))]
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '0':
continue
elif grid[i][j] == '1' and nodesVisited[i][j] == 0:
count += 1
self.dfs(grid, nodesVisited, i, j, len(grid), len(grid[0]))
return count |
'''
Create exceptions based on your inputs. Please follow the tasks below.
- Capture and handle system exceptions
- Create custom user-based exceptions
'''
class CustomInputError(Exception):
def __init__(self, *args, **kwargs):
print("Going through my own CustomInputError")
# Exception.__init__(self, *args, **kwargs)
class MyZeroDivisionException(ZeroDivisionError):
def __init__(self):
print("The data is not valid")
class DataNotValidException(TypeError):
def __init__(self):
print("The data contains Strings. Only numbers are expected in the input data")
| """
Create exceptions based on your inputs. Please follow the tasks below.
- Capture and handle system exceptions
- Create custom user-based exceptions
"""
class Custominputerror(Exception):
def __init__(self, *args, **kwargs):
print('Going through my own CustomInputError')
class Myzerodivisionexception(ZeroDivisionError):
def __init__(self):
print('The data is not valid')
class Datanotvalidexception(TypeError):
def __init__(self):
print('The data contains Strings. Only numbers are expected in the input data') |
# https://www.acmicpc.net/problem/8393
a = int(input())
result = 0
for i in range(a + 1):
result = result + i
print(result) | a = int(input())
result = 0
for i in range(a + 1):
result = result + i
print(result) |
# conf.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Tue May 18 22:08:50 UTC 2021
project = "Open GoPro Python SDK"
copyright = "2020, GoPro Inc."
author = "Tim Camise"
version = "0.5.8"
release = "0.5.8"
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
pygments_style = "sphinx"
html_static_path = ["_static"]
extensions = [
"sphinx.ext.autodoc",
"sphinxcontrib.napoleon",
"sphinx_rtd_theme",
"sphinx.ext.autosectionlabel",
]
html_theme = "sphinx_rtd_theme"
html_context = {
"display_github": True,
} | project = 'Open GoPro Python SDK'
copyright = '2020, GoPro Inc.'
author = 'Tim Camise'
version = '0.5.8'
release = '0.5.8'
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
pygments_style = 'sphinx'
html_static_path = ['_static']
extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.napoleon', 'sphinx_rtd_theme', 'sphinx.ext.autosectionlabel']
html_theme = 'sphinx_rtd_theme'
html_context = {'display_github': True} |
# Link --> https://www.hackerrank.com/challenges/maximum-element/problem
# Code:
def getMax(operations):
maximum = 0
temp = []
answer = []
for i in operations:
if i != '2' and i != '3':
numbers = i.split()
number = int(numbers[1])
temp.append(number)
if number > maximum:
maximum = number
elif i == '2':
temp.pop()
if len(temp) != 0:
maximum = max(temp)
else:
maximum = 0
else:
answer.append(maximum)
return answer
| def get_max(operations):
maximum = 0
temp = []
answer = []
for i in operations:
if i != '2' and i != '3':
numbers = i.split()
number = int(numbers[1])
temp.append(number)
if number > maximum:
maximum = number
elif i == '2':
temp.pop()
if len(temp) != 0:
maximum = max(temp)
else:
maximum = 0
else:
answer.append(maximum)
return answer |
#!/usr/bin/env python3
if __name__ == "__main__":
N = int(input().strip())
stamps = set()
for _ in range(N):
stamp = input().strip()
stamps.add(stamp)
print(len(stamps)) | if __name__ == '__main__':
n = int(input().strip())
stamps = set()
for _ in range(N):
stamp = input().strip()
stamps.add(stamp)
print(len(stamps)) |
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Intel Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Group(object):
def __init__(self, name):
self.name = name
self.__attributes = {}
def equals(self, obj):
return self.name == obj.get_name()
def get_attribute(self, key):
return self._attributes[key]
def get_device_members(self):
devices = []
all_devices = IAgentManager.getInstance().get_all_devices()
for device in all_devices:
if self.name in device.get_groups():
devices.append(device)
return devices
def get_name(self):
return self.name
def get_resource_members(self):
resources = []
all_devices = IAgentManager.getInstance().get_all_devices()
for device in all_devices:
resources_device = device.get_resources()
for resource in resource_device:
if self.name in resource.get_groups:
resources.append(resource)
return resources
def hash_code(self):
return hash(self.name)
| class Group(object):
def __init__(self, name):
self.name = name
self.__attributes = {}
def equals(self, obj):
return self.name == obj.get_name()
def get_attribute(self, key):
return self._attributes[key]
def get_device_members(self):
devices = []
all_devices = IAgentManager.getInstance().get_all_devices()
for device in all_devices:
if self.name in device.get_groups():
devices.append(device)
return devices
def get_name(self):
return self.name
def get_resource_members(self):
resources = []
all_devices = IAgentManager.getInstance().get_all_devices()
for device in all_devices:
resources_device = device.get_resources()
for resource in resource_device:
if self.name in resource.get_groups:
resources.append(resource)
return resources
def hash_code(self):
return hash(self.name) |
datasetDir = '../dataset/'
model = '../model/lenet'
modelDir = '../model/'
epochs = 20
batchSize = 128
rate = 0.001
mu = 0
sigma = 0.1
| dataset_dir = '../dataset/'
model = '../model/lenet'
model_dir = '../model/'
epochs = 20
batch_size = 128
rate = 0.001
mu = 0
sigma = 0.1 |
# flake8: noqa
_JULIA_V1 = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PythonRuntimeMetadata v1.0",
"description": "PythonRuntimeMetadata runtime/metadata.json schema.",
"type": "object",
"properties": {
"metadata_version": {
"description": "The metadata version.",
"type": "string"
},
"implementation": {
"description": "The implementation (e.g. cpython)",
"type": "string"
},
"version": {
"description": "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.",
"type": "string"
},
"abi": {
"description": "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.",
"type": "string"
},
"language_version": {
"description": "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.",
"type": "string"
},
"platform": {
"description": ("The platform string (as can be parsed by"
"EPDPlatform.from_epd_string"),
"type": "string"
},
"build_revision": {
"description": "Build revision (internal only).",
"type": "string",
},
"executable": {
"description": "The full path to the actual runtime executable.",
"type": "string",
},
"paths": {
"description": "The list of path to have access to this runtime.",
"type": "array",
"items": {"type": "string"},
},
"post_install": {
"description": ("The command (as a list) to execute after "
"installation."),
"type": "array",
"items": {"type": "string"},
},
},
"required": [
"metadata_version",
"implementation",
"version",
"abi",
"language_version",
"platform",
"build_revision",
"executable",
"paths",
"post_install",
]
}
_PYTHON_V1 = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PythonRuntimeMetadata v1.0",
"description": "PythonRuntimeMetadata runtime/metadata.json schema.",
"type": "object",
"properties": {
"metadata_version": {
"description": "The metadata version.",
"type": "string"
},
"implementation": {
"description": "The implementation (e.g. cpython)",
"type": "string"
},
"version": {
"description": "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.",
"type": "string"
},
"abi": {
"description": "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.",
"type": "string"
},
"language_version": {
"description": "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.",
"type": "string"
},
"platform": {
"description": ("The platform string (as can be parsed by"
"EPDPlatform.from_epd_string"),
"type": "string"
},
"build_revision": {
"description": "Build revision (internal only).",
"type": "string",
},
"executable": {
"description": "The full path to the actual runtime executable.",
"type": "string",
},
"paths": {
"description": "The list of path to have access to this runtime.",
"type": "array",
"items": {"type": "string"},
},
"post_install": {
"description": ("The command (as a list) to execute after "
"installation."),
"type": "array",
"items": {"type": "string"},
},
"scriptsdir": {
"description": "Full path to scripts directory.",
"type": "string",
},
"site_packages": {
"description": "The full path to the python site packages.",
"type": "string",
},
"python_tag": {
"description": "The python tag, as defined in PEP 425.",
"type": "string",
},
},
"required": [
"metadata_version",
"implementation",
"version",
"abi",
"language_version",
"platform",
"build_revision",
"executable",
"paths",
"post_install",
"scriptsdir",
"site_packages",
"python_tag",
]
}
| _julia_v1 = {'$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'PythonRuntimeMetadata v1.0', 'description': 'PythonRuntimeMetadata runtime/metadata.json schema.', 'type': 'object', 'properties': {'metadata_version': {'description': 'The metadata version.', 'type': 'string'}, 'implementation': {'description': 'The implementation (e.g. cpython)', 'type': 'string'}, 'version': {'description': "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.", 'type': 'string'}, 'abi': {'description': "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.", 'type': 'string'}, 'language_version': {'description': "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.", 'type': 'string'}, 'platform': {'description': 'The platform string (as can be parsed byEPDPlatform.from_epd_string', 'type': 'string'}, 'build_revision': {'description': 'Build revision (internal only).', 'type': 'string'}, 'executable': {'description': 'The full path to the actual runtime executable.', 'type': 'string'}, 'paths': {'description': 'The list of path to have access to this runtime.', 'type': 'array', 'items': {'type': 'string'}}, 'post_install': {'description': 'The command (as a list) to execute after installation.', 'type': 'array', 'items': {'type': 'string'}}}, 'required': ['metadata_version', 'implementation', 'version', 'abi', 'language_version', 'platform', 'build_revision', 'executable', 'paths', 'post_install']}
_python_v1 = {'$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'PythonRuntimeMetadata v1.0', 'description': 'PythonRuntimeMetadata runtime/metadata.json schema.', 'type': 'object', 'properties': {'metadata_version': {'description': 'The metadata version.', 'type': 'string'}, 'implementation': {'description': 'The implementation (e.g. cpython)', 'type': 'string'}, 'version': {'description': "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.", 'type': 'string'}, 'abi': {'description': "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.", 'type': 'string'}, 'language_version': {'description': "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.", 'type': 'string'}, 'platform': {'description': 'The platform string (as can be parsed byEPDPlatform.from_epd_string', 'type': 'string'}, 'build_revision': {'description': 'Build revision (internal only).', 'type': 'string'}, 'executable': {'description': 'The full path to the actual runtime executable.', 'type': 'string'}, 'paths': {'description': 'The list of path to have access to this runtime.', 'type': 'array', 'items': {'type': 'string'}}, 'post_install': {'description': 'The command (as a list) to execute after installation.', 'type': 'array', 'items': {'type': 'string'}}, 'scriptsdir': {'description': 'Full path to scripts directory.', 'type': 'string'}, 'site_packages': {'description': 'The full path to the python site packages.', 'type': 'string'}, 'python_tag': {'description': 'The python tag, as defined in PEP 425.', 'type': 'string'}}, 'required': ['metadata_version', 'implementation', 'version', 'abi', 'language_version', 'platform', 'build_revision', 'executable', 'paths', 'post_install', 'scriptsdir', 'site_packages', 'python_tag']} |
# Copyright 2009 Moyshe BenRabi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This is always generated file. Do not edit directyly.
# Instead edit messagegen.pl and descr.txt
class ProgramFragment(object):
def __init__(self):
self.max_program_name = 25
self.program_name = ''
self.program_major_version = 0
self.program_minor_version = 0
self.protocol_major_version = 0
self.protocol_minor_version = 0
self.protocol_source_revision = 0
def clear(self):
self.program_name = ''
self.program_major_version = 0
self.program_minor_version = 0
self.protocol_major_version = 0
self.protocol_minor_version = 0
self.protocol_source_revision = 0
super(ProgramFragment,self).clear()
def frame_data_size(self, frame_index):
result = 0
result += 1
result += 1
result += 1
result += 1
result += 4
return result
def serialize(self, writer):
writer.writeRange(self.program_name,self.max_program_name,'chr')
writer.write(self.program_major_version,'byte')
writer.write(self.program_minor_version,'byte')
writer.write(self.protocol_major_version,'byte')
writer.write(self.protocol_minor_version,'byte')
writer.write(self.protocol_source_revision,'uint')
def deserialize(self, reader):
(self.program_name, c) = reader.readRange(self.max_program_name,'chr',1)
(self.program_major_version, c) = reader.read('byte')
(self.program_minor_version, c) = reader.read('byte')
(self.protocol_major_version, c) = reader.read('byte')
(self.protocol_minor_version, c) = reader.read('byte')
(self.protocol_source_revision, c) = reader.read('uint')
def __str__(self):
return 'ProgramFragment('+self.program_name \
+ str(self.program_major_version) \
+ str(self.program_minor_version) \
+ str(self.protocol_major_version) \
+ str(self.protocol_minor_version) \
+ str(self.protocol_source_revision)+')'
def __eq__(self,other):
return True and \
(self.program_name == other.program_name) and \
self.program_major_version == other.program_major_version and \
self.program_minor_version == other.program_minor_version and \
self.protocol_major_version == other.protocol_major_version and \
self.protocol_minor_version == other.protocol_minor_version and \
self.protocol_source_revision == other.protocol_source_revision
def __ne__(self,other):
return True or \
(self.program_name != other.program_name) or \
self.program_major_version != other.program_major_version or \
self.program_minor_version != other.program_minor_version or \
self.protocol_major_version != other.protocol_major_version or \
self.protocol_minor_version != other.protocol_minor_version or \
self.protocol_source_revision != other.protocol_source_revision
| class Programfragment(object):
def __init__(self):
self.max_program_name = 25
self.program_name = ''
self.program_major_version = 0
self.program_minor_version = 0
self.protocol_major_version = 0
self.protocol_minor_version = 0
self.protocol_source_revision = 0
def clear(self):
self.program_name = ''
self.program_major_version = 0
self.program_minor_version = 0
self.protocol_major_version = 0
self.protocol_minor_version = 0
self.protocol_source_revision = 0
super(ProgramFragment, self).clear()
def frame_data_size(self, frame_index):
result = 0
result += 1
result += 1
result += 1
result += 1
result += 4
return result
def serialize(self, writer):
writer.writeRange(self.program_name, self.max_program_name, 'chr')
writer.write(self.program_major_version, 'byte')
writer.write(self.program_minor_version, 'byte')
writer.write(self.protocol_major_version, 'byte')
writer.write(self.protocol_minor_version, 'byte')
writer.write(self.protocol_source_revision, 'uint')
def deserialize(self, reader):
(self.program_name, c) = reader.readRange(self.max_program_name, 'chr', 1)
(self.program_major_version, c) = reader.read('byte')
(self.program_minor_version, c) = reader.read('byte')
(self.protocol_major_version, c) = reader.read('byte')
(self.protocol_minor_version, c) = reader.read('byte')
(self.protocol_source_revision, c) = reader.read('uint')
def __str__(self):
return 'ProgramFragment(' + self.program_name + str(self.program_major_version) + str(self.program_minor_version) + str(self.protocol_major_version) + str(self.protocol_minor_version) + str(self.protocol_source_revision) + ')'
def __eq__(self, other):
return True and self.program_name == other.program_name and (self.program_major_version == other.program_major_version) and (self.program_minor_version == other.program_minor_version) and (self.protocol_major_version == other.protocol_major_version) and (self.protocol_minor_version == other.protocol_minor_version) and (self.protocol_source_revision == other.protocol_source_revision)
def __ne__(self, other):
return True or self.program_name != other.program_name or self.program_major_version != other.program_major_version or (self.program_minor_version != other.program_minor_version) or (self.protocol_major_version != other.protocol_major_version) or (self.protocol_minor_version != other.protocol_minor_version) or (self.protocol_source_revision != other.protocol_source_revision) |
test_cases = int(input())
for t in range(1, test_cases + 1):
nums = list(map(int, input().strip().split()))
result = []
for i in range(0, 5):
for j in range(i + 1, 6):
for k in range(j + 1, 7):
result.append(nums[i] + nums[j] + nums[k])
result = sorted(list(set(result)), reverse=True)
print('#{} {}'.format(t, result[4]))
| test_cases = int(input())
for t in range(1, test_cases + 1):
nums = list(map(int, input().strip().split()))
result = []
for i in range(0, 5):
for j in range(i + 1, 6):
for k in range(j + 1, 7):
result.append(nums[i] + nums[j] + nums[k])
result = sorted(list(set(result)), reverse=True)
print('#{} {}'.format(t, result[4])) |
# atomic level
def get_idx(list, key):
for idx in range(len(list)):
if key == list[idx][0]:
return idx
def ins(list, key, val):
list.append([key, val])
return list
def ret(list, key):
idx = get_idx(list, key)
return list[idx][1]
def upd(list, key, val):
new_item = [key.lower(), val]
idx = get_idx(list, key)
list[idx] = new_item
return list
def delete(list, key):
idx = get_idx(list, key)
list.remove(idx)
return list
# table level
def ins_tab(db, table_name):
return ins(db, table_name, [])
def ret_tab(db, table_name):
return ret(db, table_name)
def upd_tab(db, table_name, table):
return upd(db, table_name, table)
def del_tab(db, table_name):
return delete(db, table_name)
# record level
def is_member(record, kv, check_value):
if len(kv) == 0:
return True
else:
for item in record:
if item[0] == kv[0]:
if check_value:
if item[1] == kv[1]:
return True
else:
return True
return False
def kvs_in_rec(record, kv_list):
# all kv's of kv_list_search are members of record
for kv in kv_list:
if not is_member(record, kv, True):
return False
return True
def ins_rec(db, table_name, kv_list):
table = ret(db, table_name)
table.append(kv_list)
return upd(db, table_name, table)
def ret_recs(db, table_name, kv_list):
list = []
table = ret(db, table_name)
for record in table:
if kvs_in_rec(record, kv_list):
list.append(record)
return list
def ret_rec_idx(db, table_name, record_idx):
table = ret(db, table_name)
if len(table) >= record_idx:
return table[record_idx]
else:
return None
def upd_recs(db, table_name, kv_list_search, kv_list_upd):
# updates all records identified by kv_list_search
new_table = []
old_table = ret_tab(db, table_name)
for old_rec in old_table:
if kvs_in_rec(old_rec, kv_list_search):
# matching record
new_rec = old_rec
for kv in kv_list_upd:
# if kv is member of record, update value of kv,
# otherwise insert entire kv
key = kv[0]
val = kv[1]
if is_member(new_rec, kv, False):
new_rec = upd(new_rec, key, val)
else:
new_rec = ins(new_rec, key, val)
new_table.append(new_rec)
else:
new_table.append(old_rec)
return upd(db, table_name, new_table)
def del_recs(db, table_name, kv_list):
new_table = []
old_table = ret_tab(db, table_name)
for record in old_table:
if not kvs_in_rec(record, kv_list):
new_table.append(record)
return upd(db, table_name, new_table)
def del_all(db, table_name):
table = []
return upd(db, table_name, table)
# value level
def ret_val(db, table_name, record_id_key, record_id_value, data_key):
# assumes [record_id_key, record_id_value] identifies a single record
records = ret_recs(db, table_name, [[record_id_key, record_id_value]])
if len(records) == 0:
return None
else:
return ret(records[0], data_key)
def ret_val_idx(db, table_name, record_idx, data_key):
record = ret_rec_idx(db, table_name, record_idx)
if record:
return ret(record, data_key)
else:
return None
def upd_val(db, table_name, record_id_key, record_id_val, data_key, data_val):
# updates all records identified by [record_id_key, record_id_value]
return upd_recs(db,
table_name,
[[record_id_key, record_id_val]],
[[data_key, data_val]])
# summary
def rec_cnt(db, table_name, kv_list):
records = ret_recs(db, table_name, kv_list)
return len(records)
def rec_list(db, table_name, key):
list = []
table = ret_tab(db, table_name)
for record in table:
for item in record:
if item[0].lower() == key.lower():
if not item[1] in list:
list.append(item[1])
return list
| def get_idx(list, key):
for idx in range(len(list)):
if key == list[idx][0]:
return idx
def ins(list, key, val):
list.append([key, val])
return list
def ret(list, key):
idx = get_idx(list, key)
return list[idx][1]
def upd(list, key, val):
new_item = [key.lower(), val]
idx = get_idx(list, key)
list[idx] = new_item
return list
def delete(list, key):
idx = get_idx(list, key)
list.remove(idx)
return list
def ins_tab(db, table_name):
return ins(db, table_name, [])
def ret_tab(db, table_name):
return ret(db, table_name)
def upd_tab(db, table_name, table):
return upd(db, table_name, table)
def del_tab(db, table_name):
return delete(db, table_name)
def is_member(record, kv, check_value):
if len(kv) == 0:
return True
else:
for item in record:
if item[0] == kv[0]:
if check_value:
if item[1] == kv[1]:
return True
else:
return True
return False
def kvs_in_rec(record, kv_list):
for kv in kv_list:
if not is_member(record, kv, True):
return False
return True
def ins_rec(db, table_name, kv_list):
table = ret(db, table_name)
table.append(kv_list)
return upd(db, table_name, table)
def ret_recs(db, table_name, kv_list):
list = []
table = ret(db, table_name)
for record in table:
if kvs_in_rec(record, kv_list):
list.append(record)
return list
def ret_rec_idx(db, table_name, record_idx):
table = ret(db, table_name)
if len(table) >= record_idx:
return table[record_idx]
else:
return None
def upd_recs(db, table_name, kv_list_search, kv_list_upd):
new_table = []
old_table = ret_tab(db, table_name)
for old_rec in old_table:
if kvs_in_rec(old_rec, kv_list_search):
new_rec = old_rec
for kv in kv_list_upd:
key = kv[0]
val = kv[1]
if is_member(new_rec, kv, False):
new_rec = upd(new_rec, key, val)
else:
new_rec = ins(new_rec, key, val)
new_table.append(new_rec)
else:
new_table.append(old_rec)
return upd(db, table_name, new_table)
def del_recs(db, table_name, kv_list):
new_table = []
old_table = ret_tab(db, table_name)
for record in old_table:
if not kvs_in_rec(record, kv_list):
new_table.append(record)
return upd(db, table_name, new_table)
def del_all(db, table_name):
table = []
return upd(db, table_name, table)
def ret_val(db, table_name, record_id_key, record_id_value, data_key):
records = ret_recs(db, table_name, [[record_id_key, record_id_value]])
if len(records) == 0:
return None
else:
return ret(records[0], data_key)
def ret_val_idx(db, table_name, record_idx, data_key):
record = ret_rec_idx(db, table_name, record_idx)
if record:
return ret(record, data_key)
else:
return None
def upd_val(db, table_name, record_id_key, record_id_val, data_key, data_val):
return upd_recs(db, table_name, [[record_id_key, record_id_val]], [[data_key, data_val]])
def rec_cnt(db, table_name, kv_list):
records = ret_recs(db, table_name, kv_list)
return len(records)
def rec_list(db, table_name, key):
list = []
table = ret_tab(db, table_name)
for record in table:
for item in record:
if item[0].lower() == key.lower():
if not item[1] in list:
list.append(item[1])
return list |
class Example:
def __init__(self):
self.name = ""
pass
def greet(self, name):
self.name = name
print("hello " + name)
| class Example:
def __init__(self):
self.name = ''
pass
def greet(self, name):
self.name = name
print('hello ' + name) |
#!/usr/bin/env python3
visited = set()
visited.add((0, 0))
turn = 0 # Santa = 0, Robo-Santa = 1
locations = [[0, 0], [0, 0]]
with open('input.txt', 'r') as f:
for line in f:
for ch in line:
pos = locations[turn]
turn = (turn + 1) % 2
if ch == '^':
pos[0] += 1
elif ch == 'v':
pos[0] -= 1
elif ch == '<':
pos[1] -= 1
elif ch == '>':
pos[1] += 1
visited.add(tuple(pos))
print("Total houses", len(visited))
| visited = set()
visited.add((0, 0))
turn = 0
locations = [[0, 0], [0, 0]]
with open('input.txt', 'r') as f:
for line in f:
for ch in line:
pos = locations[turn]
turn = (turn + 1) % 2
if ch == '^':
pos[0] += 1
elif ch == 'v':
pos[0] -= 1
elif ch == '<':
pos[1] -= 1
elif ch == '>':
pos[1] += 1
visited.add(tuple(pos))
print('Total houses', len(visited)) |
# import pytest
class TestBaseReplacerMixin:
def test_target(self): # synced
assert True
def test_write(self): # synced
assert True
def test_flush(self): # synced
assert True
def test_close(self): # synced
assert True
class TestStdOutReplacerMixin:
def test_target(self): # synced
assert True
class TestStdErrReplacerMixin:
def test_target(self): # synced
assert True
class TestStdOutFileRedirector:
def test___str__(self): # synced
assert True
def test_write(self): # synced
assert True
class TestBaseStreamRedirector:
def test___str__(self): # synced
assert True
def test_write(self): # synced
assert True
def test_flush(self): # synced
assert True
def test_close(self): # synced
assert True
class TestStdOutStreamRedirector:
pass
class TestStdErrStreamRedirector:
pass
class TestSupressor:
def test_write(self): # synced
assert True
| class Testbasereplacermixin:
def test_target(self):
assert True
def test_write(self):
assert True
def test_flush(self):
assert True
def test_close(self):
assert True
class Teststdoutreplacermixin:
def test_target(self):
assert True
class Teststderrreplacermixin:
def test_target(self):
assert True
class Teststdoutfileredirector:
def test___str__(self):
assert True
def test_write(self):
assert True
class Testbasestreamredirector:
def test___str__(self):
assert True
def test_write(self):
assert True
def test_flush(self):
assert True
def test_close(self):
assert True
class Teststdoutstreamredirector:
pass
class Teststderrstreamredirector:
pass
class Testsupressor:
def test_write(self):
assert True |
# coding: utf8
db.define_table('post',
Field('Email',requires=IS_EMAIL()),
Field('filen','upload'),
auth.signature)
| db.define_table('post', field('Email', requires=is_email()), field('filen', 'upload'), auth.signature) |
class Solution:
def dfs(self,row_cnt:int, col_cnt:int, i:int, j:int, obs_arr:list, solve_dict:dict):
if (i, j) in solve_dict:
return solve_dict[(i,j)]
right_cnt = 0
down_cnt = 0
#right
if i + 1 < row_cnt and not obs_arr[i + 1][j]:
if (i + 1, j) in solve_dict:
right_cnt = solve_dict[(i + 1, j)]
else:
right_cnt = self.dfs(row_cnt, col_cnt,i + 1, j,obs_arr,solve_dict)
#left
if j + 1 < col_cnt and not obs_arr[i][j + 1]:
if (i, j + 1) in solve_dict:
down_cnt = solve_dict[(i, j + 1)]
else:
down_cnt = self.dfs(row_cnt, col_cnt, i, j + 1,obs_arr, solve_dict)
res = right_cnt + down_cnt
solve_dict[(i, j)] = res
return res
def uniquePathsWithObstacles(self, obstacleGrid: list) -> int:
row = len(obstacleGrid)
if not row:
return 0
col = len(obstacleGrid[0])
if not col:
return 0
if obstacleGrid[row - 1][col - 1]:
return 0
if obstacleGrid[0][0]:
return 0
res = self.dfs(row,col,0,0,obstacleGrid, {(row-1, col - 1):1})
return res
t1 = [
[0,0,0],
[0,1,0],
[0,0,0]
]
sl = Solution()
res = sl.uniquePathsWithObstacles(t1)
print(res) | class Solution:
def dfs(self, row_cnt: int, col_cnt: int, i: int, j: int, obs_arr: list, solve_dict: dict):
if (i, j) in solve_dict:
return solve_dict[i, j]
right_cnt = 0
down_cnt = 0
if i + 1 < row_cnt and (not obs_arr[i + 1][j]):
if (i + 1, j) in solve_dict:
right_cnt = solve_dict[i + 1, j]
else:
right_cnt = self.dfs(row_cnt, col_cnt, i + 1, j, obs_arr, solve_dict)
if j + 1 < col_cnt and (not obs_arr[i][j + 1]):
if (i, j + 1) in solve_dict:
down_cnt = solve_dict[i, j + 1]
else:
down_cnt = self.dfs(row_cnt, col_cnt, i, j + 1, obs_arr, solve_dict)
res = right_cnt + down_cnt
solve_dict[i, j] = res
return res
def unique_paths_with_obstacles(self, obstacleGrid: list) -> int:
row = len(obstacleGrid)
if not row:
return 0
col = len(obstacleGrid[0])
if not col:
return 0
if obstacleGrid[row - 1][col - 1]:
return 0
if obstacleGrid[0][0]:
return 0
res = self.dfs(row, col, 0, 0, obstacleGrid, {(row - 1, col - 1): 1})
return res
t1 = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
sl = solution()
res = sl.uniquePathsWithObstacles(t1)
print(res) |
dataset_type = 'ShipRSImageNet_Level2'
# data_root = 'data/Ship_ImageNet/'
data_root = './data/ShipRSImageNet/'
CLASSES = ('Other Ship', 'Other Warship', 'Submarine', 'Aircraft Carrier', 'Cruiser', 'Destroyer',
'Frigate', 'Patrol', 'Landing', 'Commander', 'Auxiliary Ships', 'Other Merchant',
'Container Ship', 'RoRo', 'Cargo', 'Barge', 'Tugboat', 'Ferry', 'Yacht',
'Sailboat', 'Fishing Vessel', 'Oil Tanker', 'Hovercraft', 'Motorboat', 'Dock',)
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=8,
workers_per_gpu=2,
train=dict(
type=dataset_type,
classes=CLASSES,
ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_train_level_2.json',
img_prefix=data_root + 'VOC_Format/JPEGImages/',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
classes=CLASSES,
ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json',
img_prefix=data_root + 'VOC_Format/JPEGImages/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
classes=CLASSES,
ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json',
img_prefix=data_root + 'VOC_Format/JPEGImages/',
pipeline=test_pipeline))
evaluation = dict(interval=10, metric='bbox')
| dataset_type = 'ShipRSImageNet_Level2'
data_root = './data/ShipRSImageNet/'
classes = ('Other Ship', 'Other Warship', 'Submarine', 'Aircraft Carrier', 'Cruiser', 'Destroyer', 'Frigate', 'Patrol', 'Landing', 'Commander', 'Auxiliary Ships', 'Other Merchant', 'Container Ship', 'RoRo', 'Cargo', 'Barge', 'Tugboat', 'Ferry', 'Yacht', 'Sailboat', 'Fishing Vessel', 'Oil Tanker', 'Hovercraft', 'Motorboat', 'Dock')
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])]
test_pipeline = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'])])]
data = dict(samples_per_gpu=8, workers_per_gpu=2, train=dict(type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_train_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=train_pipeline), val=dict(type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=test_pipeline), test=dict(type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=test_pipeline))
evaluation = dict(interval=10, metric='bbox') |
def dbapi_subscription(dbsession, action, input_dict, action_filter={}, caller_area={}):
_api_name = "dbapi_subscription"
_api_entity = 'SUBSCRIPTION'
_api_action = action
_api_msgID = set_msgID(_api_name, _api_action, _api_entity)
_process_identity_kwargs = {'type': 'api', 'module': module_id, 'name': _api_name, 'action': _api_action, 'entity': _api_entity, 'msgID': _api_msgID,}
_process_adapters_kwargs = {'dbsession': dbsession}
_process_log_kwargs = {'indent_method': 'AUTO', 'indent_level':None}
_process_debug_level = get_debug_level(caller_area.get('debug_level'), **_process_identity_kwargs, **_process_adapters_kwargs)
_process_debug_files = get_debug_files(_process_debug_level, **_process_identity_kwargs, **_process_adapters_kwargs)
_process_debug_kwargs={'debug_level':_process_debug_level,'debug_files':_process_debug_files}
_process_signature = build_process_signature(**_process_identity_kwargs, **_process_adapters_kwargs, **_process_debug_kwargs, **_process_log_kwargs)
_process_call_area = build_process_call_area(_process_signature, caller_area)
log_process_start(_api_msgID,**_process_call_area)
log_process_input('', 'input_dict', input_dict,**_process_call_area)
log_process_input('', 'action_filter', action_filter,**_process_call_area)
log_process_input('', 'caller_area', caller_area,**_process_call_area)
input_dict.update({'client_type': 'subscriber'})
if action.upper() in ('REGISTER','ADD','REFRESH'):
action='REFRESH'
action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
thismsg=action_result.get('api_message')
api_result.update({'api_action': _api_action, 'api_name': _api_name})
if not api_result.get('api_status') == 'success':
# msg = f"subscription not registered"
# api_result.update({'api_message':msg})
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
client = api_result.get('api_data')
client_id = client.get('client_id')
input_dict.update({'client_id': client_id})
elif action.upper() in ('CONFIRM', 'ACTIVATE', 'DEACTIVATE', 'DELETE'):
subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, input_dict, 'DICT', caller_area=_process_call_area)
if not subscription_dict:
msg = f'subscription not found'
action_status='error'
api_result = {'api_status': action_status, 'api_message': msg, 'api_data': input_dict, 'api_action': _api_action.upper(), 'api_name': _api_name}
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
client_dict=dbsession.get(dbmodel.CLIENT, subscription_dict,'DICT', caller_area=_process_call_area)
if not client_dict:
msg = f'client not found'
action_status='error'
api_result = {'api_status': action_status, 'api_message': msg, 'api_data': subscription_dict, 'api_action': _api_action.upper(), 'api_name': _api_name}
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
#action='CONFIRM'
action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
api_result.update({'api_action': _api_action, 'api_name': _api_name})
thismsg=action_result.get('api_message')
if not api_result.get('api_status') == 'success':
# msg = f'client confirmation failed'
# api_result.update({'api_message':msg})
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, subscription_dict, 'DICT', caller_area=_process_call_area)
status=subscription_dict.get('status')
client_id=subscription_dict.get('client_id')
# if not subscription_dict.get('status') == 'Active':
# msg = f"service provider not confirmed. status={status}"
# action_status='error'
# api_result = {'api_status': action_status, 'api_message': msg, 'api_data': subscription_dict, 'messages': messages, 'rows_added': rows_added, 'rows_updated': rows_updated, 'api_action': _api_action.upper(), 'api_name': _api_name}
# log_process_finish(_api_msgID, api_result, **_process_call_area)
# return api_result
input_dict.update({'status': status})
input_dict.update({'client_id': client_id})
action_result = dbsession.table_action(dbmodel.SUBSCRIPTION, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
thismsg=thismsg.replace('CLIENT',_api_entity)
api_result.update({'api_action': _api_action, 'api_name': _api_name,'api_message':thismsg})
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
| def dbapi_subscription(dbsession, action, input_dict, action_filter={}, caller_area={}):
_api_name = 'dbapi_subscription'
_api_entity = 'SUBSCRIPTION'
_api_action = action
_api_msg_id = set_msg_id(_api_name, _api_action, _api_entity)
_process_identity_kwargs = {'type': 'api', 'module': module_id, 'name': _api_name, 'action': _api_action, 'entity': _api_entity, 'msgID': _api_msgID}
_process_adapters_kwargs = {'dbsession': dbsession}
_process_log_kwargs = {'indent_method': 'AUTO', 'indent_level': None}
_process_debug_level = get_debug_level(caller_area.get('debug_level'), **_process_identity_kwargs, **_process_adapters_kwargs)
_process_debug_files = get_debug_files(_process_debug_level, **_process_identity_kwargs, **_process_adapters_kwargs)
_process_debug_kwargs = {'debug_level': _process_debug_level, 'debug_files': _process_debug_files}
_process_signature = build_process_signature(**_process_identity_kwargs, **_process_adapters_kwargs, **_process_debug_kwargs, **_process_log_kwargs)
_process_call_area = build_process_call_area(_process_signature, caller_area)
log_process_start(_api_msgID, **_process_call_area)
log_process_input('', 'input_dict', input_dict, **_process_call_area)
log_process_input('', 'action_filter', action_filter, **_process_call_area)
log_process_input('', 'caller_area', caller_area, **_process_call_area)
input_dict.update({'client_type': 'subscriber'})
if action.upper() in ('REGISTER', 'ADD', 'REFRESH'):
action = 'REFRESH'
action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
thismsg = action_result.get('api_message')
api_result.update({'api_action': _api_action, 'api_name': _api_name})
if not api_result.get('api_status') == 'success':
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
client = api_result.get('api_data')
client_id = client.get('client_id')
input_dict.update({'client_id': client_id})
elif action.upper() in ('CONFIRM', 'ACTIVATE', 'DEACTIVATE', 'DELETE'):
subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, input_dict, 'DICT', caller_area=_process_call_area)
if not subscription_dict:
msg = f'subscription not found'
action_status = 'error'
api_result = {'api_status': action_status, 'api_message': msg, 'api_data': input_dict, 'api_action': _api_action.upper(), 'api_name': _api_name}
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
client_dict = dbsession.get(dbmodel.CLIENT, subscription_dict, 'DICT', caller_area=_process_call_area)
if not client_dict:
msg = f'client not found'
action_status = 'error'
api_result = {'api_status': action_status, 'api_message': msg, 'api_data': subscription_dict, 'api_action': _api_action.upper(), 'api_name': _api_name}
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
api_result.update({'api_action': _api_action, 'api_name': _api_name})
thismsg = action_result.get('api_message')
if not api_result.get('api_status') == 'success':
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, subscription_dict, 'DICT', caller_area=_process_call_area)
status = subscription_dict.get('status')
client_id = subscription_dict.get('client_id')
input_dict.update({'status': status})
input_dict.update({'client_id': client_id})
action_result = dbsession.table_action(dbmodel.SUBSCRIPTION, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
thismsg = thismsg.replace('CLIENT', _api_entity)
api_result.update({'api_action': _api_action, 'api_name': _api_name, 'api_message': thismsg})
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result |
def recursiveCalc(n, counter=0, steps=''):
if n<10:
steps += 'Total Steps: ' + str(counter) + '.'
return steps, counter
counter+=1
result = calc(n)
steps += str(result)+', '
return recursiveCalc(result, counter, steps)
def calc(n):
result = 1
while (n>0):
mod = n % 10
result *= mod
n -= mod
n /= 10
return result
def printNumber(n, steps):
print (str(n) + ': ' + steps)
max = -1
bestNumbers = []
for i in range(1000000):
result = recursiveCalc(i)
if(result[1] > max):
max = result[1]
printNumber(i, result[0])
bestNumbers.append(i)
print (bestNumbers)
| def recursive_calc(n, counter=0, steps=''):
if n < 10:
steps += 'Total Steps: ' + str(counter) + '.'
return (steps, counter)
counter += 1
result = calc(n)
steps += str(result) + ', '
return recursive_calc(result, counter, steps)
def calc(n):
result = 1
while n > 0:
mod = n % 10
result *= mod
n -= mod
n /= 10
return result
def print_number(n, steps):
print(str(n) + ': ' + steps)
max = -1
best_numbers = []
for i in range(1000000):
result = recursive_calc(i)
if result[1] > max:
max = result[1]
print_number(i, result[0])
bestNumbers.append(i)
print(bestNumbers) |
def ifPossible(a):
while a%2==0:
a/=2
return a
test=int(input())
while test:
a,b = input().split()
a=int(a)
b=int(b)
if a>b:
n=b
b=a
a=n
num=ifPossible(b)
ans=0
if num!=ifPossible(a):
print("-1")
else:
b/=a
while b>=8:
b/=8
ans+=1
if b>1:
ans+=1
print(ans)
test-=1
| def if_possible(a):
while a % 2 == 0:
a /= 2
return a
test = int(input())
while test:
(a, b) = input().split()
a = int(a)
b = int(b)
if a > b:
n = b
b = a
a = n
num = if_possible(b)
ans = 0
if num != if_possible(a):
print('-1')
else:
b /= a
while b >= 8:
b /= 8
ans += 1
if b > 1:
ans += 1
print(ans)
test -= 1 |
def bubble_sort(arr):
swapped = True
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
def selection_sort(arr):
for i in range(len(arr)):
minpos = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[minpos]:
minpos = j
arr[i], arr[minpos] = arr[minpos], arr[i]
def insertion_sort(arr):
for i in range(1, len(arr)):
current = arr[i]
j = i - 1
while j >= 0 and arr[j] > current:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = current
def merge_sort(array):
def _merge(left_arr, right_arr):
_summary = [0] * (len(left_arr) + len(right_arr))
li = ri = n = 0
while li < len(left_arr) and ri < len(right_arr):
if left_arr[li] <= right_arr[ri]:
_summary[n] = left_arr[li]
li += 1
n += 1
else:
_summary[n] = right_arr[ri]
ri += 1
n += 1
while li < len(left_arr):
_summary[n] = left_arr[li]
li += 1
n += 1
while ri < len(right_arr):
_summary[n] = right_arr[ri]
ri += 1
n += 1
return _summary
if len(array) <= 1: return
middle = len(array) // 2
left_array = [array[i] for i in range(0, middle)]
right_array = [array[i] for i in range(middle, len(array))]
merge_sort(left_array)
merge_sort(right_array)
summary = _merge(left_array, right_array)
for i in range(len(array)):
array[i] = summary[i]
def quick_sort(array):
if len(array) <= 1:
return
pivot = array[0]
left_array = []
right_array = []
middle_array = []
for x in array:
if x < pivot:
left_array.append(x)
elif x > pivot:
right_array.append(x)
else:
middle_array.append(x)
quick_sort(left_array)
quick_sort(right_array)
index = 0
for x in left_array + middle_array + right_array:
array[index] = x
index += 1
| def bubble_sort(arr):
swapped = True
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
(arr[i], arr[i + 1]) = (arr[i + 1], arr[i])
swapped = True
def selection_sort(arr):
for i in range(len(arr)):
minpos = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[minpos]:
minpos = j
(arr[i], arr[minpos]) = (arr[minpos], arr[i])
def insertion_sort(arr):
for i in range(1, len(arr)):
current = arr[i]
j = i - 1
while j >= 0 and arr[j] > current:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = current
def merge_sort(array):
def _merge(left_arr, right_arr):
_summary = [0] * (len(left_arr) + len(right_arr))
li = ri = n = 0
while li < len(left_arr) and ri < len(right_arr):
if left_arr[li] <= right_arr[ri]:
_summary[n] = left_arr[li]
li += 1
n += 1
else:
_summary[n] = right_arr[ri]
ri += 1
n += 1
while li < len(left_arr):
_summary[n] = left_arr[li]
li += 1
n += 1
while ri < len(right_arr):
_summary[n] = right_arr[ri]
ri += 1
n += 1
return _summary
if len(array) <= 1:
return
middle = len(array) // 2
left_array = [array[i] for i in range(0, middle)]
right_array = [array[i] for i in range(middle, len(array))]
merge_sort(left_array)
merge_sort(right_array)
summary = _merge(left_array, right_array)
for i in range(len(array)):
array[i] = summary[i]
def quick_sort(array):
if len(array) <= 1:
return
pivot = array[0]
left_array = []
right_array = []
middle_array = []
for x in array:
if x < pivot:
left_array.append(x)
elif x > pivot:
right_array.append(x)
else:
middle_array.append(x)
quick_sort(left_array)
quick_sort(right_array)
index = 0
for x in left_array + middle_array + right_array:
array[index] = x
index += 1 |
class AllennlpReaderToDict:
def __init__(self, **kwargs):
self.kwargs = kwargs
def __call__(self, *args_ignore, **kwargs_ignore):
kwargs = self.kwargs
reader = kwargs.get("reader")
file_path = kwargs.get("file_path")
n_samples = kwargs.get("n_samples")
instances = reader._read(file_path)
n_samples = n_samples or len(instances)
d = dict()
i = 0
for instance in instances:
if n_samples and i >= n_samples:
break
d[i] = instance.fields
i += 1
return d
| class Allennlpreadertodict:
def __init__(self, **kwargs):
self.kwargs = kwargs
def __call__(self, *args_ignore, **kwargs_ignore):
kwargs = self.kwargs
reader = kwargs.get('reader')
file_path = kwargs.get('file_path')
n_samples = kwargs.get('n_samples')
instances = reader._read(file_path)
n_samples = n_samples or len(instances)
d = dict()
i = 0
for instance in instances:
if n_samples and i >= n_samples:
break
d[i] = instance.fields
i += 1
return d |
def one_hot_encode(_df, _col):
_values = set(_df[_col].values)
for v in _values:
_df[_col + str(v)] = _df[_col].apply(lambda x : float(x == v) )
return _df | def one_hot_encode(_df, _col):
_values = set(_df[_col].values)
for v in _values:
_df[_col + str(v)] = _df[_col].apply(lambda x: float(x == v))
return _df |
def differ(string_1, string_2):
new_string = ""
for i in range(len(string_1)):
if string_1[i] == string_2[i]:
new_string += string_1[i]
return new_string
def main():
f = [line.rstrip("\n") for line in open("Data.txt")]
for i in range(len(f)):
for j in range(i + 1, len(f)):
if len(differ(f[i], f[j])) == len(f[i]) - 1:
print(differ(f[i], f[j]))
if __name__ == "__main__":
main()
| def differ(string_1, string_2):
new_string = ''
for i in range(len(string_1)):
if string_1[i] == string_2[i]:
new_string += string_1[i]
return new_string
def main():
f = [line.rstrip('\n') for line in open('Data.txt')]
for i in range(len(f)):
for j in range(i + 1, len(f)):
if len(differ(f[i], f[j])) == len(f[i]) - 1:
print(differ(f[i], f[j]))
if __name__ == '__main__':
main() |
class Car(object):
# setting some default values
num_of_doors = 4
num_of_wheels = 4
def __init__(self, name='General', model='GM', car_type='saloon', speed=0):
self.name = name
self.model = model
self.car_type = car_type
self.speed = speed
if self.name is 'Porshe' or self.name is 'Koenigsegg':
self.num_of_doors = 2
elif self.car_type is 'trailer':
self.num_of_wheels = 8
else:
self
def is_saloon(self):
'''
Determine between saloon and trailer
'''
if self.car_type is not 'trailer':
return True
return False
def drive(self, speed):
'''
Check the car type and return appropriate speed
'''
if self.car_type is 'trailer':
self.speed = speed * 11
else:
self.speed = 10 ** speed
return self | class Car(object):
num_of_doors = 4
num_of_wheels = 4
def __init__(self, name='General', model='GM', car_type='saloon', speed=0):
self.name = name
self.model = model
self.car_type = car_type
self.speed = speed
if self.name is 'Porshe' or self.name is 'Koenigsegg':
self.num_of_doors = 2
elif self.car_type is 'trailer':
self.num_of_wheels = 8
else:
self
def is_saloon(self):
"""
Determine between saloon and trailer
"""
if self.car_type is not 'trailer':
return True
return False
def drive(self, speed):
"""
Check the car type and return appropriate speed
"""
if self.car_type is 'trailer':
self.speed = speed * 11
else:
self.speed = 10 ** speed
return self |
class Tree:
def __init__(self,data):
self.tree = [data, [],[]]
def left_subtree(self,branch):
left_list = self.tree.pop(1)
if len(left_list) > 1:
branch.tree[1]=left_list
self.tree.insert(1,branch.tree)
else:
self.tree.insert(1,branch.tree)
def right_subtree(self,branch):
right_list = self.tree.pop(2)
if len(right_list) > 1:
branch.tree[2]=right_list
self.tree.insert(2,branch.tree)
else:
self.tree.insert(2,branch.tree)
#EXECUTION
print("Create Root Node")
root = Tree("Root_node")
print("Value of Root = ",root.tree)
print("Create Left Tree")
tree_left = Tree("Tree_Left")
root.left_subtree(tree_left)
print("Value of Tree_Left = ",root.tree)
print("Create Right Tree")
tree_right = Tree("Tree_Right")
root.right_subtree(tree_right)
print("Value of Tree_Right = ",root.tree)
print("Create Left Inbetween")
tree_inbtw = Tree("Tree left in between")
root.left_subtree(tree_inbtw)
print("Value of Tree_Left = ",root.tree)
print("Create TreeLL")
treell = Tree("TreeLL")
tree_left.left_subtree(treell)
print("Value of TREE = ",root.tree)
| class Tree:
def __init__(self, data):
self.tree = [data, [], []]
def left_subtree(self, branch):
left_list = self.tree.pop(1)
if len(left_list) > 1:
branch.tree[1] = left_list
self.tree.insert(1, branch.tree)
else:
self.tree.insert(1, branch.tree)
def right_subtree(self, branch):
right_list = self.tree.pop(2)
if len(right_list) > 1:
branch.tree[2] = right_list
self.tree.insert(2, branch.tree)
else:
self.tree.insert(2, branch.tree)
print('Create Root Node')
root = tree('Root_node')
print('Value of Root = ', root.tree)
print('Create Left Tree')
tree_left = tree('Tree_Left')
root.left_subtree(tree_left)
print('Value of Tree_Left = ', root.tree)
print('Create Right Tree')
tree_right = tree('Tree_Right')
root.right_subtree(tree_right)
print('Value of Tree_Right = ', root.tree)
print('Create Left Inbetween')
tree_inbtw = tree('Tree left in between')
root.left_subtree(tree_inbtw)
print('Value of Tree_Left = ', root.tree)
print('Create TreeLL')
treell = tree('TreeLL')
tree_left.left_subtree(treell)
print('Value of TREE = ', root.tree) |
def input_dimension():
while True:
dimension = input("Enter your board dimensions: ").split()
len_x1 = 0
len_y1 = 0
if len(dimension) != 2:
print("Invalid dimensions!")
continue
try:
len_x1 = int(dimension[0])
len_y1 = int(dimension[1])
except ValueError:
print("Invalid dimensions!")
continue
if len_x1 <= 0 or len_y1 <= 0:
print("Invalid dimensions!")
else:
break
return len_x1, len_y1
def input_starting():
while True:
position = input("Enter the knight's starting position: ").split()
x1, y1 = 0, 0
if len(position) != 2:
print("Invalid dimensions!")
continue
try:
x1 = int(position[0])
y1 = int(position[1])
except ValueError:
print("Invalid dimensions!")
continue
if not 1 <= x1 <= len_x or not 1 <= y1 <= len_y:
print("Invalid dimensions!")
else:
break
return x1, y1
def create_board():
for _i in range(len_x):
current_row = []
for _j in range(len_y):
current_row.append("_")
board.append(current_row)
def print_board(board1):
max_len = len(str(len_x * len_y))
print(" " + "-" * (len_x * (max_len + 1) + 3))
for i in range(len_y, 0, -1):
s = ""
for j in range(1, len_x + 1):
if board1[j - 1][i - 1] != '_':
s += " " + " " * (max_len - len(board1[j - 1][i - 1])) + board1[j - 1][i - 1]
elif count(board1, j, i, 'X') != 0:
next_count = str(count(board1, j, i, '_'))
s += " " + " " * (max_len - len(next_count)) + next_count
else:
s += " " + "_" * max_len
print(f"{i}|{s} |")
print(" " + "-" * (len_x * (max_len + 1) + 3))
s = ''
for i in range(len_x):
s += " " * max_len + str(i + 1)
print(" " + s + " ")
print()
def count(board1, x1, y1, symbol):
value = 0
if x1 + 1 <= len_x and y1 + 2 <= len_y and board1[x1][y1 + 1] == symbol:
value += 1
if x1 + 1 <= len_x and y1 - 2 > 0 and board1[x1][y1 - 3] == symbol:
value += 1
if x1 - 1 > 0 and y1 + 2 <= len_y and board1[x1 - 2][y1 + 1] == symbol:
value += 1
if x1 - 1 > 0 and y1 - 2 > 0 and board1[x1 - 2][y1 - 3] == symbol:
value += 1
if x1 + 2 <= len_x and y1 + 1 <= len_y and board1[x1 + 1][y1] == symbol:
value += 1
if x1 + 2 <= len_x and y1 - 1 > 0 and board1[x1 + 1][y1 - 2] == symbol:
value += 1
if x1 - 2 > 0 and y1 + 1 <= len_y and board1[x1 - 3][y1] == symbol:
value += 1
if x1 - 2 > 0 and y1 - 1 > 0 and board1[x1 - 3][y1 - 2] == symbol:
value += 1
return value
def move(board1, new_x1, new_y1):
board2 = []
for i in range(len_x):
current_row = []
for j in range(len_y):
if board1[i][j] == 'X':
current_row.append('*')
else:
current_row.append(board1[i][j])
board2.append(current_row)
board2[new_x1 - 1][new_y1 - 1] = "X"
return board2
def next_step(board1, new_x1, new_y1, index):
board2 = []
for i in range(len_x):
current_row = []
for j in range(len_y):
current_row.append(board1[i][j])
board2.append(current_row)
board2[new_x1 - 1][new_y1 - 1] = str(index)
return board2
def check_solution(board1):
total = 0
for i in range(len_x):
for j in range(len_y):
if board1[i][j] == '_' and count(board1, i + 1, j + 1, 'X') != 0:
board2 = move(board1, i + 1, j + 1)
if check_solution(board2):
return True
elif board1[i][j] in '*X':
total += 1
return total == len_x * len_y
def play_game(board1):
print_board(board1)
invalid = False
count_squares = 1
while True:
movie = input("Invalid move! Enter your next move: " if invalid else 'Enter your next move: ').split()
new_x = int(movie[0])
new_y = int(movie[1])
if board1[new_x - 1][new_y - 1] != '_' or count(board1, new_x, new_y, 'X') == 0:
invalid = True
else:
invalid = False
board1 = move(board1, new_x, new_y)
count_squares += 1
if count(board1, new_x, new_y, '_') == 0:
if len_x * len_y == count_squares:
print('What a great tour! Congratulations!')
else:
print('No more possible moves!')
print(f'Your knight visited {count_squares} squares!')
break
print_board(board1)
def print_solution(board1):
board2 = fill_board(board1, 1)
print_board(board2)
def fill_board(board1, index):
for i in range(len_x):
for j in range(len_y):
if board1[i][j] == '_' and count(board1, i + 1, j + 1, str(index)) != 0:
board2 = next_step(board1, i + 1, j + 1, index + 1)
if index + 1 == len_x * len_y:
return board2
board3 = fill_board(board2, index + 1)
if board3 is not None:
return board3
return None
board = []
len_x, len_y = input_dimension()
create_board()
x, y = input_starting()
board[x - 1][y - 1] = "X"
while True:
try_puzzle = input('Do you want to try the puzzle? (y/n): ')
if try_puzzle == 'y':
if not check_solution(list(board)):
print('No solution exists!')
exit()
play_game(board)
break
elif try_puzzle == 'n':
if not check_solution(list(board)):
print('No solution exists!')
exit()
board[x - 1][y - 1] = "1"
print("Here's the solution!")
print_solution(board)
break
else:
print('Invalid dimensions!')
| def input_dimension():
while True:
dimension = input('Enter your board dimensions: ').split()
len_x1 = 0
len_y1 = 0
if len(dimension) != 2:
print('Invalid dimensions!')
continue
try:
len_x1 = int(dimension[0])
len_y1 = int(dimension[1])
except ValueError:
print('Invalid dimensions!')
continue
if len_x1 <= 0 or len_y1 <= 0:
print('Invalid dimensions!')
else:
break
return (len_x1, len_y1)
def input_starting():
while True:
position = input("Enter the knight's starting position: ").split()
(x1, y1) = (0, 0)
if len(position) != 2:
print('Invalid dimensions!')
continue
try:
x1 = int(position[0])
y1 = int(position[1])
except ValueError:
print('Invalid dimensions!')
continue
if not 1 <= x1 <= len_x or not 1 <= y1 <= len_y:
print('Invalid dimensions!')
else:
break
return (x1, y1)
def create_board():
for _i in range(len_x):
current_row = []
for _j in range(len_y):
current_row.append('_')
board.append(current_row)
def print_board(board1):
max_len = len(str(len_x * len_y))
print(' ' + '-' * (len_x * (max_len + 1) + 3))
for i in range(len_y, 0, -1):
s = ''
for j in range(1, len_x + 1):
if board1[j - 1][i - 1] != '_':
s += ' ' + ' ' * (max_len - len(board1[j - 1][i - 1])) + board1[j - 1][i - 1]
elif count(board1, j, i, 'X') != 0:
next_count = str(count(board1, j, i, '_'))
s += ' ' + ' ' * (max_len - len(next_count)) + next_count
else:
s += ' ' + '_' * max_len
print(f'{i}|{s} |')
print(' ' + '-' * (len_x * (max_len + 1) + 3))
s = ''
for i in range(len_x):
s += ' ' * max_len + str(i + 1)
print(' ' + s + ' ')
print()
def count(board1, x1, y1, symbol):
value = 0
if x1 + 1 <= len_x and y1 + 2 <= len_y and (board1[x1][y1 + 1] == symbol):
value += 1
if x1 + 1 <= len_x and y1 - 2 > 0 and (board1[x1][y1 - 3] == symbol):
value += 1
if x1 - 1 > 0 and y1 + 2 <= len_y and (board1[x1 - 2][y1 + 1] == symbol):
value += 1
if x1 - 1 > 0 and y1 - 2 > 0 and (board1[x1 - 2][y1 - 3] == symbol):
value += 1
if x1 + 2 <= len_x and y1 + 1 <= len_y and (board1[x1 + 1][y1] == symbol):
value += 1
if x1 + 2 <= len_x and y1 - 1 > 0 and (board1[x1 + 1][y1 - 2] == symbol):
value += 1
if x1 - 2 > 0 and y1 + 1 <= len_y and (board1[x1 - 3][y1] == symbol):
value += 1
if x1 - 2 > 0 and y1 - 1 > 0 and (board1[x1 - 3][y1 - 2] == symbol):
value += 1
return value
def move(board1, new_x1, new_y1):
board2 = []
for i in range(len_x):
current_row = []
for j in range(len_y):
if board1[i][j] == 'X':
current_row.append('*')
else:
current_row.append(board1[i][j])
board2.append(current_row)
board2[new_x1 - 1][new_y1 - 1] = 'X'
return board2
def next_step(board1, new_x1, new_y1, index):
board2 = []
for i in range(len_x):
current_row = []
for j in range(len_y):
current_row.append(board1[i][j])
board2.append(current_row)
board2[new_x1 - 1][new_y1 - 1] = str(index)
return board2
def check_solution(board1):
total = 0
for i in range(len_x):
for j in range(len_y):
if board1[i][j] == '_' and count(board1, i + 1, j + 1, 'X') != 0:
board2 = move(board1, i + 1, j + 1)
if check_solution(board2):
return True
elif board1[i][j] in '*X':
total += 1
return total == len_x * len_y
def play_game(board1):
print_board(board1)
invalid = False
count_squares = 1
while True:
movie = input('Invalid move! Enter your next move: ' if invalid else 'Enter your next move: ').split()
new_x = int(movie[0])
new_y = int(movie[1])
if board1[new_x - 1][new_y - 1] != '_' or count(board1, new_x, new_y, 'X') == 0:
invalid = True
else:
invalid = False
board1 = move(board1, new_x, new_y)
count_squares += 1
if count(board1, new_x, new_y, '_') == 0:
if len_x * len_y == count_squares:
print('What a great tour! Congratulations!')
else:
print('No more possible moves!')
print(f'Your knight visited {count_squares} squares!')
break
print_board(board1)
def print_solution(board1):
board2 = fill_board(board1, 1)
print_board(board2)
def fill_board(board1, index):
for i in range(len_x):
for j in range(len_y):
if board1[i][j] == '_' and count(board1, i + 1, j + 1, str(index)) != 0:
board2 = next_step(board1, i + 1, j + 1, index + 1)
if index + 1 == len_x * len_y:
return board2
board3 = fill_board(board2, index + 1)
if board3 is not None:
return board3
return None
board = []
(len_x, len_y) = input_dimension()
create_board()
(x, y) = input_starting()
board[x - 1][y - 1] = 'X'
while True:
try_puzzle = input('Do you want to try the puzzle? (y/n): ')
if try_puzzle == 'y':
if not check_solution(list(board)):
print('No solution exists!')
exit()
play_game(board)
break
elif try_puzzle == 'n':
if not check_solution(list(board)):
print('No solution exists!')
exit()
board[x - 1][y - 1] = '1'
print("Here's the solution!")
print_solution(board)
break
else:
print('Invalid dimensions!') |
#
# This file contains the Python code from Program 6.2 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm06_02.txt
#
class StackAsArray(Stack):
def __init__(self, size = 0):
super(StackAsArray, self).__init__()
self._array = Array(size)
def purge(self):
while self._count > 0:
self._array[self._count] = None
self._count -= 1
#...
| class Stackasarray(Stack):
def __init__(self, size=0):
super(StackAsArray, self).__init__()
self._array = array(size)
def purge(self):
while self._count > 0:
self._array[self._count] = None
self._count -= 1 |
n = input()
split =n.split()
limak = int(split[0])
bob = int(split[-1])
years = 0
while True:
limak*=3
bob*=2
years+=1
if limak>bob:
break
print(years)
| n = input()
split = n.split()
limak = int(split[0])
bob = int(split[-1])
years = 0
while True:
limak *= 3
bob *= 2
years += 1
if limak > bob:
break
print(years) |
fizz = 3
buzz = 5
upto = 100
for n in range(1,(upto + 1)):
if n % fizz == 0:
if n % buzz == 0:
print("FizzBuzz")
else:
print("Fizz")
elif n % buzz == 0:
print("Buzz")
else:
print(n)
| fizz = 3
buzz = 5
upto = 100
for n in range(1, upto + 1):
if n % fizz == 0:
if n % buzz == 0:
print('FizzBuzz')
else:
print('Fizz')
elif n % buzz == 0:
print('Buzz')
else:
print(n) |
#!/usr/bin/env python3
def count_combos(coins, total):
len_coins = len(coins)
memo = {}
def count(tot, i):
if tot == 0:
return 1
if i == len_coins:
return 0
subproblem = (tot, i)
try:
return memo[subproblem]
except KeyError:
j = i + 1
subtotals = range(0, total + 1, coins[i])
combos = sum(count(tot - subtot, j) for subtot in subtotals)
memo[subproblem] = combos
return combos
return count(total, 0)
def read_record():
return map(int, input().split())
total, _ = read_record() # don't need m
coins = list(read_record())
print(count_combos(coins, total))
| def count_combos(coins, total):
len_coins = len(coins)
memo = {}
def count(tot, i):
if tot == 0:
return 1
if i == len_coins:
return 0
subproblem = (tot, i)
try:
return memo[subproblem]
except KeyError:
j = i + 1
subtotals = range(0, total + 1, coins[i])
combos = sum((count(tot - subtot, j) for subtot in subtotals))
memo[subproblem] = combos
return combos
return count(total, 0)
def read_record():
return map(int, input().split())
(total, _) = read_record()
coins = list(read_record())
print(count_combos(coins, total)) |
ans = []
n = int(input())
for i in range(n):
a, b = list(map(int, input().split()))
ans.append(a + b)
for i in range(len(ans)):
print("Case #{}: {}".format(i+1, ans[i])) | ans = []
n = int(input())
for i in range(n):
(a, b) = list(map(int, input().split()))
ans.append(a + b)
for i in range(len(ans)):
print('Case #{}: {}'.format(i + 1, ans[i])) |
SYSDIGERR = -1
NOPROCESS = -2
NOFUNCS = -3
NOATTACH = -4
CONSTOP = -5
HSTOPS = -6
HLOGLEN = -7
HNOKILL = -8
HNORUN = -9
CACHE = ".cache"
LIBFILENAME = "libs.out"
LANGFILENAME = ".lang.cache"
BINLISTCACHE = ".binlist.cache"
LIBLISTCACHE = ".liblist.cache"
BINTOLIBCACHE = ".bintolib.cache"
TOOLNAME = "CONFINE"
SECCOMPCPROG = "seccomp"
DOCKERENTRYSCRIPT = "docker-entrypoint.sh"
DOCKERENTRYSCRIPTMODIFIED = "docker-entrypoint.wseccomp.sh"
ERRTOMSG = dict()
ERRTOMSG[SYSDIGERR] = "There was an error running sysdig, please make sure it is installed and the script has enough privileges to run it"
ERRTOMSG[NOPROCESS] = "Sysdig was not able to identify any processes. This causes our dynamic analysis to fail and the static analysis cannot analyze anything"
ERRTOMSG[NOFUNCS] = "No imported functions could be extracted from any of the binaries and libraries required by the container"
ERRTOMSG[NOATTACH] = "The container did not run in attached mode"
ERRTOMSG[CONSTOP] = "The container got killed after being launched in attach mode"
ERRTOMSG[HSTOPS] = "The hardened container stops running. Probably due to a problem in generating the SECCOMP profile and prohibiting access to a required system call"
ERRTOMSG[HLOGLEN] = "While the container has been hardened successfully, the log length doesn't match the original log length, which was run without any SECCOMP profile"
ERRTOMSG[HNOKILL] = "The container has been hardened successfully, but we could not kill it afterwards. This usually means that the container has died. If so, the generated profile has a problem"
ERRTOMSG[HNORUN] = "The hardened container does not run at all. The generated SECCOMP profile has a problem"
| sysdigerr = -1
noprocess = -2
nofuncs = -3
noattach = -4
constop = -5
hstops = -6
hloglen = -7
hnokill = -8
hnorun = -9
cache = '.cache'
libfilename = 'libs.out'
langfilename = '.lang.cache'
binlistcache = '.binlist.cache'
liblistcache = '.liblist.cache'
bintolibcache = '.bintolib.cache'
toolname = 'CONFINE'
seccompcprog = 'seccomp'
dockerentryscript = 'docker-entrypoint.sh'
dockerentryscriptmodified = 'docker-entrypoint.wseccomp.sh'
errtomsg = dict()
ERRTOMSG[SYSDIGERR] = 'There was an error running sysdig, please make sure it is installed and the script has enough privileges to run it'
ERRTOMSG[NOPROCESS] = 'Sysdig was not able to identify any processes. This causes our dynamic analysis to fail and the static analysis cannot analyze anything'
ERRTOMSG[NOFUNCS] = 'No imported functions could be extracted from any of the binaries and libraries required by the container'
ERRTOMSG[NOATTACH] = 'The container did not run in attached mode'
ERRTOMSG[CONSTOP] = 'The container got killed after being launched in attach mode'
ERRTOMSG[HSTOPS] = 'The hardened container stops running. Probably due to a problem in generating the SECCOMP profile and prohibiting access to a required system call'
ERRTOMSG[HLOGLEN] = "While the container has been hardened successfully, the log length doesn't match the original log length, which was run without any SECCOMP profile"
ERRTOMSG[HNOKILL] = 'The container has been hardened successfully, but we could not kill it afterwards. This usually means that the container has died. If so, the generated profile has a problem'
ERRTOMSG[HNORUN] = 'The hardened container does not run at all. The generated SECCOMP profile has a problem' |
#Given an array nums and a value val, remove all instances of that value in-place and return the new length.
#Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#The order of elements can be changed. It doesn't matter what you leave beyond the new length.
#Example 1:
#Given nums = [3,2,2,3], val = 3,
#Your function should return length = 2, with the first two elements of nums being 2.
#It doesn't matter what you leave beyond the returned length.
#Example 2:
#Given nums = [0,1,2,2,3,0,4,2], val = 2,
#Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
#Note that the order of those five elements can be arbitrary.
#It doesn't matter what values are set beyond the returned length.
#Clarification:
#Confused why the returned value is an integer but your answer is an array?
#Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
#Internally you can think of this:
#// nums is passed in by reference. (i.e., without making a copy)
#int len = removeElement(nums, val);
#// any modification to nums in your function would be known by the caller.
#// using the length returned by your function, it prints the first len elements.
#for (int i = 0; i < len; i++) {
# print(nums[i]);
#}
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
result=[]
m=0
for n in range(len(nums)):
if nums[n]!=val:
nums[m]=nums[n]
m+=1
return m
| class Solution:
def remove_element(self, nums: List[int], val: int) -> int:
result = []
m = 0
for n in range(len(nums)):
if nums[n] != val:
nums[m] = nums[n]
m += 1
return m |
#!/bin/env/python
infileList = []
keyList = []
cList = (
"GBR",
"FIN",
"CHS",
"PUR",
"CLM",
"IBS",
"CEU",
"YRI",
"CHB",
"JPT",
"LWK",
"ASW",
"MXL",
"TSI",
)
for i in range(17,23):
infileList.append("proc_input.chr" + str(i) + ".vcf")
keyList.append("cluster_chr" + str(i))
infileList.append("proc_input.chrX.vcf")
keyList.append("cluster_chrX")
for l in range(len(infileList)):
files = open(infileList[l], "r")
outFile = open("output/" + keyList[l], "w")
logFile = open("output/cluster.log", "w")
line = files.readline()
count = 0
cDict = {}
while line:
if not count == 0:
tmp = line.split(",")
for k in range(len(tmp)):
if not k == 0:
value = tmp[k].split(":")
if count == 1:
cDict[cList[k - 1]] = value
logFile.write("cList: " + str(cList[k-1]))
for j in range(len(cDict[cList[k - 1]])):
cDict[cList[k - 1]][j] = int(cDict[cList[k - 1]][j])
else:
for j in range(len(value)):
if not j == 3:
cDict[cList[k - 1]][j] += int(value[j])
count += 1
line = files.readline()
print(str(count) + " end")
logFile.write("cDict: " + str(cDict))
for k, list in cDict.items():
sum = 0
for v in list:
sum += int(v)
logFile.write("sum: " + str(sum))
for v in range(len(list)):
if not v == len(list) - 1:
outFile.write(str(round((float(list[v]) / float(sum)) * 100, 2)) + ",")
else:
outFile.write(str(round((float(list[v]) / float(sum)) * 100, 2)) + "\n")
print(infileList[l] + " success")
files.close()
outFile.close()
logFile.close()
| infile_list = []
key_list = []
c_list = ('GBR', 'FIN', 'CHS', 'PUR', 'CLM', 'IBS', 'CEU', 'YRI', 'CHB', 'JPT', 'LWK', 'ASW', 'MXL', 'TSI')
for i in range(17, 23):
infileList.append('proc_input.chr' + str(i) + '.vcf')
keyList.append('cluster_chr' + str(i))
infileList.append('proc_input.chrX.vcf')
keyList.append('cluster_chrX')
for l in range(len(infileList)):
files = open(infileList[l], 'r')
out_file = open('output/' + keyList[l], 'w')
log_file = open('output/cluster.log', 'w')
line = files.readline()
count = 0
c_dict = {}
while line:
if not count == 0:
tmp = line.split(',')
for k in range(len(tmp)):
if not k == 0:
value = tmp[k].split(':')
if count == 1:
cDict[cList[k - 1]] = value
logFile.write('cList: ' + str(cList[k - 1]))
for j in range(len(cDict[cList[k - 1]])):
cDict[cList[k - 1]][j] = int(cDict[cList[k - 1]][j])
else:
for j in range(len(value)):
if not j == 3:
cDict[cList[k - 1]][j] += int(value[j])
count += 1
line = files.readline()
print(str(count) + ' end')
logFile.write('cDict: ' + str(cDict))
for (k, list) in cDict.items():
sum = 0
for v in list:
sum += int(v)
logFile.write('sum: ' + str(sum))
for v in range(len(list)):
if not v == len(list) - 1:
outFile.write(str(round(float(list[v]) / float(sum) * 100, 2)) + ',')
else:
outFile.write(str(round(float(list[v]) / float(sum) * 100, 2)) + '\n')
print(infileList[l] + ' success')
files.close()
outFile.close()
logFile.close() |
n = int(input())
sumI = 0
for i in range(n):
sumI = sumI + int(input())
o = int(input())
for i in range(o):
sumI = sumI + int(input())
print('{:.3f}'.format((round(sumI*1000/(n+i+1)))/1000))
| n = int(input())
sum_i = 0
for i in range(n):
sum_i = sumI + int(input())
o = int(input())
for i in range(o):
sum_i = sumI + int(input())
print('{:.3f}'.format(round(sumI * 1000 / (n + i + 1)) / 1000)) |
class HeapError(Exception):
pass
class Heap(object):
def __init__(self, iterable=()):
self._heap = []
for value in iterable:
self.push(value)
def _get(self, node):
if not self._heap:
raise HeapError("empty heap")
if node is None:
return self._heap[0]
if len(self._heap) <= node._index or self._heap[node._index] is not node:
raise HeapError("node not in the heap")
return node
def push(self, value):
node = _Node(len(self._heap), value)
self._heap.append(node)
_up(self._heap, node)
return node
def peek(self, node=None):
return self._get(node)._value
def pop(self, node=None):
node = self._get(node)
last = self._heap.pop()
if last is not node:
self._heap[node._index] = last
last._index = node._index
_down(self._heap, last)
_up(self._heap, last)
return node._value
def head(self):
return self._get(None)
def __len__(self):
return len(self._heap)
class _Node(object):
__slots__ = "_index", "_value"
def __init__(self, index, value):
self._index = index
self._value = value
def _swap(array, left, right):
array[left._index] = right
array[right._index] = left
left._index, right._index = right._index, left._index
def _up(array, node):
while node._index > 0:
parent = array[(node._index - 1) // 2]
if parent._value <= node._value:
break
_swap(array, node, parent)
def _down(array, node):
length = len(array)
while True:
smallest = node
left_index = 2 * node._index + 1
if left_index < length:
left = array[left_index]
if left._value < smallest._value:
smallest = left
right_index = left_index + 1
if right_index < length:
right = array[right_index]
if right._value < smallest._value:
smallest = right
if node is smallest:
break
_swap(array, node, smallest)
| class Heaperror(Exception):
pass
class Heap(object):
def __init__(self, iterable=()):
self._heap = []
for value in iterable:
self.push(value)
def _get(self, node):
if not self._heap:
raise heap_error('empty heap')
if node is None:
return self._heap[0]
if len(self._heap) <= node._index or self._heap[node._index] is not node:
raise heap_error('node not in the heap')
return node
def push(self, value):
node = __node(len(self._heap), value)
self._heap.append(node)
_up(self._heap, node)
return node
def peek(self, node=None):
return self._get(node)._value
def pop(self, node=None):
node = self._get(node)
last = self._heap.pop()
if last is not node:
self._heap[node._index] = last
last._index = node._index
_down(self._heap, last)
_up(self._heap, last)
return node._value
def head(self):
return self._get(None)
def __len__(self):
return len(self._heap)
class _Node(object):
__slots__ = ('_index', '_value')
def __init__(self, index, value):
self._index = index
self._value = value
def _swap(array, left, right):
array[left._index] = right
array[right._index] = left
(left._index, right._index) = (right._index, left._index)
def _up(array, node):
while node._index > 0:
parent = array[(node._index - 1) // 2]
if parent._value <= node._value:
break
_swap(array, node, parent)
def _down(array, node):
length = len(array)
while True:
smallest = node
left_index = 2 * node._index + 1
if left_index < length:
left = array[left_index]
if left._value < smallest._value:
smallest = left
right_index = left_index + 1
if right_index < length:
right = array[right_index]
if right._value < smallest._value:
smallest = right
if node is smallest:
break
_swap(array, node, smallest) |
# Sum of numbers 3
def get_sum(x, y):
s = 0
if x > y:
for index in range(y, x + 1):
s = s + index
return s
elif x < y:
for index in range(x, y + 1):
s = s + index
return s
else:
return x
print(get_sum(2, 1))
print(get_sum(0, -1))
| def get_sum(x, y):
s = 0
if x > y:
for index in range(y, x + 1):
s = s + index
return s
elif x < y:
for index in range(x, y + 1):
s = s + index
return s
else:
return x
print(get_sum(2, 1))
print(get_sum(0, -1)) |
# EMPTY = "L"
# OCCUPIED = "#"
# FIXED = "."
EMPTY = 0
OCCUPIED = 1
FIXED = -1
def read_input(file_name):
seats = []
with open(file_name) as input_file:
for line in input_file:
line = line.strip()
seats.append( list(map(map_input, line) ))
return seats
# Failed attempt to speed up the program
def map_input(x):
if x == ".":
return FIXED
elif x == "L":
return EMPTY
elif x == "#":
return OCCUPIED
else:
raise RuntimeError("Unhandled input")
# The following rules are applied to every seat simultaneously:
# If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied.
# If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty.
# Otherwise, the seat's state does not change.
# Floor (.) never changes; seats don't move, and nobody sits on the floor.
# adjacent = left, right, or diagonal from the seat
def part1(seats):
# My answer: 2303
return run_iterations(seats, 1, 4)
# Part 2: like part 1, but different rules for state change
def part2(seats):
# my answer: 2057
return run_iterations(seats, max(len(seats), len(seats[0])), 5)
def run_iterations(seats, max_extent, occupied_limit):
num_cycles = 0
num_rows = len(seats)
num_columns = len(seats[0])
seats_copy = [row.copy() for row in seats]
new_seat_state = [ [FIXED for j in range(num_columns)] for i in range(num_rows) ]
while True:
num_cycles += 1
num_changes = 0
for row in range(num_rows):
for column in range(num_columns):
current_state = seats_copy[row][column]
if current_state != FIXED:
occupied = count_occupied(seats_copy, row, column, max_extent)
if current_state == EMPTY and occupied == 0:
new_seat_state[row][column] = OCCUPIED
num_changes += 1
elif current_state == OCCUPIED and occupied >= occupied_limit:
new_seat_state[row][column] = EMPTY
num_changes += 1
else:
new_seat_state[row][column] = current_state
if num_changes == 0 or num_cycles > 1000:
break
# else:
# print("Iteration {} num changes: {}".format(num_cycles, num_changes))
tmp = new_seat_state
new_seat_state = seats_copy
seats_copy = tmp
num_occupied = 0
for row in seats_copy:
for seat in row:
if seat == OCCUPIED:
num_occupied += 1
return num_occupied
def count_occupied(seats, row, column, max_extent):
occupied = 0
offsets = [-1, 0, 1]
num_rows = len(seats)
num_columns = len(seats[0])
for r in offsets:
for c in offsets:
if r == 0 and c == 0:
continue
for i in range(1, max_extent + 1):
offset_row = row + r * i
if offset_row < 0 or offset_row >= num_rows:
break
offset_column = column + c * i
if offset_column < 0 or offset_column >= num_columns:
break
current_state = seats[offset_row][offset_column]
if current_state == OCCUPIED:
occupied += 1
break
elif current_state == EMPTY:
break
return occupied
# This is pathetically slow. Not sure why, this would be fast in Java.
seats = read_input('day11_input.txt')
num_seats_filled = part1(seats)
print("Part 1: number of seats filled : {}".format(num_seats_filled))
num_seats_filled = part2(seats)
print("Part 2: number of seats filled {}".format(num_seats_filled))
| empty = 0
occupied = 1
fixed = -1
def read_input(file_name):
seats = []
with open(file_name) as input_file:
for line in input_file:
line = line.strip()
seats.append(list(map(map_input, line)))
return seats
def map_input(x):
if x == '.':
return FIXED
elif x == 'L':
return EMPTY
elif x == '#':
return OCCUPIED
else:
raise runtime_error('Unhandled input')
def part1(seats):
return run_iterations(seats, 1, 4)
def part2(seats):
return run_iterations(seats, max(len(seats), len(seats[0])), 5)
def run_iterations(seats, max_extent, occupied_limit):
num_cycles = 0
num_rows = len(seats)
num_columns = len(seats[0])
seats_copy = [row.copy() for row in seats]
new_seat_state = [[FIXED for j in range(num_columns)] for i in range(num_rows)]
while True:
num_cycles += 1
num_changes = 0
for row in range(num_rows):
for column in range(num_columns):
current_state = seats_copy[row][column]
if current_state != FIXED:
occupied = count_occupied(seats_copy, row, column, max_extent)
if current_state == EMPTY and occupied == 0:
new_seat_state[row][column] = OCCUPIED
num_changes += 1
elif current_state == OCCUPIED and occupied >= occupied_limit:
new_seat_state[row][column] = EMPTY
num_changes += 1
else:
new_seat_state[row][column] = current_state
if num_changes == 0 or num_cycles > 1000:
break
tmp = new_seat_state
new_seat_state = seats_copy
seats_copy = tmp
num_occupied = 0
for row in seats_copy:
for seat in row:
if seat == OCCUPIED:
num_occupied += 1
return num_occupied
def count_occupied(seats, row, column, max_extent):
occupied = 0
offsets = [-1, 0, 1]
num_rows = len(seats)
num_columns = len(seats[0])
for r in offsets:
for c in offsets:
if r == 0 and c == 0:
continue
for i in range(1, max_extent + 1):
offset_row = row + r * i
if offset_row < 0 or offset_row >= num_rows:
break
offset_column = column + c * i
if offset_column < 0 or offset_column >= num_columns:
break
current_state = seats[offset_row][offset_column]
if current_state == OCCUPIED:
occupied += 1
break
elif current_state == EMPTY:
break
return occupied
seats = read_input('day11_input.txt')
num_seats_filled = part1(seats)
print('Part 1: number of seats filled : {}'.format(num_seats_filled))
num_seats_filled = part2(seats)
print('Part 2: number of seats filled {}'.format(num_seats_filled)) |
# When user enters 'exit', exit program
while (True):
inp = raw_input('> ')
if inp.lower() == 'exit':
break
else:
print(inp)
| while True:
inp = raw_input('> ')
if inp.lower() == 'exit':
break
else:
print(inp) |
# https://leetcode.com/problems/bulls-and-cows
class Solution:
def getHint(self, secret, guess):
s_used, g_used = set(), set()
bull = 0
for idx, (s_char, g_char) in enumerate(zip(secret, guess)):
if s_char == g_char:
bull += 1
s_used.add(idx)
g_used.add(idx)
print(s_used)
print(g_used)
cow = 0
for i, s_char in enumerate(secret):
for j, g_char in enumerate(guess):
if (s_char == g_char) and (i not in s_used) and (j not in g_used):
cow += 1
s_used.add(i)
g_used.add(j)
print(s_used)
print(g_used)
return "{}A{}B".format(bull, cow)
| class Solution:
def get_hint(self, secret, guess):
(s_used, g_used) = (set(), set())
bull = 0
for (idx, (s_char, g_char)) in enumerate(zip(secret, guess)):
if s_char == g_char:
bull += 1
s_used.add(idx)
g_used.add(idx)
print(s_used)
print(g_used)
cow = 0
for (i, s_char) in enumerate(secret):
for (j, g_char) in enumerate(guess):
if s_char == g_char and i not in s_used and (j not in g_used):
cow += 1
s_used.add(i)
g_used.add(j)
print(s_used)
print(g_used)
return '{}A{}B'.format(bull, cow) |
__version__ = '0.2.2'
default_app_config = 'cid.apps.CidAppConfig'
| __version__ = '0.2.2'
default_app_config = 'cid.apps.CidAppConfig' |
#
# PySNMP MIB module HH3C-IDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-IDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:27:21 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, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection")
hh3cCommon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cCommon")
InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Bits, Counter64, ModuleIdentity, Unsigned32, TimeTicks, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, ObjectIdentity, iso, Integer32, MibIdentifier, Gauge32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter64", "ModuleIdentity", "Unsigned32", "TimeTicks", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "ObjectIdentity", "iso", "Integer32", "MibIdentifier", "Gauge32", "NotificationType")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
hh3cIDSMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1))
if mibBuilder.loadTexts: hh3cIDSMib.setLastUpdated('200507141942Z')
if mibBuilder.loadTexts: hh3cIDSMib.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
if mibBuilder.loadTexts: hh3cIDSMib.setContactInfo('Platform Team Hangzhou H3C Tech. Co., Ltd. Hai-Dian District Beijing P.R. China http://www.h3c.com Zip:100085 ')
if mibBuilder.loadTexts: hh3cIDSMib.setDescription('This MIB describes IDS private information. IDS(Instruction Detecting System) is used to detect intruder activity. ')
hh3cIds = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 47))
hh3cIDSTrapGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1))
hh3cIDSTrapInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1))
hh3cIDSTrapIPFragmentQueueLen = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 1), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapIPFragmentQueueLen.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapIPFragmentQueueLen.setDescription('The length of IP fragment queue.')
hh3cIDSTrapStatSessionTabLen = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 2), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapStatSessionTabLen.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapStatSessionTabLen.setDescription('The length of status session table.')
hh3cIDSTrapIPAddressType = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 3), InetAddressType()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapIPAddressType.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapIPAddressType.setDescription('The type of IP Address.')
hh3cIDSTrapIPAddress = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 4), InetAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapIPAddress.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapIPAddress.setDescription('IP Address.')
hh3cIDSTrapUserName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapUserName.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapUserName.setDescription('User name.')
hh3cIDSTrapLoginType = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("telnet", 1), ("ssh", 2), ("web", 3)))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapLoginType.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapLoginType.setDescription('Login type, including telnet, ssh and web.')
hh3cIDSTrapUpgradeType = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("programme", 1), ("crb", 2), ("vrb", 3)))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapUpgradeType.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapUpgradeType.setDescription('Upgrade type, including programme(system image), crb(custom rule base, one kind of configuration file), vrb(vendor rule base, one kind of configuration file).')
hh3cIDSTrapCRLName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapCRLName.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapCRLName.setDescription('CRL(Certificate Revoke List) name.')
hh3cIDSTrapCertName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 9), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapCertName.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapCertName.setDescription('Certificate name.')
hh3cIDSTrapDetectRuleID = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 10), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapDetectRuleID.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapDetectRuleID.setDescription('The rule ID which is a unique identifier for a specified detect rule.')
hh3cIDSTrapEngineID = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 11), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapEngineID.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapEngineID.setDescription('A unique number used to identify an interface.')
hh3cIDSTrapFileName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 12), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapFileName.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapFileName.setDescription('The file name.')
hh3cIDSTrapCfgLineInFile = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 13), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapCfgLineInFile.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapCfgLineInFile.setDescription('The line number in the configuration file.')
hh3cIDSTrapReasonForError = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 14), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cIDSTrapReasonForError.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapReasonForError.setDescription('The information of the notification. Although the format and content of this object are device specific, they should be defined uniformly in the device.')
hh3cIDSTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2))
hh3cIDSTrapPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0))
hh3cIDSTrapIPFragQueueFull = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 1)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapIPFragmentQueueLen"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapIPFragQueueFull.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapIPFragQueueFull.setDescription('This notification will be generated when the IP fragment queue is full. The hh3cIDSTrapIPFragmentQueueLen describes the length of current fragment queue. The hh3cIDSTrapReasonForError describes reason for error.')
hh3cIDSTrapStatSessTabFull = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 2)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapStatSessionTabLen"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapStatSessTabFull.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapStatSessTabFull.setDescription('This notification will be generated when the status session table is full. The hh3cIDSTrapStatSessionTabLen describes the length of current status session table. The hh3cIDSTrapReasonForError describes reason for error.')
hh3cIDSTrapDetectRuleParseFail = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 3)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapDetectRuleID"), ("HH3C-IDS-MIB", "hh3cIDSTrapEngineID"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapDetectRuleParseFail.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapDetectRuleParseFail.setDescription('This notification will be generated when failing to parse the rules for detecting. The hh3cIDSTrapDetectRuleID object describes rule ID. The hh3cIDSTrapEngineID object identifies an interface the rule applies to. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapDBConnLost = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 4)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapIPAddressType"), ("HH3C-IDS-MIB", "hh3cIDSTrapIPAddress"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapDBConnLost.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapDBConnLost.setDescription('This notification will be generated when connecting with database server fails. The hh3cIDSTrapIPAddressType object describes the IP address type of database server. The hh3cIDSTrapIPAddress object describes the IP address of database server. The hh3cIDSTrapReasonForError describes reason of connecting failure.')
hh3cIDSTrapCRLNeedUpdate = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 5)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapCRLName"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapCRLNeedUpdate.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapCRLNeedUpdate.setDescription('This notification will be generated when IDS device detects that CRL is out of date. The hh3cIDSTrapCRLName object describes the CRL(Certificate Revoke List) name. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapCertOverdue = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 6)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapCertName"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapCertOverdue.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapCertOverdue.setDescription('This notification will be generated when IDS device detects that certificate is overdue. The hh3cIDSTrapCertName object describes the certificate name. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapTooManyLoginFail = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 7)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapUserName"), ("HH3C-IDS-MIB", "hh3cIDSTrapIPAddressType"), ("HH3C-IDS-MIB", "hh3cIDSTrapIPAddress"), ("HH3C-IDS-MIB", "hh3cIDSTrapLoginType"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapTooManyLoginFail.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapTooManyLoginFail.setDescription('This notification will be generated when the login failure times of a user over a certain number. The hh3cIDSTrapUserName object describes the user name when logging in. The hh3cIDSTrapIPAddressType object describes the IP address type of client. The hh3cIDSTrapIPAddress object describes the IP address of client. The hh3cIDSTrapLoginType object describes login type, including: telnet, ssh, web. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapUpgradeError = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 8)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapUpgradeType"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapUpgradeError.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapUpgradeError.setDescription('This notification will be generated when upgrading fails. The hh3cIDSTrapUpgradeType object describes upgrade type, including: programme, vrb. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapFileAccessError = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 9)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapFileName"), ("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapFileAccessError.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapFileAccessError.setDescription('This notification will be generated when accessing file fails. The hh3cIDSTrapFileName object describes the name of file accessed. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapConsArithMemLow = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 10)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapConsArithMemLow.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapConsArithMemLow.setDescription('This notification will be generated when memory used by constructing the arithmetic to seek content is lacking. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapSSRAMOperFail = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 11)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapSSRAMOperFail.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapSSRAMOperFail.setDescription('This notification will be generated when reading or writing SSRAM of CIE card fails. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapPacketProcessDisorder = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 12)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapReasonForError"))
if mibBuilder.loadTexts: hh3cIDSTrapPacketProcessDisorder.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapPacketProcessDisorder.setDescription('This notification will be generated when packets processed is in disorder. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3cIDSTrapCfgFileFormatError = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 13)).setObjects(("HH3C-IDS-MIB", "hh3cIDSTrapFileName"), ("HH3C-IDS-MIB", "hh3cIDSTrapCfgLineInFile"))
if mibBuilder.loadTexts: hh3cIDSTrapCfgFileFormatError.setStatus('current')
if mibBuilder.loadTexts: hh3cIDSTrapCfgFileFormatError.setDescription('When devices startup and load the configuration file, if format error is found, this notification will be generated. The hh3cIDSTrapFileName object describes the name of configuration file. The hh3cIDSTrapCfgLineInFile object describes the line number in the file.')
mibBuilder.exportSymbols("HH3C-IDS-MIB", hh3cIDSTrapCertName=hh3cIDSTrapCertName, hh3cIDSTrapUpgradeError=hh3cIDSTrapUpgradeError, hh3cIDSTrapDetectRuleParseFail=hh3cIDSTrapDetectRuleParseFail, hh3cIDSTrapCfgFileFormatError=hh3cIDSTrapCfgFileFormatError, hh3cIDSTrapIPFragmentQueueLen=hh3cIDSTrapIPFragmentQueueLen, hh3cIDSTrapPrefix=hh3cIDSTrapPrefix, hh3cIDSTrapConsArithMemLow=hh3cIDSTrapConsArithMemLow, hh3cIDSTrapCRLNeedUpdate=hh3cIDSTrapCRLNeedUpdate, hh3cIDSTrapStatSessionTabLen=hh3cIDSTrapStatSessionTabLen, hh3cIDSTrapPacketProcessDisorder=hh3cIDSTrapPacketProcessDisorder, hh3cIDSTrapEngineID=hh3cIDSTrapEngineID, hh3cIDSTrapCfgLineInFile=hh3cIDSTrapCfgLineInFile, hh3cIDSTrapIPFragQueueFull=hh3cIDSTrapIPFragQueueFull, hh3cIDSTrapFileName=hh3cIDSTrapFileName, hh3cIDSTrapDBConnLost=hh3cIDSTrapDBConnLost, hh3cIDSTrapFileAccessError=hh3cIDSTrapFileAccessError, hh3cIDSTrapCertOverdue=hh3cIDSTrapCertOverdue, hh3cIDSMib=hh3cIDSMib, hh3cIDSTrapInfo=hh3cIDSTrapInfo, hh3cIDSTrapTooManyLoginFail=hh3cIDSTrapTooManyLoginFail, hh3cIDSTrapCRLName=hh3cIDSTrapCRLName, hh3cIDSTrapIPAddressType=hh3cIDSTrapIPAddressType, hh3cIDSTrapIPAddress=hh3cIDSTrapIPAddress, hh3cIDSTrapLoginType=hh3cIDSTrapLoginType, hh3cIDSTrapUserName=hh3cIDSTrapUserName, hh3cIDSTrapSSRAMOperFail=hh3cIDSTrapSSRAMOperFail, hh3cIds=hh3cIds, hh3cIDSTrap=hh3cIDSTrap, PYSNMP_MODULE_ID=hh3cIDSMib, hh3cIDSTrapGroup=hh3cIDSTrapGroup, hh3cIDSTrapUpgradeType=hh3cIDSTrapUpgradeType, hh3cIDSTrapDetectRuleID=hh3cIDSTrapDetectRuleID, hh3cIDSTrapStatSessTabFull=hh3cIDSTrapStatSessTabFull, hh3cIDSTrapReasonForError=hh3cIDSTrapReasonForError)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection')
(hh3c_common,) = mibBuilder.importSymbols('HH3C-OID-MIB', 'hh3cCommon')
(inet_address_type, inet_address) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressType', 'InetAddress')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(bits, counter64, module_identity, unsigned32, time_ticks, ip_address, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, object_identity, iso, integer32, mib_identifier, gauge32, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'Counter64', 'ModuleIdentity', 'Unsigned32', 'TimeTicks', 'IpAddress', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'ObjectIdentity', 'iso', 'Integer32', 'MibIdentifier', 'Gauge32', 'NotificationType')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
hh3c_ids_mib = module_identity((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1))
if mibBuilder.loadTexts:
hh3cIDSMib.setLastUpdated('200507141942Z')
if mibBuilder.loadTexts:
hh3cIDSMib.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
if mibBuilder.loadTexts:
hh3cIDSMib.setContactInfo('Platform Team Hangzhou H3C Tech. Co., Ltd. Hai-Dian District Beijing P.R. China http://www.h3c.com Zip:100085 ')
if mibBuilder.loadTexts:
hh3cIDSMib.setDescription('This MIB describes IDS private information. IDS(Instruction Detecting System) is used to detect intruder activity. ')
hh3c_ids = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 47))
hh3c_ids_trap_group = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1))
hh3c_ids_trap_info = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1))
hh3c_ids_trap_ip_fragment_queue_len = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 1), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapIPFragmentQueueLen.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapIPFragmentQueueLen.setDescription('The length of IP fragment queue.')
hh3c_ids_trap_stat_session_tab_len = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 2), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapStatSessionTabLen.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapStatSessionTabLen.setDescription('The length of status session table.')
hh3c_ids_trap_ip_address_type = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 3), inet_address_type()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapIPAddressType.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapIPAddressType.setDescription('The type of IP Address.')
hh3c_ids_trap_ip_address = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 4), inet_address()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapIPAddress.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapIPAddress.setDescription('IP Address.')
hh3c_ids_trap_user_name = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 5), octet_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapUserName.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapUserName.setDescription('User name.')
hh3c_ids_trap_login_type = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('telnet', 1), ('ssh', 2), ('web', 3)))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapLoginType.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapLoginType.setDescription('Login type, including telnet, ssh and web.')
hh3c_ids_trap_upgrade_type = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('programme', 1), ('crb', 2), ('vrb', 3)))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapUpgradeType.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapUpgradeType.setDescription('Upgrade type, including programme(system image), crb(custom rule base, one kind of configuration file), vrb(vendor rule base, one kind of configuration file).')
hh3c_ids_trap_crl_name = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 8), octet_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapCRLName.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapCRLName.setDescription('CRL(Certificate Revoke List) name.')
hh3c_ids_trap_cert_name = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 9), octet_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapCertName.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapCertName.setDescription('Certificate name.')
hh3c_ids_trap_detect_rule_id = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 10), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapDetectRuleID.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapDetectRuleID.setDescription('The rule ID which is a unique identifier for a specified detect rule.')
hh3c_ids_trap_engine_id = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 11), integer32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapEngineID.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapEngineID.setDescription('A unique number used to identify an interface.')
hh3c_ids_trap_file_name = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 12), octet_string().subtype(subtypeSpec=value_size_constraint(0, 256))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapFileName.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapFileName.setDescription('The file name.')
hh3c_ids_trap_cfg_line_in_file = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 13), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapCfgLineInFile.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapCfgLineInFile.setDescription('The line number in the configuration file.')
hh3c_ids_trap_reason_for_error = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 1, 14), octet_string().subtype(subtypeSpec=value_size_constraint(0, 256))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cIDSTrapReasonForError.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapReasonForError.setDescription('The information of the notification. Although the format and content of this object are device specific, they should be defined uniformly in the device.')
hh3c_ids_trap = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2))
hh3c_ids_trap_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0))
hh3c_ids_trap_ip_frag_queue_full = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 1)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapIPFragmentQueueLen'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapIPFragQueueFull.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapIPFragQueueFull.setDescription('This notification will be generated when the IP fragment queue is full. The hh3cIDSTrapIPFragmentQueueLen describes the length of current fragment queue. The hh3cIDSTrapReasonForError describes reason for error.')
hh3c_ids_trap_stat_sess_tab_full = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 2)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapStatSessionTabLen'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapStatSessTabFull.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapStatSessTabFull.setDescription('This notification will be generated when the status session table is full. The hh3cIDSTrapStatSessionTabLen describes the length of current status session table. The hh3cIDSTrapReasonForError describes reason for error.')
hh3c_ids_trap_detect_rule_parse_fail = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 3)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapDetectRuleID'), ('HH3C-IDS-MIB', 'hh3cIDSTrapEngineID'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapDetectRuleParseFail.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapDetectRuleParseFail.setDescription('This notification will be generated when failing to parse the rules for detecting. The hh3cIDSTrapDetectRuleID object describes rule ID. The hh3cIDSTrapEngineID object identifies an interface the rule applies to. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_db_conn_lost = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 4)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapIPAddressType'), ('HH3C-IDS-MIB', 'hh3cIDSTrapIPAddress'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapDBConnLost.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapDBConnLost.setDescription('This notification will be generated when connecting with database server fails. The hh3cIDSTrapIPAddressType object describes the IP address type of database server. The hh3cIDSTrapIPAddress object describes the IP address of database server. The hh3cIDSTrapReasonForError describes reason of connecting failure.')
hh3c_ids_trap_crl_need_update = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 5)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapCRLName'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapCRLNeedUpdate.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapCRLNeedUpdate.setDescription('This notification will be generated when IDS device detects that CRL is out of date. The hh3cIDSTrapCRLName object describes the CRL(Certificate Revoke List) name. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_cert_overdue = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 6)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapCertName'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapCertOverdue.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapCertOverdue.setDescription('This notification will be generated when IDS device detects that certificate is overdue. The hh3cIDSTrapCertName object describes the certificate name. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_too_many_login_fail = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 7)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapUserName'), ('HH3C-IDS-MIB', 'hh3cIDSTrapIPAddressType'), ('HH3C-IDS-MIB', 'hh3cIDSTrapIPAddress'), ('HH3C-IDS-MIB', 'hh3cIDSTrapLoginType'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapTooManyLoginFail.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapTooManyLoginFail.setDescription('This notification will be generated when the login failure times of a user over a certain number. The hh3cIDSTrapUserName object describes the user name when logging in. The hh3cIDSTrapIPAddressType object describes the IP address type of client. The hh3cIDSTrapIPAddress object describes the IP address of client. The hh3cIDSTrapLoginType object describes login type, including: telnet, ssh, web. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_upgrade_error = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 8)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapUpgradeType'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapUpgradeError.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapUpgradeError.setDescription('This notification will be generated when upgrading fails. The hh3cIDSTrapUpgradeType object describes upgrade type, including: programme, vrb. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_file_access_error = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 9)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapFileName'), ('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapFileAccessError.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapFileAccessError.setDescription('This notification will be generated when accessing file fails. The hh3cIDSTrapFileName object describes the name of file accessed. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_cons_arith_mem_low = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 10)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapConsArithMemLow.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapConsArithMemLow.setDescription('This notification will be generated when memory used by constructing the arithmetic to seek content is lacking. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_ssram_oper_fail = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 11)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapSSRAMOperFail.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapSSRAMOperFail.setDescription('This notification will be generated when reading or writing SSRAM of CIE card fails. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_packet_process_disorder = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 12)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapReasonForError'))
if mibBuilder.loadTexts:
hh3cIDSTrapPacketProcessDisorder.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapPacketProcessDisorder.setDescription('This notification will be generated when packets processed is in disorder. The hh3cIDSTrapReasonForError object describes reason for error.')
hh3c_ids_trap_cfg_file_format_error = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 47, 1, 1, 2, 0, 13)).setObjects(('HH3C-IDS-MIB', 'hh3cIDSTrapFileName'), ('HH3C-IDS-MIB', 'hh3cIDSTrapCfgLineInFile'))
if mibBuilder.loadTexts:
hh3cIDSTrapCfgFileFormatError.setStatus('current')
if mibBuilder.loadTexts:
hh3cIDSTrapCfgFileFormatError.setDescription('When devices startup and load the configuration file, if format error is found, this notification will be generated. The hh3cIDSTrapFileName object describes the name of configuration file. The hh3cIDSTrapCfgLineInFile object describes the line number in the file.')
mibBuilder.exportSymbols('HH3C-IDS-MIB', hh3cIDSTrapCertName=hh3cIDSTrapCertName, hh3cIDSTrapUpgradeError=hh3cIDSTrapUpgradeError, hh3cIDSTrapDetectRuleParseFail=hh3cIDSTrapDetectRuleParseFail, hh3cIDSTrapCfgFileFormatError=hh3cIDSTrapCfgFileFormatError, hh3cIDSTrapIPFragmentQueueLen=hh3cIDSTrapIPFragmentQueueLen, hh3cIDSTrapPrefix=hh3cIDSTrapPrefix, hh3cIDSTrapConsArithMemLow=hh3cIDSTrapConsArithMemLow, hh3cIDSTrapCRLNeedUpdate=hh3cIDSTrapCRLNeedUpdate, hh3cIDSTrapStatSessionTabLen=hh3cIDSTrapStatSessionTabLen, hh3cIDSTrapPacketProcessDisorder=hh3cIDSTrapPacketProcessDisorder, hh3cIDSTrapEngineID=hh3cIDSTrapEngineID, hh3cIDSTrapCfgLineInFile=hh3cIDSTrapCfgLineInFile, hh3cIDSTrapIPFragQueueFull=hh3cIDSTrapIPFragQueueFull, hh3cIDSTrapFileName=hh3cIDSTrapFileName, hh3cIDSTrapDBConnLost=hh3cIDSTrapDBConnLost, hh3cIDSTrapFileAccessError=hh3cIDSTrapFileAccessError, hh3cIDSTrapCertOverdue=hh3cIDSTrapCertOverdue, hh3cIDSMib=hh3cIDSMib, hh3cIDSTrapInfo=hh3cIDSTrapInfo, hh3cIDSTrapTooManyLoginFail=hh3cIDSTrapTooManyLoginFail, hh3cIDSTrapCRLName=hh3cIDSTrapCRLName, hh3cIDSTrapIPAddressType=hh3cIDSTrapIPAddressType, hh3cIDSTrapIPAddress=hh3cIDSTrapIPAddress, hh3cIDSTrapLoginType=hh3cIDSTrapLoginType, hh3cIDSTrapUserName=hh3cIDSTrapUserName, hh3cIDSTrapSSRAMOperFail=hh3cIDSTrapSSRAMOperFail, hh3cIds=hh3cIds, hh3cIDSTrap=hh3cIDSTrap, PYSNMP_MODULE_ID=hh3cIDSMib, hh3cIDSTrapGroup=hh3cIDSTrapGroup, hh3cIDSTrapUpgradeType=hh3cIDSTrapUpgradeType, hh3cIDSTrapDetectRuleID=hh3cIDSTrapDetectRuleID, hh3cIDSTrapStatSessTabFull=hh3cIDSTrapStatSessTabFull, hh3cIDSTrapReasonForError=hh3cIDSTrapReasonForError) |
class TrieNode():
def __init__(self, letter=''):
self.children = {}
self.is_word = False
def lookup_letter(self, c):
if c in self.children:
return True, self.children[c].is_word
else:
return False, False
class Trie():
def __init__(self):
self.root = TrieNode()
def add(self, word):
cur = self.root
for letter in word:
if letter not in cur.children:
cur.children[letter] = TrieNode()
cur = cur.children[letter]
cur.is_word = True
def lookup(self, word):
cur = self.root
for letter in word:
if letter not in cur.children:
return []
cur = cur.children[letter]
if cur.is_word:
return cur.index
else:
return []
def build_prefix(dictionary):
trie = Trie()
for word in dictionary:
trie.add(word)
return trie
def find_words(dictionary, board):
result = []
prefix = build_prefix(dictionary)
boggle(board, prefix, result)
return result
def boggle(board, prefix, result):
#print(board, len(board[0]), len(board))
visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))]
for r in range(0, len(board)):
for c in range(0, len(board[0])):
str = []
_boggle(board, visited, prefix.root, result, r, c, str)
def _is_valid(visited, i, j):
if (i < 0) or (i >= len(visited)) or \
(j < 0) or (j >= len(visited[0])) or \
visited[i][j] == True:
return False
return True
def _boggle(board, visited, node, result, row, col, str):
print(node.children)
print(visited)
c = board[row][col]
present, is_word = node.lookup_letter(c)
if present == False:
return
str.append(c)
if is_word == True :
result.append("".join(str))
print(result)
visited[row][col] = True
for i in row-1, row, row+1:
for j in col-1, col, col+1:
if _is_valid(visited, i, j):
_boggle(board, visited, node.children[c], result, i, j, str)
str.pop()
visited[row][col] = False
dictionary = ["geek", "geeks", "boy"]
board = [["g", "b", "o"],
["e", "y", "s"],
["s", "e", "k"]]
res = find_words(dictionary, board)
| class Trienode:
def __init__(self, letter=''):
self.children = {}
self.is_word = False
def lookup_letter(self, c):
if c in self.children:
return (True, self.children[c].is_word)
else:
return (False, False)
class Trie:
def __init__(self):
self.root = trie_node()
def add(self, word):
cur = self.root
for letter in word:
if letter not in cur.children:
cur.children[letter] = trie_node()
cur = cur.children[letter]
cur.is_word = True
def lookup(self, word):
cur = self.root
for letter in word:
if letter not in cur.children:
return []
cur = cur.children[letter]
if cur.is_word:
return cur.index
else:
return []
def build_prefix(dictionary):
trie = trie()
for word in dictionary:
trie.add(word)
return trie
def find_words(dictionary, board):
result = []
prefix = build_prefix(dictionary)
boggle(board, prefix, result)
return result
def boggle(board, prefix, result):
visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))]
for r in range(0, len(board)):
for c in range(0, len(board[0])):
str = []
_boggle(board, visited, prefix.root, result, r, c, str)
def _is_valid(visited, i, j):
if i < 0 or i >= len(visited) or j < 0 or (j >= len(visited[0])) or (visited[i][j] == True):
return False
return True
def _boggle(board, visited, node, result, row, col, str):
print(node.children)
print(visited)
c = board[row][col]
(present, is_word) = node.lookup_letter(c)
if present == False:
return
str.append(c)
if is_word == True:
result.append(''.join(str))
print(result)
visited[row][col] = True
for i in (row - 1, row, row + 1):
for j in (col - 1, col, col + 1):
if _is_valid(visited, i, j):
_boggle(board, visited, node.children[c], result, i, j, str)
str.pop()
visited[row][col] = False
dictionary = ['geek', 'geeks', 'boy']
board = [['g', 'b', 'o'], ['e', 'y', 's'], ['s', 'e', 'k']]
res = find_words(dictionary, board) |
def calcula_fatorial(n):
resultado = 1
for i in range(1, n+1):
resultado = resultado * i
return resultado
def imprime_numeros(n):
imprimir = ""
for i in range(n, 0, -1):
imprimir += "%d . " %(i)
return imprimir[:len(imprimir) - 3]
numero = int(input("Digite um numero: "))
print("Fatorial de: %d" %(numero))
imprime = imprime_numeros(numero)
fatorial = calcula_fatorial(numero)
print("%d! = %s = %d" %(numero, imprime, fatorial))
| def calcula_fatorial(n):
resultado = 1
for i in range(1, n + 1):
resultado = resultado * i
return resultado
def imprime_numeros(n):
imprimir = ''
for i in range(n, 0, -1):
imprimir += '%d . ' % i
return imprimir[:len(imprimir) - 3]
numero = int(input('Digite um numero: '))
print('Fatorial de: %d' % numero)
imprime = imprime_numeros(numero)
fatorial = calcula_fatorial(numero)
print('%d! = %s = %d' % (numero, imprime, fatorial)) |
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
rooms = 0
if not intervals:
return 0
endp = 0
starts = sorted([i[0] for i in intervals])
ends = sorted([i[1] for i in intervals])
for i in range(len(starts)):
if starts[i]>=ends[endp]:
endp+=1
else:
rooms+=1
return rooms | class Solution:
def min_meeting_rooms(self, intervals: List[List[int]]) -> int:
rooms = 0
if not intervals:
return 0
endp = 0
starts = sorted([i[0] for i in intervals])
ends = sorted([i[1] for i in intervals])
for i in range(len(starts)):
if starts[i] >= ends[endp]:
endp += 1
else:
rooms += 1
return rooms |
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
class PointCloudPath:
BASE_DIR = 'ds0'
ANNNOTATION_DIR = 'ann'
DEFAULT_IMAGE_EXT = '.jpg'
POINT_CLOUD_DIR = 'pointcloud'
RELATED_IMAGES_DIR = 'related_images'
KEY_ID_FILE = 'key_id_map.json'
META_FILE = 'meta.json'
SPECIAL_ATTRS = {'description', 'track_id',
'labelerLogin', 'createdAt', 'updatedAt', 'frame'} | class Pointcloudpath:
base_dir = 'ds0'
annnotation_dir = 'ann'
default_image_ext = '.jpg'
point_cloud_dir = 'pointcloud'
related_images_dir = 'related_images'
key_id_file = 'key_id_map.json'
meta_file = 'meta.json'
special_attrs = {'description', 'track_id', 'labelerLogin', 'createdAt', 'updatedAt', 'frame'} |
VIDEO_ELEMENT = 'videoRenderer'
CHANNEL_ELEMENT = 'channelRenderer'
PLAYLIST_ELEMENT = 'playlistRenderer'
SHELF_ELEMENT = 'shelfRenderer'
class ResultMode:
json = 0
dict = 1
class SearchMode:
videos = 'EgIQAQ%3D%3D'
channels = 'EgIQAg%3D%3D'
playlists = 'EgIQAw%3D%3D'
class VideoUploadDateFilter:
lastHour = 'EgQIARAB'
today = 'EgQIAhAB'
thisWeek = 'EgQIAxAB'
thisMonth = 'EgQIBBAB'
thisYear = 'EgQIBRAB'
class VideoDurationFilter:
short = 'EgQQARgB'
long = 'EgQQARgC'
class VideoSortOrder:
relevance = 'CAASAhAB'
uploadDate = 'CAISAhAB'
viewCount = 'CAMSAhAB'
rating = 'CAESAhAB'
| video_element = 'videoRenderer'
channel_element = 'channelRenderer'
playlist_element = 'playlistRenderer'
shelf_element = 'shelfRenderer'
class Resultmode:
json = 0
dict = 1
class Searchmode:
videos = 'EgIQAQ%3D%3D'
channels = 'EgIQAg%3D%3D'
playlists = 'EgIQAw%3D%3D'
class Videouploaddatefilter:
last_hour = 'EgQIARAB'
today = 'EgQIAhAB'
this_week = 'EgQIAxAB'
this_month = 'EgQIBBAB'
this_year = 'EgQIBRAB'
class Videodurationfilter:
short = 'EgQQARgB'
long = 'EgQQARgC'
class Videosortorder:
relevance = 'CAASAhAB'
upload_date = 'CAISAhAB'
view_count = 'CAMSAhAB'
rating = 'CAESAhAB' |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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.
#
''' Write python code for creating the SAS model '''
# model/input layer definition
def write_input_layer(model_name='sas', layer_name='data', channels='-1',
width='-1', height='-1', scale='1.0'):
'''
Generate Python code defining a SAS deep learning input layer
Parameters
----------
model_name : string
Name for deep learning model
layer_name : string
Layer name
channels : string
number of input channels
width : string
image width
height : string
image height
scale : string
scaling factor to apply to raw image pixel data
Returns
-------
string
String representing Python code defining a SAS deep learning input layer
'''
out = [
'def sas_model_gen(s, input_crop_type=None, input_channel_offset=None, input_image_size=None):',
' # quick check for deeplearn actionset',
' actionset_list = s.actionsetinfo().setinfo.actionset.tolist()',
' actionset_list = [item.lower() for item in actionset_list]',
' if "deeplearn" not in actionset_list:s.loadactionset("deeplearn")',
' ',
' # quick error-checking and default setting',
' if (input_crop_type is None):',
' input_crop_type="NONE"',
' else:',
' if (input_crop_type.upper() != "NONE") and (input_crop_type.upper() != "UNIQUE"):',
' raise ValueError("input_crop_type can only be NONE or UNIQUE")',
'',
' if (input_image_size is not None):',
' channels = input_image_size[0]',
' if (len(input_image_size) == 2):',
' height = width = input_image_size[1]',
' elif (len(inputImageSize) == 3):',
' height,width = input_image_size[1:]',
' else:',
' raise ValueError("input_image_size must be a tuple with two or three entries")',
'',
' # instantiate model',
' s.buildModel(model=dict(name=' + repr(model_name) + ',replace=True),type="CNN")',
'',
' # input layer',
' nchannels=' + channels,
' if input_channel_offset is None and nchannels==3:',
' print("INFO: setting channel mean values to ImageNet means")',
' input_channel_offset = [103.939, 116.779, 123.68]',
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict( type="input", nchannels=' + channels + ', width=' + width + ', height=' + height + ',',
' scale = ' + scale + ', randomcrop=input_crop_type, offsets=input_channel_offset))',
' elif input_channel_offset is not None:',
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict( type="input", nchannels=' + channels + ', width=' + width + ', height=' + height + ',',
' scale = ' + scale + ', randomcrop=input_crop_type, offsets=input_channel_offset))',
' else:',
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict( type="input", nchannels=' + channels + ', width=' + width + ', height=' + height + ',',
' scale = ' + scale + ', randomcrop=input_crop_type))'
]
return '\n'.join(out)
# convolution layer definition
def write_convolution_layer(model_name='sas', layer_name='conv', nfilters='-1',
width='3', height='3', stride='1', nobias='False',
activation='identity', dropout='0', src_layer='none',
padding='None'):
'''
Generate Python code defining a SAS deep learning convolution layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
nfilters : string, optional
number of output feature maps
width : string, optional
image width
height : string, optional
image height
stride : string, optional
vertical/horizontal step size in pixels
nobias : string, optional
omit (True) or retain (False) the bias term
activation : string, optional
activation function
dropout : string, optional
dropout factor (0 < dropout < 1.0)
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
'''
out = [
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict(type="convolution", nfilters=' + nfilters + ', width=' + width + ', height=' + height + ',',
' stride=' + stride + ', nobias=' + nobias + ', act=' + repr(
activation) + ', dropout=' + dropout + ', padding=' + padding +'), \n',
' srcLayers=' + src_layer + ')'
]
return '\n'.join(out)
# batch normalization layer definition
def write_batch_norm_layer(model_name='sas', layer_name='bn',
activation='identity', src_layer='none'):
'''
Generate Python code defining a SAS deep learning batch normalization layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
activation : string, optional
activation function
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
'''
out = [
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict( type="batchnorm", act=' + repr(activation) + '),',
' srcLayers=' + src_layer + ')'
]
return '\n'.join(out)
# pooling layer definition
def write_pooling_layer(model_name='sas', layer_name='pool',
width='2', height='2', stride='2', type='max',
dropout='0', src_layer='none', padding='None'):
'''
Generate Python code defining a SAS deep learning pooling layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
width : string, optional
image width
height : string, optional
image height
stride : string, optional
vertical/horizontal step size in pixels
type : string, optional
pooling type
dropout : string, optional
dropout factor (0 < dropout < 1.0)
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
'''
out = [
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict(type="pooling", width=' + width + ', height=' + height + ',',
' stride=' + stride + ', pool=' + repr(type) + ', dropout=' + dropout + ',',
' padding=' + padding + '),',
' srcLayers=' + src_layer + ')'
]
return '\n'.join(out)
# residual layer definition
def write_residual_layer(model_name='sas', layer_name='residual',
activation='identity', src_layer='none'):
'''
Generate Python code defining a SAS deep learning residual layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
activation : string, optional
activation function
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
'''
out = [
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict( type="residual", act="' + activation + '"),',
' srcLayers=' + src_layer + ')'
]
return '\n'.join(out)
# fully connected layer definition
def write_full_connect_layer(model_name='sas', layer_name='fullconnect',
nrof_neurons='-1', nobias='true',
activation='identity', type='fullconnect', dropout='0',
src_layer='none'):
'''
Generate Python code defining a SAS deep learning fully connected layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
nrof_neurons : string, optional
number of output neurons
nobias : string, optional
omit (True) or retain (False) the bias term
activation : string, optional
activation function
type : string, optional
fully connected layer type (fullconnect or output)
dropout : string, optional
dropout factor (0 < dropout < 1.0)
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
'''
if (type == 'fullconnect'):
out = [
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict(type=' + repr(type) + ', n=' + nrof_neurons + ',',
' nobias=' + nobias + ', act=' + repr(activation) + ', dropout=' + dropout + '),',
' srcLayers=' + src_layer + ')'
]
else:
out = [
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict(type=' + repr(type) + ', n=' + nrof_neurons + ',',
' nobias=' + nobias + ', act=' + repr(activation) + '),',
' srcLayers=' + src_layer + ')'
]
return '\n'.join(out)
# concat layer definition
def write_concatenate_layer(model_name='sas', layer_name='concat',
activation='identity', src_layer='none'):
'''
Generate Python code defining a SAS deep learning concat layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
activation : string, optional
activation function
src_layer : string, optional
source layer(s) for the concat layer
Returns
-------
string
'''
out = [
' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',',
' layer=dict( type="concat", act="' + activation + '"),',
' srcLayers=' + src_layer + ')'
]
return '\n'.join(out)
# Python __main__ function
def write_main_entry(model_name):
'''
Generate Python code defining the __main__ Python entry point
Parameters
----------
model_name : string
Name for deep learning model
Returns
-------
string
'''
return ''
| """ Write python code for creating the SAS model """
def write_input_layer(model_name='sas', layer_name='data', channels='-1', width='-1', height='-1', scale='1.0'):
"""
Generate Python code defining a SAS deep learning input layer
Parameters
----------
model_name : string
Name for deep learning model
layer_name : string
Layer name
channels : string
number of input channels
width : string
image width
height : string
image height
scale : string
scaling factor to apply to raw image pixel data
Returns
-------
string
String representing Python code defining a SAS deep learning input layer
"""
out = ['def sas_model_gen(s, input_crop_type=None, input_channel_offset=None, input_image_size=None):', ' # quick check for deeplearn actionset', ' actionset_list = s.actionsetinfo().setinfo.actionset.tolist()', ' actionset_list = [item.lower() for item in actionset_list]', ' if "deeplearn" not in actionset_list:s.loadactionset("deeplearn")', ' ', ' # quick error-checking and default setting', ' if (input_crop_type is None):', ' input_crop_type="NONE"', ' else:', ' if (input_crop_type.upper() != "NONE") and (input_crop_type.upper() != "UNIQUE"):', ' raise ValueError("input_crop_type can only be NONE or UNIQUE")', '', ' if (input_image_size is not None):', ' channels = input_image_size[0]', ' if (len(input_image_size) == 2):', ' height = width = input_image_size[1]', ' elif (len(inputImageSize) == 3):', ' height,width = input_image_size[1:]', ' else:', ' raise ValueError("input_image_size must be a tuple with two or three entries")', '', ' # instantiate model', ' s.buildModel(model=dict(name=' + repr(model_name) + ',replace=True),type="CNN")', '', ' # input layer', ' nchannels=' + channels, ' if input_channel_offset is None and nchannels==3:', ' print("INFO: setting channel mean values to ImageNet means")', ' input_channel_offset = [103.939, 116.779, 123.68]', ' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict( type="input", nchannels=' + channels + ', width=' + width + ', height=' + height + ',', ' scale = ' + scale + ', randomcrop=input_crop_type, offsets=input_channel_offset))', ' elif input_channel_offset is not None:', ' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict( type="input", nchannels=' + channels + ', width=' + width + ', height=' + height + ',', ' scale = ' + scale + ', randomcrop=input_crop_type, offsets=input_channel_offset))', ' else:', ' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict( type="input", nchannels=' + channels + ', width=' + width + ', height=' + height + ',', ' scale = ' + scale + ', randomcrop=input_crop_type))']
return '\n'.join(out)
def write_convolution_layer(model_name='sas', layer_name='conv', nfilters='-1', width='3', height='3', stride='1', nobias='False', activation='identity', dropout='0', src_layer='none', padding='None'):
"""
Generate Python code defining a SAS deep learning convolution layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
nfilters : string, optional
number of output feature maps
width : string, optional
image width
height : string, optional
image height
stride : string, optional
vertical/horizontal step size in pixels
nobias : string, optional
omit (True) or retain (False) the bias term
activation : string, optional
activation function
dropout : string, optional
dropout factor (0 < dropout < 1.0)
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
"""
out = [' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict(type="convolution", nfilters=' + nfilters + ', width=' + width + ', height=' + height + ',', ' stride=' + stride + ', nobias=' + nobias + ', act=' + repr(activation) + ', dropout=' + dropout + ', padding=' + padding + '), \n', ' srcLayers=' + src_layer + ')']
return '\n'.join(out)
def write_batch_norm_layer(model_name='sas', layer_name='bn', activation='identity', src_layer='none'):
"""
Generate Python code defining a SAS deep learning batch normalization layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
activation : string, optional
activation function
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
"""
out = [' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict( type="batchnorm", act=' + repr(activation) + '),', ' srcLayers=' + src_layer + ')']
return '\n'.join(out)
def write_pooling_layer(model_name='sas', layer_name='pool', width='2', height='2', stride='2', type='max', dropout='0', src_layer='none', padding='None'):
"""
Generate Python code defining a SAS deep learning pooling layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
width : string, optional
image width
height : string, optional
image height
stride : string, optional
vertical/horizontal step size in pixels
type : string, optional
pooling type
dropout : string, optional
dropout factor (0 < dropout < 1.0)
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
"""
out = [' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict(type="pooling", width=' + width + ', height=' + height + ',', ' stride=' + stride + ', pool=' + repr(type) + ', dropout=' + dropout + ',', ' padding=' + padding + '),', ' srcLayers=' + src_layer + ')']
return '\n'.join(out)
def write_residual_layer(model_name='sas', layer_name='residual', activation='identity', src_layer='none'):
"""
Generate Python code defining a SAS deep learning residual layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
activation : string, optional
activation function
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
"""
out = [' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict( type="residual", act="' + activation + '"),', ' srcLayers=' + src_layer + ')']
return '\n'.join(out)
def write_full_connect_layer(model_name='sas', layer_name='fullconnect', nrof_neurons='-1', nobias='true', activation='identity', type='fullconnect', dropout='0', src_layer='none'):
"""
Generate Python code defining a SAS deep learning fully connected layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
nrof_neurons : string, optional
number of output neurons
nobias : string, optional
omit (True) or retain (False) the bias term
activation : string, optional
activation function
type : string, optional
fully connected layer type (fullconnect or output)
dropout : string, optional
dropout factor (0 < dropout < 1.0)
src_layer : string, optional
source layer(s) for the convolution layer
Returns
-------
string
"""
if type == 'fullconnect':
out = [' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict(type=' + repr(type) + ', n=' + nrof_neurons + ',', ' nobias=' + nobias + ', act=' + repr(activation) + ', dropout=' + dropout + '),', ' srcLayers=' + src_layer + ')']
else:
out = [' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict(type=' + repr(type) + ', n=' + nrof_neurons + ',', ' nobias=' + nobias + ', act=' + repr(activation) + '),', ' srcLayers=' + src_layer + ')']
return '\n'.join(out)
def write_concatenate_layer(model_name='sas', layer_name='concat', activation='identity', src_layer='none'):
"""
Generate Python code defining a SAS deep learning concat layer
Parameters
----------
model_name : string, optional
Name for deep learning model
layer_name : string, optional
Layer name
activation : string, optional
activation function
src_layer : string, optional
source layer(s) for the concat layer
Returns
-------
string
"""
out = [' s.addLayer(model=' + repr(model_name) + ', name=' + repr(layer_name) + ',', ' layer=dict( type="concat", act="' + activation + '"),', ' srcLayers=' + src_layer + ')']
return '\n'.join(out)
def write_main_entry(model_name):
"""
Generate Python code defining the __main__ Python entry point
Parameters
----------
model_name : string
Name for deep learning model
Returns
-------
string
"""
return '' |
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
DOUBAN_COOKIE = {
"__gads": "ID=2421173a5ca57aed-228b4c29c5c800c1:T=1621494084:RT=1621494084:S=ALNI_MaJlRkH7cibeVPuRhGgoy4NehQdpw",
"__utma": "81379588.766923198.1621432056.1634626277.1634642692.15",
"__utmv": "30149280.23826",
"__utmz": "81379588.1634626277.14.8.utmcsr=cn.bing.com|utmccn=(referral)|utmcmd=referral|utmcct=/",
"__yadk_uid": "mpCqcudA39rNIrjPG2dzOaZVU9YKWwMV",
"_ga": "GA1.2.2128100270.1634613032",
"_ga_RXNMP372GL": "GS1.1.1634613031.1.0.1634613033.58",
"_pk_id.100001.3ac3": "e2d5b8eca75bca93.1621432056.15.1634642691.1634626483.",
"_pk_ref.100001.3ac3": "[\"\",\"\",1634642691,\"https://cn.bing.com/\"]",
"_vwo_uuid_v2": "DF8649AFF718CAD037CCABE9EC9DA0284|35908c2cbe71e8172adb1d18e8eb654d",
"ap_v": "0,6.0",
"bid": "nvSOKb3e_kY",
"ck": "vPPv",
"ct": "y",
"dbcl2": "\"238268017:3kJuTVIhGR8\"",
"douban-fav-remind": "1",
"gr_cs1_816e1a27-0db8-472b-bedd-a0ce47a62b39": "user_id:0",
"gr_cs1_a0853268-d85f-4a95-90d5-70006915ab52": "user_id:1",
"gr_session_id_22c937bbd8ebd703f2d8e9445f7dfd03": "a0853268-d85f-4a95-90d5-70006915ab52",
"gr_session_id_22c937bbd8ebd703f2d8e9445f7dfd03_a0853268-d85f-4a95-90d5-70006915ab52": "true",
"gr_user_id": "322312de-376f-4247-911e-4d511f4f93bd",
"ll": "\"118282\"",
"push_doumail_num": "0",
"push_noty_num": "0",
"viewed": "\"1000647_35541390_1000001_35252459_35378783_1043815_1200840_4913064_26261735_30348068\""
}
| douban_cookie = {'__gads': 'ID=2421173a5ca57aed-228b4c29c5c800c1:T=1621494084:RT=1621494084:S=ALNI_MaJlRkH7cibeVPuRhGgoy4NehQdpw', '__utma': '81379588.766923198.1621432056.1634626277.1634642692.15', '__utmv': '30149280.23826', '__utmz': '81379588.1634626277.14.8.utmcsr=cn.bing.com|utmccn=(referral)|utmcmd=referral|utmcct=/', '__yadk_uid': 'mpCqcudA39rNIrjPG2dzOaZVU9YKWwMV', '_ga': 'GA1.2.2128100270.1634613032', '_ga_RXNMP372GL': 'GS1.1.1634613031.1.0.1634613033.58', '_pk_id.100001.3ac3': 'e2d5b8eca75bca93.1621432056.15.1634642691.1634626483.', '_pk_ref.100001.3ac3': '["","",1634642691,"https://cn.bing.com/"]', '_vwo_uuid_v2': 'DF8649AFF718CAD037CCABE9EC9DA0284|35908c2cbe71e8172adb1d18e8eb654d', 'ap_v': '0,6.0', 'bid': 'nvSOKb3e_kY', 'ck': 'vPPv', 'ct': 'y', 'dbcl2': '"238268017:3kJuTVIhGR8"', 'douban-fav-remind': '1', 'gr_cs1_816e1a27-0db8-472b-bedd-a0ce47a62b39': 'user_id:0', 'gr_cs1_a0853268-d85f-4a95-90d5-70006915ab52': 'user_id:1', 'gr_session_id_22c937bbd8ebd703f2d8e9445f7dfd03': 'a0853268-d85f-4a95-90d5-70006915ab52', 'gr_session_id_22c937bbd8ebd703f2d8e9445f7dfd03_a0853268-d85f-4a95-90d5-70006915ab52': 'true', 'gr_user_id': '322312de-376f-4247-911e-4d511f4f93bd', 'll': '"118282"', 'push_doumail_num': '0', 'push_noty_num': '0', 'viewed': '"1000647_35541390_1000001_35252459_35378783_1043815_1200840_4913064_26261735_30348068"'} |
class Mail:
def __init__(self, prot, *argv):
self.prot = prot(*argv)
def login(self, account, passwd):
self.prot.login(account, passwd)
def send(self, frm, to, subject, content):
self.prot.send(frm, to, subject, content)
def quit(self):
self.prot.quit()
| class Mail:
def __init__(self, prot, *argv):
self.prot = prot(*argv)
def login(self, account, passwd):
self.prot.login(account, passwd)
def send(self, frm, to, subject, content):
self.prot.send(frm, to, subject, content)
def quit(self):
self.prot.quit() |
class BaseError(Exception):
error_id = ""
error_msg = ""
def __repr__(self):
return "<{err_id}>: {err_msg}".format(
err_id=self.error_id,
err_msg=self.error_msg,
)
def render(self):
return dict(
error_id=self.error_id,
error_msg=self.error_msg,
)
class ClientError(BaseError):
error_id = "Third_Party_Dependent_Error"
def __init__(self, error_msg):
self.error_msg = error_msg
class BookNotFound(BaseError):
error_id = "Book_Not_Found"
def __init__(self, error_msg):
self.error_msg = error_msg
class UserNotFound(BaseError):
error_id = "User_Not_Found"
def __init__(self, error_msg):
self.error_msg = error_msg
class RecommendedNotFound(BaseError):
error_id = "Recommended_Not_Found"
def __init__(self, error_msg):
self.error_msg = error_msg
| class Baseerror(Exception):
error_id = ''
error_msg = ''
def __repr__(self):
return '<{err_id}>: {err_msg}'.format(err_id=self.error_id, err_msg=self.error_msg)
def render(self):
return dict(error_id=self.error_id, error_msg=self.error_msg)
class Clienterror(BaseError):
error_id = 'Third_Party_Dependent_Error'
def __init__(self, error_msg):
self.error_msg = error_msg
class Booknotfound(BaseError):
error_id = 'Book_Not_Found'
def __init__(self, error_msg):
self.error_msg = error_msg
class Usernotfound(BaseError):
error_id = 'User_Not_Found'
def __init__(self, error_msg):
self.error_msg = error_msg
class Recommendednotfound(BaseError):
error_id = 'Recommended_Not_Found'
def __init__(self, error_msg):
self.error_msg = error_msg |
TOTAL_BUDGET_AUTHORITY = 8361447130497.72
TOTAL_OBLIGATIONS_INCURRED = 4690484214947.31
WEBSITE_AWARD_BINS = {
"<1M": {"lower": None, "upper": 1000000},
"1M..25M": {"lower": 1000000, "upper": 25000000},
"25M..100M": {"lower": 25000000, "upper": 100000000},
"100M..500M": {"lower": 100000000, "upper": 500000000},
">500M": {"lower": 500000000, "upper": None},
}
DOD_CGAC = "097" # DoD's toptier identifier.
DOD_SUBSUMED_CGAC = ["017", "021", "057"] # Air Force, Army, and Navy are to be reported under DoD.
DOD_ARMED_FORCES_CGAC = [DOD_CGAC] + DOD_SUBSUMED_CGAC # The list of ALL agencies reported under DoD.
DOD_ARMED_FORCES_TAS_CGAC_FREC = [("011", "1137"), ("011", "DE00")] # TAS (CGAC, FREC)s for additional DoD agencies.
DOD_FEDERAL_ACCOUNTS = [
("011", "1081"),
("011", "1082"),
("011", "1085"),
("011", "4116"),
("011", "4121"),
("011", "4122"),
("011", "4174"),
("011", "8238"),
("011", "8242"),
] # Federal Account (AID, MAIN)s that are to be reported under DoD.
# Agencies which should be excluded from dropdowns.
EXCLUDE_CGAC = ["000", "067"]
| total_budget_authority = 8361447130497.72
total_obligations_incurred = 4690484214947.31
website_award_bins = {'<1M': {'lower': None, 'upper': 1000000}, '1M..25M': {'lower': 1000000, 'upper': 25000000}, '25M..100M': {'lower': 25000000, 'upper': 100000000}, '100M..500M': {'lower': 100000000, 'upper': 500000000}, '>500M': {'lower': 500000000, 'upper': None}}
dod_cgac = '097'
dod_subsumed_cgac = ['017', '021', '057']
dod_armed_forces_cgac = [DOD_CGAC] + DOD_SUBSUMED_CGAC
dod_armed_forces_tas_cgac_frec = [('011', '1137'), ('011', 'DE00')]
dod_federal_accounts = [('011', '1081'), ('011', '1082'), ('011', '1085'), ('011', '4116'), ('011', '4121'), ('011', '4122'), ('011', '4174'), ('011', '8238'), ('011', '8242')]
exclude_cgac = ['000', '067'] |
def f():
x: list[list[i32]]
x = [[1, 2, 3]]
y: list[list[str]]
y = [['a', 'b']]
x = y
| def f():
x: list[list[i32]]
x = [[1, 2, 3]]
y: list[list[str]]
y = [['a', 'b']]
x = y |
permissions = {
"on_permissions": {
"all": "0",
"uids": [],
"badges": {
"broadcaster": "1"
},
"forbid": {
"all": "0",
"uids": [],
"badges": {}
}
},
"on_channel": {
"all": "0",
"uids": [],
"badges": {},
"forbid": {
"all": "0",
"uids": [],
"badges": {}
}
},
"on_commadd": {
"all": "0",
"uids": [],
"badges": {
"broadcaster": "1"
},
"forbid": {
"all": "0",
"uids": [],
"badges": {}
}
}
}
| permissions = {'on_permissions': {'all': '0', 'uids': [], 'badges': {'broadcaster': '1'}, 'forbid': {'all': '0', 'uids': [], 'badges': {}}}, 'on_channel': {'all': '0', 'uids': [], 'badges': {}, 'forbid': {'all': '0', 'uids': [], 'badges': {}}}, 'on_commadd': {'all': '0', 'uids': [], 'badges': {'broadcaster': '1'}, 'forbid': {'all': '0', 'uids': [], 'badges': {}}}} |
a = 0
def fun1():
print("fun1: a=", a)
def fun2():
a = 10 # By default, the assignment statement creates variables in the local scope
print("fun2: a=", a)
def fun3():
global a # refer global variable
a = 5
print("fun3: a=", a)
fun1()
fun2()
fun1()
fun3()
fun1()
| a = 0
def fun1():
print('fun1: a=', a)
def fun2():
a = 10
print('fun2: a=', a)
def fun3():
global a
a = 5
print('fun3: a=', a)
fun1()
fun2()
fun1()
fun3()
fun1() |
def reverse_string(string):
reversed_letters = list()
index = 1
for letter in string:
reversed_letters.append(string[ len(string) - index ])
index += 1
return "".join(reversed_letters)
word_input = str(input("Input a word: "))
print(f"INPUT: {word_input}")
print("OUTPUT: %s (%d characters)" % (reverse_string(word_input).upper(), len(word_input))) | def reverse_string(string):
reversed_letters = list()
index = 1
for letter in string:
reversed_letters.append(string[len(string) - index])
index += 1
return ''.join(reversed_letters)
word_input = str(input('Input a word: '))
print(f'INPUT: {word_input}')
print('OUTPUT: %s (%d characters)' % (reverse_string(word_input).upper(), len(word_input))) |
def conta_a(palavra):
c = 0
for letra in palavra:
if letra == 'a':
c += 1
return c
s = 'Insper'
r = s[::-2]
print(r)
| def conta_a(palavra):
c = 0
for letra in palavra:
if letra == 'a':
c += 1
return c
s = 'Insper'
r = s[::-2]
print(r) |
#String functions
myStr = 'Hello world!'
#Capitalize
print(myStr.capitalize())
#Swap case
print(myStr.swapcase())
#Get length
print(len(myStr))
#Replace
print(myStr.replace('world', 'everyone'))
#Count
sub = 'l'
print(myStr.count(sub))
#Startswith
print(myStr.startswith('Hello'))
#Endswith
print(myStr.endswith('Hello'))
#Split to list
print(myStr.split())
#Find
print(myStr.find('world'))
#Index
print(myStr.index('world'))
#Is all alphanumeric?
print(myStr.isalnum())
#Is all alphabetic?
print(myStr.isalpha())
#Is all numeric?
print(myStr.isnumeric()) | my_str = 'Hello world!'
print(myStr.capitalize())
print(myStr.swapcase())
print(len(myStr))
print(myStr.replace('world', 'everyone'))
sub = 'l'
print(myStr.count(sub))
print(myStr.startswith('Hello'))
print(myStr.endswith('Hello'))
print(myStr.split())
print(myStr.find('world'))
print(myStr.index('world'))
print(myStr.isalnum())
print(myStr.isalpha())
print(myStr.isnumeric()) |
#!/usr/bin/env python
DESCRIPTION = "Variant of djb2 hash in use by Nokoyawa ransomware"
# Type can be either 'unsigned_int' (32bit) or 'unsigned_long' (64bit)
TYPE = 'unsigned_int'
# Test must match the exact has of the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
TEST_1 = 3792689168
def hash(data):
generated_hash = 5381
for b in data:
generated_hash = (generated_hash * 33 + (b if b < 0x61 else (b - 0x20))) & 0xFFFFFFFF
return generated_hash
| description = 'Variant of djb2 hash in use by Nokoyawa ransomware'
type = 'unsigned_int'
test_1 = 3792689168
def hash(data):
generated_hash = 5381
for b in data:
generated_hash = generated_hash * 33 + (b if b < 97 else b - 32) & 4294967295
return generated_hash |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Scraper": "00_scraper.ipynb",
"Scraper.get_facebook_posts": "00_scraper.ipynb",
"print_something": "00_scraper.ipynb"}
modules = ["scraper.py"]
doc_url = "https://devacto.github.io/talk_like/"
git_url = "https://github.com/devacto/talk_like/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'Scraper': '00_scraper.ipynb', 'Scraper.get_facebook_posts': '00_scraper.ipynb', 'print_something': '00_scraper.ipynb'}
modules = ['scraper.py']
doc_url = 'https://devacto.github.io/talk_like/'
git_url = 'https://github.com/devacto/talk_like/tree/master/'
def custom_doc_links(name):
return None |
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
FI_A = list()
for row in A:
row = [0 if i else 1 for i in row[::-1]]
FI_A.append(row)
return FI_A
| class Solution:
def flip_and_invert_image(self, A: List[List[int]]) -> List[List[int]]:
fi_a = list()
for row in A:
row = [0 if i else 1 for i in row[::-1]]
FI_A.append(row)
return FI_A |
{{AUTO_GENERATED_NOTICE}}
load("@{{REPO_NAME}}//:rules.bzl", "rescript_compiler")
rescript_compiler(
name = "darwin",
bsc = ":darwin/bsc.exe",
bsb_helper = ":darwin/bsb_helper.exe",
visibility = ["//visibility:public"],
)
rescript_compiler(
name = "linux",
bsc = ":linux/bsc.exe",
bsb_helper = ":linux/bsb_helper.exe",
visibility = ["//visibility:public"],
)
rescript_compiler(
name = "windows",
bsc = ":win32/bsc.exe",
bsb_helper = ":win32/bsb_helper.exe",
visibility = ["//visibility:public"],
) | {{AUTO_GENERATED_NOTICE}}
load('@{{REPO_NAME}}//:rules.bzl', 'rescript_compiler')
rescript_compiler(name='darwin', bsc=':darwin/bsc.exe', bsb_helper=':darwin/bsb_helper.exe', visibility=['//visibility:public'])
rescript_compiler(name='linux', bsc=':linux/bsc.exe', bsb_helper=':linux/bsb_helper.exe', visibility=['//visibility:public'])
rescript_compiler(name='windows', bsc=':win32/bsc.exe', bsb_helper=':win32/bsb_helper.exe', visibility=['//visibility:public']) |
def myFunction():
print('The value of __name__ is ' + __name__)
def main():
myFunction()
if __name__ == '__main__':
main() | def my_function():
print('The value of __name__ is ' + __name__)
def main():
my_function()
if __name__ == '__main__':
main() |
tokens = {
'ID': r'[A-Za-z][A-Za-z_0-9]*',
'FLOATNUM': r'(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)',
'INTNUM': r'[0-9]+',
# Multi-character operators
'==': r'==',
'<=': r'<=',
'>=': r'>=',
'<>': r'<>',
'::': r'::',
}
special_characters = '<>+-*/=(){}[];,.:'
reserved_keywords = {
'if': 'IF',
'then': 'THEN',
'else': 'ELSE',
'while': 'WHILE',
'class': 'CLASS',
'integer': 'INTEGER',
'float': 'FLOAT',
'do': 'DO',
'end': 'END',
'public': 'PUBLIC',
'private': 'PRIVATE',
'or': 'OR',
'and': 'AND',
'not': 'NOT',
'read': 'READ',
'write': 'WRITE',
'return': 'RETURN',
'main': 'MAIN',
'inherits': 'INHERITS',
'local': 'LOCAL',
'void': 'VOID'
}
comments = r'(/\*(.|\n)*?\*/)|(//.*(\n[ \t]*//.*)*)'
whitespace = ' \t'
line_end = r'\n+'
| tokens = {'ID': '[A-Za-z][A-Za-z_0-9]*', 'FLOATNUM': '(([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)', 'INTNUM': '[0-9]+', '==': '==', '<=': '<=', '>=': '>=', '<>': '<>', '::': '::'}
special_characters = '<>+-*/=(){}[];,.:'
reserved_keywords = {'if': 'IF', 'then': 'THEN', 'else': 'ELSE', 'while': 'WHILE', 'class': 'CLASS', 'integer': 'INTEGER', 'float': 'FLOAT', 'do': 'DO', 'end': 'END', 'public': 'PUBLIC', 'private': 'PRIVATE', 'or': 'OR', 'and': 'AND', 'not': 'NOT', 'read': 'READ', 'write': 'WRITE', 'return': 'RETURN', 'main': 'MAIN', 'inherits': 'INHERITS', 'local': 'LOCAL', 'void': 'VOID'}
comments = '(/\\*(.|\\n)*?\\*/)|(//.*(\\n[ \\t]*//.*)*)'
whitespace = ' \t'
line_end = '\\n+' |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.