content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
print_('Voltages') for a in ['CH1','CH2','CH3','AN8','CAP','SEN']: button('Voltage : %s'%a,"get_voltage('%s')"%a,"display_number") print('') #Just to get a newline print('') print_('Passive Elements') button('Capacitance_:',"get_capacitance()","display_number") print('') button('Resistance__:',"get_resistance()","display_number")
print_('Voltages') for a in ['CH1', 'CH2', 'CH3', 'AN8', 'CAP', 'SEN']: button('Voltage : %s' % a, "get_voltage('%s')" % a, 'display_number') print('') print('') print_('Passive Elements') button('Capacitance_:', 'get_capacitance()', 'display_number') print('') button('Resistance__:', 'get_resistance()', 'display_number')
ASCII_BYTE = ' !"#\\$%&\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\~\t' # Directory structure MAIN_TRACE = 'cor1_1' SECOND_TRACE = 'cor1_2' DIFF_TRACE = 'cor2_1' INPUT1 = 'input1' INPUT2 = 'input2' FUNCTYPE = 'functype' HEADER = """ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <intrin.h> #include <windows.h> #include <tchar.h> #include <strsafe.h> #define dbg_printf (void)printf // Macro to help to loading functions #define LOAD_FUNC(h, n) \\ n##_func = (n##_func_t)GetProcAddress(h, #n); \\ if (!n##_func) { \\ dbg_printf("failed to load function " #n "\\n"); \\ exit(1); \\ } // Macro help creating unique nop functions #define NOP(x) \\ int nop##x() { \\ dbg_printf("==> nop%d called, %p\\n", ##x, _ReturnAddress());\\ return (DWORD)x; \\ } HMODULE dlllib; {typedef} """ FUZZME = """ void fuzz_me(char* filename){ {funcdef} {harness} } """ MAIN = """ int main(int argc, char ** argv) { if (argc < 2) { printf("Usage %s: <input file>\\n", argv[0]); printf(" e.g., harness.exe input\\n"); exit(1); } dlllib = LoadLibraryA("%s"); if (dlllib == NULL){ dbg_printf("failed to load library, gle = %d\\n", GetLastError()); exit(1); } char * filename = argv[1]; fuzz_me(filename); return 0; } """ """ LOAD_FUNC(dlllib, avformat_open_input); int ret_avformat_open_input = avformat_open_input_func(&ctx_org, filename, 0, &avformat_open_input_arg3); // zeros: if pointer one page ==> copy original page to that page ==> if error dbg_printf("avformat_open_input: ret = %d\n", ret_avformat_open_input); // @jinho: check crash / progress """ FUNC = """ {print_cid} LOAD_FUNC(dlllib, {funcname}); {ret_statement}{funcname}_func({arguments}); {dbg_printf} """ FUNC_WO = """ {print_cid} {ret_statement}{funcname}_func({arguments}); {dbg_printf} """
ascii_byte = ' !"#\\$%&\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\~\t' main_trace = 'cor1_1' second_trace = 'cor1_2' diff_trace = 'cor2_1' input1 = 'input1' input2 = 'input2' functype = 'functype' header = '\n#include <stdio.h>\n#include <string.h> \n#include <stdlib.h> \n#include <intrin.h>\n#include <windows.h>\n#include <tchar.h>\n#include <strsafe.h>\n\n#define dbg_printf (void)printf\n\n// Macro to help to loading functions\n#define LOAD_FUNC(h, n) \\\n n##_func = (n##_func_t)GetProcAddress(h, #n); \\\n if (!n##_func) { \\\n dbg_printf("failed to load function " #n "\\n"); \\\n exit(1); \\\n } \n\n// Macro help creating unique nop functions\n#define NOP(x) \\\n int nop##x() { \\\n dbg_printf("==> nop%d called, %p\\n", ##x, _ReturnAddress());\\\n return (DWORD)x; \\\n }\n\nHMODULE dlllib;\n\n{typedef}\n\n' fuzzme = '\nvoid fuzz_me(char* filename){\n\n{funcdef}\n\n{harness}\n\n}\n' main = '\nint main(int argc, char ** argv)\n{\n if (argc < 2) {\n printf("Usage %s: <input file>\\n", argv[0]);\n printf(" e.g., harness.exe input\\n");\n exit(1);\n }\n\n dlllib = LoadLibraryA("%s");\n if (dlllib == NULL){\n dbg_printf("failed to load library, gle = %d\\n", GetLastError());\n exit(1);\n }\n\n char * filename = argv[1]; \n fuzz_me(filename); \n return 0;\n}\n' '\n LOAD_FUNC(dlllib, avformat_open_input);\n int ret_avformat_open_input = avformat_open_input_func(&ctx_org, filename, 0, &avformat_open_input_arg3); // zeros: if pointer one page ==> copy original page to that page ==> if error\n dbg_printf("avformat_open_input: ret = %d\n", ret_avformat_open_input); // @jinho: check crash / progress\n' func = ' \n {print_cid} \n LOAD_FUNC(dlllib, {funcname});\n {ret_statement}{funcname}_func({arguments});\n {dbg_printf} ' func_wo = ' \n {print_cid}\n {ret_statement}{funcname}_func({arguments});\n {dbg_printf} '
def main(): total = None serie = input("What's your favorite serie?: ") seasons = int(input("How much seasons have?: ")) number_chap = int(input("How much chapter have?: ")) duration_chap = int(input("How much minuts chapters have?: ")) total = seasons * number_chap * duration_chap / 60 print(f'You has been {total} hours look {serie}') if __name__ == '__main__': main()
def main(): total = None serie = input("What's your favorite serie?: ") seasons = int(input('How much seasons have?: ')) number_chap = int(input('How much chapter have?: ')) duration_chap = int(input('How much minuts chapters have?: ')) total = seasons * number_chap * duration_chap / 60 print(f'You has been {total} hours look {serie}') if __name__ == '__main__': main()
BASE_LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "console": { "format": "{module}: {message}", "datefmt": "%d/%b/%Y %H:%M:%S", "style": "{", }, }, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "console", }, }, "loggers": { "": {"handlers": ["console"], "level": "DEBUG",}, "api": {"handlers": ["console"], "level": "DEBUG", "propagate": False,}, }, }
base_logging = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'console': {'format': '{module}: {message}', 'datefmt': '%d/%b/%Y %H:%M:%S', 'style': '{'}}, 'handlers': {'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'console'}}, 'loggers': {'': {'handlers': ['console'], 'level': 'DEBUG'}, 'api': {'handlers': ['console'], 'level': 'DEBUG', 'propagate': False}}}
newdata = [] with open("requirements.txt") as f: data = f.read() data = data.split("\n") for i in data: if "@" not in i: newdata.append(i) # print(newdata) file = open("requirements.txt", "w") # print("".join(newdata) + "\n") for i in newdata: print(i) file.write(i + "\n")
newdata = [] with open('requirements.txt') as f: data = f.read() data = data.split('\n') for i in data: if '@' not in i: newdata.append(i) file = open('requirements.txt', 'w') for i in newdata: print(i) file.write(i + '\n')
source = r'''#include <cstdio> #include "mylib.h" void do_something_else() { printf("something else\n"); }''' print(source)
source = '#include <cstdio>\n#include "mylib.h"\n\nvoid do_something_else()\n{\n printf("something else\\n");\n}' print(source)
print(' ') print('-------Menghitung laba seorang pengusaha-------') a=100000000 sum=0 b=0 laba=[int(0),int(0),int(a)*.1,int(a)*.1,int(a)*.5,int(a)*.5,int(a)*.5,int(a)*.2] print('') print('Modal seorang pengusaha :',a) print(' ') for i in laba: sum=sum+i b+=1 print('Laba Bulan ke -',b,'Sebesar :',i) print(' ') print('Total laba yang didapat pengusaha :', sum)
print(' ') print('-------Menghitung laba seorang pengusaha-------') a = 100000000 sum = 0 b = 0 laba = [int(0), int(0), int(a) * 0.1, int(a) * 0.1, int(a) * 0.5, int(a) * 0.5, int(a) * 0.5, int(a) * 0.2] print('') print('Modal seorang pengusaha :', a) print(' ') for i in laba: sum = sum + i b += 1 print('Laba Bulan ke -', b, 'Sebesar :', i) print(' ') print('Total laba yang didapat pengusaha :', sum)
#!python3 msn = 0 for x in range(3,1000000) : n = x csn = 0 while n != 1 : if n % 2 == 0 : n = int(n / 2) else : n = n * 3 +1 csn += 1 if csn > msn : msn = csn sn = x print(sn)
msn = 0 for x in range(3, 1000000): n = x csn = 0 while n != 1: if n % 2 == 0: n = int(n / 2) else: n = n * 3 + 1 csn += 1 if csn > msn: msn = csn sn = x print(sn)
def day01_1(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i]) == int(input_data[(i + 1) % len(input_data)]): result += int(input_data[i]) return result def day01_2(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i]) == int(input_data[(i + int(len(input_data) / 2)) % len(input_data)]): result += int(input_data[i]) return result
def day01_1(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i]) == int(input_data[(i + 1) % len(input_data)]): result += int(input_data[i]) return result def day01_2(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i]) == int(input_data[(i + int(len(input_data) / 2)) % len(input_data)]): result += int(input_data[i]) return result
class Solution: def minimumDeleteSum(self, s1, s2): """ :type s1: str :type s2: str :rtype: int """ w1 = len(s1) w2 = len(s2) dp = [[0 for j in range(w2 + 1)] for i in range(w1 + 1)] dp[0][0] = 0 for i in range(1, w2 + 1): dp[0][i] = dp[0][i-1] + ord(s2[i-1]) for j in range(1, w1 + 1): dp[j][0] = dp[j-1][0] + ord(s1[j-1]) for i in range(1, w1 + 1): for j in range(1, w2 + 1): if s1[i-1] == s2[j-1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = min(ord(s1[i-1]) + ord(s2[j-1]) + dp[i-1][j-1], ord(s1[i-1]) + dp[i-1][j], ord(s2[j-1])+dp[i][j-1]) return dp[w1][w2]
class Solution: def minimum_delete_sum(self, s1, s2): """ :type s1: str :type s2: str :rtype: int """ w1 = len(s1) w2 = len(s2) dp = [[0 for j in range(w2 + 1)] for i in range(w1 + 1)] dp[0][0] = 0 for i in range(1, w2 + 1): dp[0][i] = dp[0][i - 1] + ord(s2[i - 1]) for j in range(1, w1 + 1): dp[j][0] = dp[j - 1][0] + ord(s1[j - 1]) for i in range(1, w1 + 1): for j in range(1, w2 + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = min(ord(s1[i - 1]) + ord(s2[j - 1]) + dp[i - 1][j - 1], ord(s1[i - 1]) + dp[i - 1][j], ord(s2[j - 1]) + dp[i][j - 1]) return dp[w1][w2]
class Fuzzy_logical_relationship(object): def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return str(self.lhs) + " -> " + str(self.rhs)
class Fuzzy_Logical_Relationship(object): def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return str(self.lhs) + ' -> ' + str(self.rhs)
random_list = tuple(range(0, 1000)) def just_mean(x): total = 0 for xi in x: total += xi return total / len(x) mean_output = just_mean(random_list)
random_list = tuple(range(0, 1000)) def just_mean(x): total = 0 for xi in x: total += xi return total / len(x) mean_output = just_mean(random_list)
INVALID_INPUT = 1 DOCKER_ERROR = 2 UNKNOWN_ERROR = 3 class DkrException(Exception): def __init__(self, message, exit_code): self.message = message self.exit_code = exit_code
invalid_input = 1 docker_error = 2 unknown_error = 3 class Dkrexception(Exception): def __init__(self, message, exit_code): self.message = message self.exit_code = exit_code
class Action: def __init__(self, unit, target): self.unit = unit self.target = target def complete(self): self.unit.walked = [] self.unit.action = None self.unit._flee_or_fight_if_enemy() def update(self): pass class MoveAction(Action): def update(self): if hasattr(self.target, "other_side"): # move towards the center of the next square self.unit.go_to_xy(self.target.other_side.place.x, self.target.other_side.place.y) elif getattr(self.target, "place", None) is self.unit.place: self.unit.action_reach_and_use() elif self.unit.airground_type == "air": self.unit.go_to_xy(self.target.x, self.target.y) else: self.complete() class MoveXYAction(Action): timer = 15 # 5 seconds # XXXXXXXX not beautiful def update(self): if self.timer > 0: self.timer -= 1 x, y = self.target if self.unit.go_to_xy(x, y): self.complete() else: self.complete() class AttackAction(Action): def update(self): # without moving to another square if self.unit.range and self.target in self.unit.place.objects: self.unit.action_reach_and_use() elif self.unit.can_attack(self.target): self.unit.aim(self.target) else: self.complete()
class Action: def __init__(self, unit, target): self.unit = unit self.target = target def complete(self): self.unit.walked = [] self.unit.action = None self.unit._flee_or_fight_if_enemy() def update(self): pass class Moveaction(Action): def update(self): if hasattr(self.target, 'other_side'): self.unit.go_to_xy(self.target.other_side.place.x, self.target.other_side.place.y) elif getattr(self.target, 'place', None) is self.unit.place: self.unit.action_reach_and_use() elif self.unit.airground_type == 'air': self.unit.go_to_xy(self.target.x, self.target.y) else: self.complete() class Movexyaction(Action): timer = 15 def update(self): if self.timer > 0: self.timer -= 1 (x, y) = self.target if self.unit.go_to_xy(x, y): self.complete() else: self.complete() class Attackaction(Action): def update(self): if self.unit.range and self.target in self.unit.place.objects: self.unit.action_reach_and_use() elif self.unit.can_attack(self.target): self.unit.aim(self.target) else: self.complete()
""" Part 1 Solution: 580 Part 2 Solution: 81972 """ # Basically a Sum function def solve_day1_part1(): fname = "data_day1.txt" frequency = 0 with open(fname) as fp: line = fp.readline().rstrip("\n") while line: i = int(line) frequency += i # print("{} => {} = {}".format(line, i, total)) # print("{}".format(frequency)) line = fp.readline().rstrip("\n") return frequency """ # Notes - Must read the data several times until we find a repeated frequency. - Maybe I should read the data in a list once for performance but what if we have billions of numbers? """ def solve_day1_part2(frequency, frequency_count): fname = "data_day1.txt" # total_count["-17"] = 3 with open(fname) as fp: line = fp.readline().rstrip("\n") while line: i = int(line) frequency += i key = str(frequency) if key not in frequency_count: frequency_count[key] = 1 # print("Adding T={}\n".format(key)) else: print("Dup T={}".format(key)) # print("Frequency table: 1".format(total_count)) return key # print("{} => {} = {}".format(line, i, total)) line = fp.readline().rstrip("\n") # print("Once more") return solve_day1_part2(frequency, frequency_count) total = solve_day1_part1() print("Sum={}".format(total)) # frequency_count = {} first_repeat = solve_day1_part2(0, {}) print("first repeated ={}".format(first_repeat))
""" Part 1 Solution: 580 Part 2 Solution: 81972 """ def solve_day1_part1(): fname = 'data_day1.txt' frequency = 0 with open(fname) as fp: line = fp.readline().rstrip('\n') while line: i = int(line) frequency += i line = fp.readline().rstrip('\n') return frequency '\n# Notes\n- Must read the data several times until we find a repeated frequency.\n- Maybe I should read the data in a list once for performance but what if we have billions of numbers?\n' def solve_day1_part2(frequency, frequency_count): fname = 'data_day1.txt' with open(fname) as fp: line = fp.readline().rstrip('\n') while line: i = int(line) frequency += i key = str(frequency) if key not in frequency_count: frequency_count[key] = 1 else: print('Dup T={}'.format(key)) return key line = fp.readline().rstrip('\n') return solve_day1_part2(frequency, frequency_count) total = solve_day1_part1() print('Sum={}'.format(total)) first_repeat = solve_day1_part2(0, {}) print('first repeated ={}'.format(first_repeat))
a=int(input("enter first number:")) b=int(input("enter second number:")) sum=0 for i in range (a,b+1): sum=sum+i print(sum)
a = int(input('enter first number:')) b = int(input('enter second number:')) sum = 0 for i in range(a, b + 1): sum = sum + i print(sum)
# contains bunch of buggy examples # taken from https://hackernoon.com/10-common-security-gotchas-in-python # -and-how-to-avoid-them-e19fbe265e03 def transcode_file(filename): """Input injection""" command = 'ffmpeg -i "{source}" output_file.mpg'.format(source=filename) return command # a bad idea! def access_function(user): """Assert statements""" assert user.is_admin, 'user does not have access' # secure code... class RunBinSh(): """Pickles""" def __reduce__(self): return
def transcode_file(filename): """Input injection""" command = 'ffmpeg -i "{source}" output_file.mpg'.format(source=filename) return command def access_function(user): """Assert statements""" assert user.is_admin, 'user does not have access' class Runbinsh: """Pickles""" def __reduce__(self): return
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {integer[]} preorder # @param {integer[]} inorder # @return {TreeNode} def buildTree(self, preorder, inorder): if not preorder or not inorder: return None n1,n2 = len(preorder), len(inorder) if n1!=n2 or n1 == 0: return None root = TreeNode(0) st = [root] i = 0 j = 0 last_pop= root while(i < n1): num = preorder[i] node = TreeNode(num) if last_pop != None: last_pop.right = node st.append(node) last_pop = None else: last = st[-1] last.left = node st.append(node) while(j < n1 and st[-1].val == inorder[j]): last_pop = st.pop() j += 1 i+=1 return root.right
class Solution: def build_tree(self, preorder, inorder): if not preorder or not inorder: return None (n1, n2) = (len(preorder), len(inorder)) if n1 != n2 or n1 == 0: return None root = tree_node(0) st = [root] i = 0 j = 0 last_pop = root while i < n1: num = preorder[i] node = tree_node(num) if last_pop != None: last_pop.right = node st.append(node) last_pop = None else: last = st[-1] last.left = node st.append(node) while j < n1 and st[-1].val == inorder[j]: last_pop = st.pop() j += 1 i += 1 return root.right
while 1: a = 1 break print(a) # pass
while 1: a = 1 break print(a)
class Solution: def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ start = self.binarySearch(nums, target) if start == -1: return [-1, -1] end = self.binarySearch(nums, target, True) return [start, end] def binarySearch(self, nums, target, getRight=False): if len(nums) == 0: return -1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = int(start + (end - start) / 2) if nums[mid] == target: if getRight: start = mid else: end = mid elif nums[mid] < target: start = mid + 1 else: end = mid - 1 if getRight: if nums[end] == target: return end elif nums[start] == target: return start else: if nums[start] == target: return start elif nums[end] == target: return end return -1
class Solution: def search_range(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ start = self.binarySearch(nums, target) if start == -1: return [-1, -1] end = self.binarySearch(nums, target, True) return [start, end] def binary_search(self, nums, target, getRight=False): if len(nums) == 0: return -1 (start, end) = (0, len(nums) - 1) while start + 1 < end: mid = int(start + (end - start) / 2) if nums[mid] == target: if getRight: start = mid else: end = mid elif nums[mid] < target: start = mid + 1 else: end = mid - 1 if getRight: if nums[end] == target: return end elif nums[start] == target: return start elif nums[start] == target: return start elif nums[end] == target: return end return -1
# Migration removed because it depends on models which have been removed def run(): return False
def run(): return False
""" Program to determine whether a given number is a Harshad number Harshad number A number is said to be the Harshad number if it is divisible by the sum of its digit. For example, if number is 156, then sum of its digit will be 1 + 5 + 6 = 12. Since 156 is divisible by 12. So, 156 is a Harshad number. Some of the other examples of Harshad number are 8, 54, 120, etc. To find whether the given number is a Harshad number or not, calculate the sum of the digit of the number then, check whether the given number is divisible by the sum of its digit. If yes, then given number is a Harshad number.""" num = int(input("Enter a number: ")); rem = sum = 0; #Make a copy of num and store it in variable n n = num; #Calculates sum of digits while(num > 0): rem = num%10; sum = sum + rem; num = num//10; #Checks whether the number is divisible by the sum of digits if(n%sum == 0): print(str(n) + " is a harshad number"); else: print(str(n) + " is not a harshad number");
""" Program to determine whether a given number is a Harshad number Harshad number A number is said to be the Harshad number if it is divisible by the sum of its digit. For example, if number is 156, then sum of its digit will be 1 + 5 + 6 = 12. Since 156 is divisible by 12. So, 156 is a Harshad number. Some of the other examples of Harshad number are 8, 54, 120, etc. To find whether the given number is a Harshad number or not, calculate the sum of the digit of the number then, check whether the given number is divisible by the sum of its digit. If yes, then given number is a Harshad number.""" num = int(input('Enter a number: ')) rem = sum = 0 n = num while num > 0: rem = num % 10 sum = sum + rem num = num // 10 if n % sum == 0: print(str(n) + ' is a harshad number') else: print(str(n) + ' is not a harshad number')
#-----------------------------------------------------------------# #! Python3 # Author : NK # Month, Year : March, 2019 # Info : Program to get Squares of numbers upto 25, using return # Desc : An example program to show usage of return #-----------------------------------------------------------------# def nextSquare(x): return x*x def main(): for x in range(25): print(nextSquare(x)) if __name__ == '__main__': main()
def next_square(x): return x * x def main(): for x in range(25): print(next_square(x)) if __name__ == '__main__': main()
def get_planet_name(id): tmp = { 1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars", 5: "Jupiter", 6: "Saturn", 7: "Uranus", 8: "Neptune" } return tmp[id]
def get_planet_name(id): tmp = {1: 'Mercury', 2: 'Venus', 3: 'Earth', 4: 'Mars', 5: 'Jupiter', 6: 'Saturn', 7: 'Uranus', 8: 'Neptune'} return tmp[id]
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions = [(val, idx) for idx, val in enumerate(potions)] potions.sort() spells = [(val, idx) for idx, val in enumerate(spells)] spells.sort() left = 0 right = len(potions) - 1 res = [0] * len(spells) while left < len(spells): while right >= 0 and spells[left][0] * potions[right][0] >= success: right -= 1 res[spells[left][1]] = max(res[left], len(potions) - right - 1) left += 1 return res
class Solution: def successful_pairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions = [(val, idx) for (idx, val) in enumerate(potions)] potions.sort() spells = [(val, idx) for (idx, val) in enumerate(spells)] spells.sort() left = 0 right = len(potions) - 1 res = [0] * len(spells) while left < len(spells): while right >= 0 and spells[left][0] * potions[right][0] >= success: right -= 1 res[spells[left][1]] = max(res[left], len(potions) - right - 1) left += 1 return res
# # PySNMP MIB module SONOMASYSTEMS-SONOMA-IPAPPS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-IPAPPS-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:09:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Unsigned32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Gauge32, Counter32, Integer32, IpAddress, iso, Counter64, ObjectIdentity, TimeTicks, MibIdentifier, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Gauge32", "Counter32", "Integer32", "IpAddress", "iso", "Counter64", "ObjectIdentity", "TimeTicks", "MibIdentifier", "NotificationType") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") sonomaApplications, = mibBuilder.importSymbols("SONOMASYSTEMS-SONOMA-MIB", "sonomaApplications") ipApplications = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1)) bootpGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1)) pingGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2)) class DisplayString(OctetString): pass tftpFileServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 1), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tftpFileServerIpAddress.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileServerIpAddress.setDescription('The IP Address of the file server to use for image and parameter file downloads and uploads.') tftpFileName = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tftpFileName.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileName.setDescription('The path and name of the file to be uploaded or downloaded. This string is 128 charachters long, any longer causes problems fro Windown NT or Windows 95. This length is recommended in RFC 1542.') tftpImageNumber = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("image1", 1), ("image2", 2), ("image3", 3), ("image4", 4), ("image5", 5), ("image6", 6), ("image7", 7), ("image8", 8))).clone('image1')).setMaxAccess("readwrite") if mibBuilder.loadTexts: tftpImageNumber.setStatus('mandatory') if mibBuilder.loadTexts: tftpImageNumber.setDescription('The Image number (1 - 8) for the operational image file to be downloaded to. In the case of BOOTP the image will be stored in the BOOTP/ directory in flash') tftpFileAction = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("noAction", 1), ("startBootPImageDownload", 2), ("startTFTPImageDownload", 3), ("startPrimaryImageTFTPDownload", 4), ("startSecondaryImageTFTPDownload", 5), ("startTFTPParameterBinDownload", 6), ("startTFTPParameterTextDownload", 7), ("startTFTPParameterBinUpload", 8), ("startTFTPParameterTextUpload", 9), ("startTFTPProfileDownload", 10))).clone('noAction')).setMaxAccess("readwrite") if mibBuilder.loadTexts: tftpFileAction.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileAction.setDescription("This object is used to initiate file transfer between this unit and the file server identified by tftpFileServerIpAddress. A download indicates that the file transfer is from the file server (down) to the device. An upload indicates a file transfer from the device (up) to the server. This object can be used to initiate either image or parameter file downloads and a parameter file upload. There is no image file upload feature. An image file can be downloaded via either a BootP request (where the image filename and the BootP server's IP Address is unknown) or via a TFTP request where the user has configured the tftpFileName object with the path and name of the file. BootP cannot be used to download or upload a parameter file. An attempt to set this object to one of the following values: startTFTPImageDownload, startTFTPParameterDownload or startTFTPParameterUpload, will fail if either the tftpFileName or tftpFileServerIpAddress object has not bee configured. The tftpFileName and tftpFileServerIpAddress objects are ignored for BootP requests. A value of noAction is always returned to a GetRequest. Seting this object with a value of noAction has no effect. The startPrimaryImageTFTPDownload is used to initiate the download of the primary boot image. This image is only downloaded when there is a new revision of the basic boot mechanism or changes to the flash or CMOS sub-systems.") tftpFileTransferStatus = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18))).clone(namedValues=NamedValues(("idle", 1), ("downloading", 2), ("uploading", 3), ("programmingflash", 4), ("failBootpNoServer", 5), ("failTFTPNoFile", 6), ("errorServerResponse", 7), ("failTFTPInvalidFile", 8), ("failNetworkTimeout", 9), ("failFlashProgError", 10), ("failFlashChksumError", 11), ("errorServerData", 12), ("uploadResultUnknown", 13), ("uploadSuccessful", 14), ("downloadSuccessful", 15), ("generalFailure", 16), ("failCannotOverwriteActiveImage", 17), ("failCannotOverwriteActiveParam", 18)))).setMaxAccess("readonly") if mibBuilder.loadTexts: tftpFileTransferStatus.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileTransferStatus.setDescription('This is the current status of the file transfer process.') pingIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 1), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pingIpAddress.setStatus('mandatory') if mibBuilder.loadTexts: pingIpAddress.setDescription(' The IP Address to Ping') pingTimeout = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pingTimeout.setStatus('mandatory') if mibBuilder.loadTexts: pingTimeout.setDescription('This is the timeout, in seconds, for a ping.') pingRetries = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 3), Integer32().clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: pingRetries.setStatus('mandatory') if mibBuilder.loadTexts: pingRetries.setDescription(' This value indicates the number of times, to ping. A value of 1 is the default and insicates that the unit will send one pingp. 0 means no action.') pingStatus = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("readonly") if mibBuilder.loadTexts: pingStatus.setStatus('mandatory') if mibBuilder.loadTexts: pingStatus.setDescription(' A text string which indicates the result or status of the last ping which the unit sent.') pingAction = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("start", 1), ("stop", 2), ("noAction", 3))).clone('noAction')).setMaxAccess("readwrite") if mibBuilder.loadTexts: pingAction.setStatus('mandatory') if mibBuilder.loadTexts: pingAction.setDescription('Indicates whether to stop or start a ping. This always returns the value noAction to a Get Request.') mibBuilder.exportSymbols("SONOMASYSTEMS-SONOMA-IPAPPS-MIB", tftpFileTransferStatus=tftpFileTransferStatus, tftpImageNumber=tftpImageNumber, pingRetries=pingRetries, pingGroup=pingGroup, ipApplications=ipApplications, tftpFileAction=tftpFileAction, tftpFileServerIpAddress=tftpFileServerIpAddress, pingTimeout=pingTimeout, pingAction=pingAction, pingStatus=pingStatus, pingIpAddress=pingIpAddress, bootpGroup=bootpGroup, DisplayString=DisplayString, tftpFileName=tftpFileName)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (unsigned32, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, gauge32, counter32, integer32, ip_address, iso, counter64, object_identity, time_ticks, mib_identifier, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Gauge32', 'Counter32', 'Integer32', 'IpAddress', 'iso', 'Counter64', 'ObjectIdentity', 'TimeTicks', 'MibIdentifier', 'NotificationType') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (sonoma_applications,) = mibBuilder.importSymbols('SONOMASYSTEMS-SONOMA-MIB', 'sonomaApplications') ip_applications = mib_identifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1)) bootp_group = mib_identifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1)) ping_group = mib_identifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2)) class Displaystring(OctetString): pass tftp_file_server_ip_address = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 1), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: tftpFileServerIpAddress.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileServerIpAddress.setDescription('The IP Address of the file server to use for image and parameter file downloads and uploads.') tftp_file_name = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 127))).setMaxAccess('readwrite') if mibBuilder.loadTexts: tftpFileName.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileName.setDescription('The path and name of the file to be uploaded or downloaded. This string is 128 charachters long, any longer causes problems fro Windown NT or Windows 95. This length is recommended in RFC 1542.') tftp_image_number = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=named_values(('image1', 1), ('image2', 2), ('image3', 3), ('image4', 4), ('image5', 5), ('image6', 6), ('image7', 7), ('image8', 8))).clone('image1')).setMaxAccess('readwrite') if mibBuilder.loadTexts: tftpImageNumber.setStatus('mandatory') if mibBuilder.loadTexts: tftpImageNumber.setDescription('The Image number (1 - 8) for the operational image file to be downloaded to. In the case of BOOTP the image will be stored in the BOOTP/ directory in flash') tftp_file_action = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=named_values(('noAction', 1), ('startBootPImageDownload', 2), ('startTFTPImageDownload', 3), ('startPrimaryImageTFTPDownload', 4), ('startSecondaryImageTFTPDownload', 5), ('startTFTPParameterBinDownload', 6), ('startTFTPParameterTextDownload', 7), ('startTFTPParameterBinUpload', 8), ('startTFTPParameterTextUpload', 9), ('startTFTPProfileDownload', 10))).clone('noAction')).setMaxAccess('readwrite') if mibBuilder.loadTexts: tftpFileAction.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileAction.setDescription("This object is used to initiate file transfer between this unit and the file server identified by tftpFileServerIpAddress. A download indicates that the file transfer is from the file server (down) to the device. An upload indicates a file transfer from the device (up) to the server. This object can be used to initiate either image or parameter file downloads and a parameter file upload. There is no image file upload feature. An image file can be downloaded via either a BootP request (where the image filename and the BootP server's IP Address is unknown) or via a TFTP request where the user has configured the tftpFileName object with the path and name of the file. BootP cannot be used to download or upload a parameter file. An attempt to set this object to one of the following values: startTFTPImageDownload, startTFTPParameterDownload or startTFTPParameterUpload, will fail if either the tftpFileName or tftpFileServerIpAddress object has not bee configured. The tftpFileName and tftpFileServerIpAddress objects are ignored for BootP requests. A value of noAction is always returned to a GetRequest. Seting this object with a value of noAction has no effect. The startPrimaryImageTFTPDownload is used to initiate the download of the primary boot image. This image is only downloaded when there is a new revision of the basic boot mechanism or changes to the flash or CMOS sub-systems.") tftp_file_transfer_status = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18))).clone(namedValues=named_values(('idle', 1), ('downloading', 2), ('uploading', 3), ('programmingflash', 4), ('failBootpNoServer', 5), ('failTFTPNoFile', 6), ('errorServerResponse', 7), ('failTFTPInvalidFile', 8), ('failNetworkTimeout', 9), ('failFlashProgError', 10), ('failFlashChksumError', 11), ('errorServerData', 12), ('uploadResultUnknown', 13), ('uploadSuccessful', 14), ('downloadSuccessful', 15), ('generalFailure', 16), ('failCannotOverwriteActiveImage', 17), ('failCannotOverwriteActiveParam', 18)))).setMaxAccess('readonly') if mibBuilder.loadTexts: tftpFileTransferStatus.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileTransferStatus.setDescription('This is the current status of the file transfer process.') ping_ip_address = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 1), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: pingIpAddress.setStatus('mandatory') if mibBuilder.loadTexts: pingIpAddress.setDescription(' The IP Address to Ping') ping_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: pingTimeout.setStatus('mandatory') if mibBuilder.loadTexts: pingTimeout.setDescription('This is the timeout, in seconds, for a ping.') ping_retries = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 3), integer32().clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: pingRetries.setStatus('mandatory') if mibBuilder.loadTexts: pingRetries.setDescription(' This value indicates the number of times, to ping. A value of 1 is the default and insicates that the unit will send one pingp. 0 means no action.') ping_status = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 256))).setMaxAccess('readonly') if mibBuilder.loadTexts: pingStatus.setStatus('mandatory') if mibBuilder.loadTexts: pingStatus.setDescription(' A text string which indicates the result or status of the last ping which the unit sent.') ping_action = mib_scalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('start', 1), ('stop', 2), ('noAction', 3))).clone('noAction')).setMaxAccess('readwrite') if mibBuilder.loadTexts: pingAction.setStatus('mandatory') if mibBuilder.loadTexts: pingAction.setDescription('Indicates whether to stop or start a ping. This always returns the value noAction to a Get Request.') mibBuilder.exportSymbols('SONOMASYSTEMS-SONOMA-IPAPPS-MIB', tftpFileTransferStatus=tftpFileTransferStatus, tftpImageNumber=tftpImageNumber, pingRetries=pingRetries, pingGroup=pingGroup, ipApplications=ipApplications, tftpFileAction=tftpFileAction, tftpFileServerIpAddress=tftpFileServerIpAddress, pingTimeout=pingTimeout, pingAction=pingAction, pingStatus=pingStatus, pingIpAddress=pingIpAddress, bootpGroup=bootpGroup, DisplayString=DisplayString, tftpFileName=tftpFileName)
#!/usr/bin/env python3 '''Iterate over multiple sequences in parallel using zip() function NOET: zip() stops when the shortest sequence is done ''' # Init days = ['Monday', 'Tuesday', 'Wednesday'] fruits = ['banana', 'orange', 'peach'] drinks = ['coffee', 'tea', 'beer'] desserts = ['tiramisu', 'ice cream', 'pie', 'pudding'] for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts) : print(day, ': drink', drink, '- eat', fruit, '- enjoy', dessert)
"""Iterate over multiple sequences in parallel using zip() function NOET: zip() stops when the shortest sequence is done """ days = ['Monday', 'Tuesday', 'Wednesday'] fruits = ['banana', 'orange', 'peach'] drinks = ['coffee', 'tea', 'beer'] desserts = ['tiramisu', 'ice cream', 'pie', 'pudding'] for (day, fruit, drink, dessert) in zip(days, fruits, drinks, desserts): print(day, ': drink', drink, '- eat', fruit, '- enjoy', dessert)
"""One To Many. ...is used to mark that an instance of a class can be associated with many instances of another class. For example, on a blog engine, an instance of the Article class could be associated with many instances of the Comment class. In this case, we would map the mentioned classes and its relation as follows: """ class Article(Base): __tablename__ = "articles" id = Column(Integer, primary_key=True) comments = relationship("Comment") class Comment(Base): __tablename__ = "comments" id = Column(Integer, primary_key=True) article_id = Column(Integer, ForeignKey("articles.id"))
"""One To Many. ...is used to mark that an instance of a class can be associated with many instances of another class. For example, on a blog engine, an instance of the Article class could be associated with many instances of the Comment class. In this case, we would map the mentioned classes and its relation as follows: """ class Article(Base): __tablename__ = 'articles' id = column(Integer, primary_key=True) comments = relationship('Comment') class Comment(Base): __tablename__ = 'comments' id = column(Integer, primary_key=True) article_id = column(Integer, foreign_key('articles.id'))
name=input("Please input my daughter's name:") while name!="Nina" and name!="Anime": print("I'm sorry, but the name is not valid.") name=input("Please input my daughter's name:") print("Yes."+name+"is my daughter.")
name = input("Please input my daughter's name:") while name != 'Nina' and name != 'Anime': print("I'm sorry, but the name is not valid.") name = input("Please input my daughter's name:") print('Yes.' + name + 'is my daughter.')
cases = [ ('pmt -s 1 -n 20 populations, use seed so same run each time', 'pmt -s 1 -n 20 populations'), ('pmt -s 2 -n 6 populations, use seed so same run each time', 'pmt -s 2 -n 6 -r 3 populations') ]
cases = [('pmt -s 1 -n 20 populations, use seed so same run each time', 'pmt -s 1 -n 20 populations'), ('pmt -s 2 -n 6 populations, use seed so same run each time', 'pmt -s 2 -n 6 -r 3 populations')]
{ "hawq": { "master": "localhost", "standby": "", "port": 5432, "user": "johnsaxon", "password": "test", "database": "postgres" }, "data_config": { "schema": "public", "table": "elec_tiny", "features": [ { "name": "id", "type": "categorical", "cates": [ "2019-01-20", "2019-03-01", "2019-04-20", "2018-09-10", "2018-12-01", "2019-01-01", "2019-02-20", "2019-04-10", "2018-09-20", "2018-10-01", "2019-02-01", "2018-10-20", "2018-11-10", "2018-12-10", "2018-12-20", "2019-01-10", "2019-03-10", "2019-04-01", "2018-10-10", "2018-11-01", "2018-11-20", "2019-02-10", "2019-03-20", "2018-09-01" ] }, { "name": "stat_date", "type": "n", "cates": [] }, { "name": "meter_id", "type": "n", "cates": [] }, { "name": "energy_mean", "type": "n", "cates": [] }, { "name": "energy_max", "type": "n", "cates": [] }, { "name": "energy_min", "type": "n", "cates": [] }, { "name": "energy_sum", "type": "n", "cates": [] }, { "name": "energy_std", "type": "n", "cates": [] }, { "name": "power_mean", "type": "n", "cates": [] }, { "name": "power_max", "type": "n", "cates": [] }, { "name": "power_min", "type": "n", "cates": [] }, { "name": "power_std", "type": "n", "cates": [] }, { "name": "cur_mean", "type": "n", "cates": [] }, { "name": "cur_max", "type": "n", "cates": [] }, { "name": "cur_min", "type": "n", "cates": [] }, { "name": "cur_std", "type": "n", "cates": [] }, { "name": "vol_mean", "type": "n", "cates": [] }, { "name": "vol_max", "type": "n", "cates": [] }, { "name": "vol_min", "type": "n", "cates": [] }, { "name": "vol_std", "type": "n", "cates": [] }, { "name": "x", "type": "n", "cates": [] }, { "name": "avg_h8", "type": "n", "cates": [] }, { "name": "avg_t_8", "type": "n", "cates": [] }, { "name": "avg_ws_h", "type": "n", "cates": [] }, { "name": "avg_wd_h", "type": "n", "cates": [] }, { "name": "max_h8", "type": "n", "cates": [] }, { "name": "max_t_8", "type": "n", "cates": [] }, { "name": "max_ws_h", "type": "n", "cates": [] }, { "name": "min_h8", "type": "n", "cates": [] }, { "name": "min_t_8", "type": "n", "cates": [] }, { "name": "min_ws_h", "type": "n", "cates": [] }, { "name": "avg_irradiance", "type": "n", "cates": [] }, { "name": "max_irradiance", "type": "n", "cates": [] }, { "name": "min_irradiance", "type": "n", "cates": [] } ], "label": { "name": "load", "type": "n", "cates": [] } }, "task": { "type": 1, "algorithm": 1, "warm_start": false, "estimators": 3, "incre": 1, "batch": 1000 } }
{'hawq': {'master': 'localhost', 'standby': '', 'port': 5432, 'user': 'johnsaxon', 'password': 'test', 'database': 'postgres'}, 'data_config': {'schema': 'public', 'table': 'elec_tiny', 'features': [{'name': 'id', 'type': 'categorical', 'cates': ['2019-01-20', '2019-03-01', '2019-04-20', '2018-09-10', '2018-12-01', '2019-01-01', '2019-02-20', '2019-04-10', '2018-09-20', '2018-10-01', '2019-02-01', '2018-10-20', '2018-11-10', '2018-12-10', '2018-12-20', '2019-01-10', '2019-03-10', '2019-04-01', '2018-10-10', '2018-11-01', '2018-11-20', '2019-02-10', '2019-03-20', '2018-09-01']}, {'name': 'stat_date', 'type': 'n', 'cates': []}, {'name': 'meter_id', 'type': 'n', 'cates': []}, {'name': 'energy_mean', 'type': 'n', 'cates': []}, {'name': 'energy_max', 'type': 'n', 'cates': []}, {'name': 'energy_min', 'type': 'n', 'cates': []}, {'name': 'energy_sum', 'type': 'n', 'cates': []}, {'name': 'energy_std', 'type': 'n', 'cates': []}, {'name': 'power_mean', 'type': 'n', 'cates': []}, {'name': 'power_max', 'type': 'n', 'cates': []}, {'name': 'power_min', 'type': 'n', 'cates': []}, {'name': 'power_std', 'type': 'n', 'cates': []}, {'name': 'cur_mean', 'type': 'n', 'cates': []}, {'name': 'cur_max', 'type': 'n', 'cates': []}, {'name': 'cur_min', 'type': 'n', 'cates': []}, {'name': 'cur_std', 'type': 'n', 'cates': []}, {'name': 'vol_mean', 'type': 'n', 'cates': []}, {'name': 'vol_max', 'type': 'n', 'cates': []}, {'name': 'vol_min', 'type': 'n', 'cates': []}, {'name': 'vol_std', 'type': 'n', 'cates': []}, {'name': 'x', 'type': 'n', 'cates': []}, {'name': 'avg_h8', 'type': 'n', 'cates': []}, {'name': 'avg_t_8', 'type': 'n', 'cates': []}, {'name': 'avg_ws_h', 'type': 'n', 'cates': []}, {'name': 'avg_wd_h', 'type': 'n', 'cates': []}, {'name': 'max_h8', 'type': 'n', 'cates': []}, {'name': 'max_t_8', 'type': 'n', 'cates': []}, {'name': 'max_ws_h', 'type': 'n', 'cates': []}, {'name': 'min_h8', 'type': 'n', 'cates': []}, {'name': 'min_t_8', 'type': 'n', 'cates': []}, {'name': 'min_ws_h', 'type': 'n', 'cates': []}, {'name': 'avg_irradiance', 'type': 'n', 'cates': []}, {'name': 'max_irradiance', 'type': 'n', 'cates': []}, {'name': 'min_irradiance', 'type': 'n', 'cates': []}], 'label': {'name': 'load', 'type': 'n', 'cates': []}}, 'task': {'type': 1, 'algorithm': 1, 'warm_start': false, 'estimators': 3, 'incre': 1, 'batch': 1000}}
"""New retry v2 handlers. This package obsoletes the ibm_botocore/retryhandler.py module and contains new retry logic. """
"""New retry v2 handlers. This package obsoletes the ibm_botocore/retryhandler.py module and contains new retry logic. """
""" 38. User-registered management commands The ``manage.py`` utility provides a number of useful commands for managing a Django project. If you want to add a utility command of your own, you can. The user-defined command ``dance`` is defined in the management/commands subdirectory of this test application. It is a simple command that responds with a printed message when invoked. For more details on how to define your own ``manage.py`` commands, look at the ``django.core.management.commands`` directory. This directory contains the definitions for the base Django ``manage.py`` commands. """ __test__ = {'API_TESTS': """ >>> from django.core import management # Invoke a simple user-defined command >>> management.call_command('dance', style="Jive") I don't feel like dancing Jive. # Invoke a command that doesn't exist >>> management.call_command('explode') Traceback (most recent call last): ... CommandError: Unknown command: 'explode' # Invoke a command with default option `style` >>> management.call_command('dance') I don't feel like dancing Rock'n'Roll. """}
""" 38. User-registered management commands The ``manage.py`` utility provides a number of useful commands for managing a Django project. If you want to add a utility command of your own, you can. The user-defined command ``dance`` is defined in the management/commands subdirectory of this test application. It is a simple command that responds with a printed message when invoked. For more details on how to define your own ``manage.py`` commands, look at the ``django.core.management.commands`` directory. This directory contains the definitions for the base Django ``manage.py`` commands. """ __test__ = {'API_TESTS': '\n>>> from django.core import management\n\n# Invoke a simple user-defined command\n>>> management.call_command(\'dance\', style="Jive")\nI don\'t feel like dancing Jive.\n\n# Invoke a command that doesn\'t exist\n>>> management.call_command(\'explode\')\nTraceback (most recent call last):\n...\nCommandError: Unknown command: \'explode\'\n\n# Invoke a command with default option `style`\n>>> management.call_command(\'dance\')\nI don\'t feel like dancing Rock\'n\'Roll.\n\n'}
{ "targets": [{ "target_name": "findGitRepos", "dependencies": [ "vendor/openpa/openpa.gyp:openpa" ], "sources": [ "cpp/src/FindGitRepos.cpp", "cpp/src/Queue.cpp" ], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")", "cpp/includes" ], "defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"], "conditions": [ ["OS=='win'", { "msvs_settings": { "VCCLCompilerTool": { "DisableSpecificWarnings": [ "4506", "4538", "4793" ] }, "VCLinkerTool": { "AdditionalOptions": [ "/ignore:4248" ] }, }, "defines": [ "OPA_HAVE_NT_INTRINSICS=1", "_opa_inline=__inline" ], "conditions": [ ["target_arch=='x64'", { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:X64", ], }, }, { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:x86", ], }, }], ] }], ["OS=='mac'", { "cflags+": ["-fvisibility=hidden"], "xcode_settings": { "GCC_SYMBOLS_PRIVATE_EXTERN": "YES" } }], ["OS=='mac' or OS=='linux'", { "defines": [ "OPA_HAVE_GCC_INTRINSIC_ATOMICS=1", "HAVE_STDDEF_H=1", "HAVE_STDLIB_H=1", "HAVE_UNISTD_H=1" ] }], ["target_arch=='x64' or target_arch=='arm64'", { "defines": [ "OPA_SIZEOF_VOID_P=8" ] }], ["target_arch=='ia32' or target_arch=='armv7'", { "defines": [ "OPA_SIZEOF_VOID_P=4" ] }] ], }] }
{'targets': [{'target_name': 'findGitRepos', 'dependencies': ['vendor/openpa/openpa.gyp:openpa'], 'sources': ['cpp/src/FindGitRepos.cpp', 'cpp/src/Queue.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")', 'cpp/includes'], 'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS'], 'conditions': [["OS=='win'", {'msvs_settings': {'VCCLCompilerTool': {'DisableSpecificWarnings': ['4506', '4538', '4793']}, 'VCLinkerTool': {'AdditionalOptions': ['/ignore:4248']}}, 'defines': ['OPA_HAVE_NT_INTRINSICS=1', '_opa_inline=__inline'], 'conditions': [["target_arch=='x64'", {'VCLibrarianTool': {'AdditionalOptions': ['/MACHINE:X64']}}, {'VCLibrarianTool': {'AdditionalOptions': ['/MACHINE:x86']}}]]}], ["OS=='mac'", {'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES'}}], ["OS=='mac' or OS=='linux'", {'defines': ['OPA_HAVE_GCC_INTRINSIC_ATOMICS=1', 'HAVE_STDDEF_H=1', 'HAVE_STDLIB_H=1', 'HAVE_UNISTD_H=1']}], ["target_arch=='x64' or target_arch=='arm64'", {'defines': ['OPA_SIZEOF_VOID_P=8']}], ["target_arch=='ia32' or target_arch=='armv7'", {'defines': ['OPA_SIZEOF_VOID_P=4']}]]}]}
def define_actions( action ): """ Define the list of actions we are using. Args action: String with the passed action. Could be "all" Returns actions: List of strings of actions Raises ValueError if the action is not included in H3.6M """ actions = ["walking", "eating", "smoking", "discussion", "directions", "greeting", "phoning", "posing", "purchases", "sitting", "sittingdown", "takingphoto", "waiting", "walkingdog", "walkingtogether"] if action in actions: return [action] if action == "all": return actions if action == "all_srnn": return ["walking", "eating", "smoking", "discussion"] raise( ValueError, "Unrecognized action: %d" % action )
def define_actions(action): """ Define the list of actions we are using. Args action: String with the passed action. Could be "all" Returns actions: List of strings of actions Raises ValueError if the action is not included in H3.6M """ actions = ['walking', 'eating', 'smoking', 'discussion', 'directions', 'greeting', 'phoning', 'posing', 'purchases', 'sitting', 'sittingdown', 'takingphoto', 'waiting', 'walkingdog', 'walkingtogether'] if action in actions: return [action] if action == 'all': return actions if action == 'all_srnn': return ['walking', 'eating', 'smoking', 'discussion'] raise (ValueError, 'Unrecognized action: %d' % action)
# Withdrawal Request amount must be non-negative non_negative_amount = \ """ ALTER TABLE ledger_withdrawalrequest DROP CONSTRAINT IF EXISTS non_negative_amount; ALTER TABLE ledger_withdrawalrequest ADD CONSTRAINT non_negative_amount CHECK ("amount" >= 0); ALTER TABLE ledger_withdrawalrequest VALIDATE CONSTRAINT non_negative_amount; """
non_negative_amount = '\nALTER TABLE ledger_withdrawalrequest DROP CONSTRAINT IF EXISTS non_negative_amount;\nALTER TABLE ledger_withdrawalrequest ADD CONSTRAINT non_negative_amount CHECK ("amount" >= 0);\nALTER TABLE ledger_withdrawalrequest VALIDATE CONSTRAINT non_negative_amount;\n'
# Using hash table # Time Complexity: O(n) class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: checkDict =dict() final = list() for i in nums1: if i not in checkDict: checkDict[i] = 1 else: checkDict[i] += 1 for i in nums2: if i in checkDict: if checkDict[i] > 0: final.append(i) checkDict[i] -= 1 return final # Time Complexity: O(m + n) def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: final = list() if len(nums1) < len(nums2): sl = nums1 ll = nums2 else: sl = nums2 ll = nums1 for i in range(len(sl)): new = sl[i] if new in ll: ll.remove(new) final.append(new) return final # Using sorted list # Time Complexity: O(n*logn) def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: i, j = 0, 0 intersection = list() nums1.sort() nums2.sort() # Handle empty array if len(nums1) == 0: return intersection while i < len(nums1) and j < len(nums2): if nums1[i] == nums2[j]: # Check for unique elements if nums1[i] != nums1[i-1] or i == 0: intersection.append(nums1[i]) i += 1 j += 1 elif nums1[i] < nums2[j]: i += 1 else: j += 1 return intersection
class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: check_dict = dict() final = list() for i in nums1: if i not in checkDict: checkDict[i] = 1 else: checkDict[i] += 1 for i in nums2: if i in checkDict: if checkDict[i] > 0: final.append(i) checkDict[i] -= 1 return final def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: final = list() if len(nums1) < len(nums2): sl = nums1 ll = nums2 else: sl = nums2 ll = nums1 for i in range(len(sl)): new = sl[i] if new in ll: ll.remove(new) final.append(new) return final def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: (i, j) = (0, 0) intersection = list() nums1.sort() nums2.sort() if len(nums1) == 0: return intersection while i < len(nums1) and j < len(nums2): if nums1[i] == nums2[j]: if nums1[i] != nums1[i - 1] or i == 0: intersection.append(nums1[i]) i += 1 j += 1 elif nums1[i] < nums2[j]: i += 1 else: j += 1 return intersection
# using factorial, reduced the time complexity # of program from O(2^N) to O(N) def factorial(n): if n < 2: return 1 else: return n * factorial(n - 1) def computeCoefficient(col, row): return factorial(row) // (factorial(col) * factorial(row - col)) # Recusrive method to create the series def computePascal(col, row): if col == row or col == 0: return 1 else: return computeCoefficient(col, row) # Method to create the triangle for `N` row def printTriangle(num): for r in range(num): for c in range(r + 1): print(str(computePascal(c, r)), end=" ") print("\n") printTriangle(10) """ Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 """
def factorial(n): if n < 2: return 1 else: return n * factorial(n - 1) def compute_coefficient(col, row): return factorial(row) // (factorial(col) * factorial(row - col)) def compute_pascal(col, row): if col == row or col == 0: return 1 else: return compute_coefficient(col, row) def print_triangle(num): for r in range(num): for c in range(r + 1): print(str(compute_pascal(c, r)), end=' ') print('\n') print_triangle(10) '\nOutput:\n1 \n\n1 1 \n\n1 2 1 \n\n1 3 3 1 \n\n1 4 6 4 1 \n\n1 5 10 10 5 1 \n\n1 6 15 20 15 6 1 \n\n1 7 21 35 35 21 7 1 \n\n1 8 28 56 70 56 28 8 1 \n\n1 9 36 84 126 126 84 36 9 1 \n'
#!/usr/bin/env python # -*- coding: utf-8 -*- class Names(): Chemical_Elemnts = ["Yb", "Pb", "Ca", "Ti", "Mo", "Sn", "Cd", "Ag", "La", "Cs", "W", "Sb", "Ta", "V", "Fe", "Bi", "Ce", "Nb", "Cu", "I", "B", "Te", "Al", "Zr", "Gd", "Na", "Ga", "Cl", "S", "Si", "O", "F", "Mn", "Ba", "K", "Zn", "N", "Li", "Ge", "Y", "Sr", "P", "Mg", "Er", "As"] ''' Chemical_Compounds = ['Ag2O', 'Al2O3', 'As2O3', 'As2O5', 'B2O3', 'BaO', 'Bi2O3', 'CaO', 'CdO', 'Ce2O3', 'CeO2', 'Cl', 'Cs2O', 'Cu2O', 'CuO', 'Er2O3', 'F', 'Fe2O3', 'Fe3O4', 'FeO', 'Ga2O3', 'Gd2O3', 'GeO', 'GeO2', 'I', 'K2O', 'La2O3', 'Li2O', 'MgO', 'Mn2O3', 'Mn2O7', 'Mn3O4', 'MnO', 'MnO2', 'Mo2O3', 'Mo2O5', 'MoO', 'MoO2', 'MoO3', 'N', 'N2O5', 'NO2', 'Na2O', 'Nb2O3', 'Nb2O5', 'P2O3', 'P2O5', 'Pb3O4', 'PbO', 'PbO2', 'SO2', 'SO3', 'Sb2O3', 'Sb2O5', 'SbO2', 'SiO', 'SiO2', 'Sn2O3', 'SnO', 'SnO2', 'SrO', 'Ta2O3', 'Ta2O5', 'TeO2', 'TeO3', 'Ti2O3', 'TiO', 'TiO2', 'V2O3', 'V2O5', 'VO2', 'VO6', 'WO3', 'Y2O3', 'Yb2O3', 'ZnO', 'ZrO2'] ''' Chemical_Compounds = ['Ag2O', 'Al2O3', 'As2O3', 'As2O5', 'B2O3', 'BaO', 'Bi2O3', 'CaO', 'CdO', 'Ce2O3', 'CeO2', 'Cl', 'Cs2O', 'Cu2O', 'CuO', 'Er2O3', 'F', 'Fe2O3', 'Fe3O4', 'FeO', 'Ga2O3', 'Gd2O3', 'GeO2', 'I', 'K2O', 'La2O3', 'Li2O', 'MgO', 'Mn2O3', 'Mn2O7', 'Mn3O4', 'MnO', 'MnO2', 'Mo2O3', 'Mo2O5', 'MoO', 'MoO2', 'MoO3', 'N', 'N2O5', 'NO2', 'Na2O', 'Nb2O3', 'Nb2O5', 'P2O3', 'P2O5', 'Pb3O4', 'PbO', 'PbO2', 'SO2', 'SO3', 'Sb2O3', 'Sb2O5', 'SbO2', 'SiO2', 'Sn2O3', 'SnO', 'SnO2', 'SrO', 'Ta2O3', 'Ta2O5', 'TeO3', 'Ti2O3', 'TiO', 'TiO2', 'V2O3', 'V2O5', 'VO2', 'VO6', 'WO3', 'Y2O3', 'Yb2O3', 'ZnO', 'ZrO2']
class Names: chemical__elemnts = ['Yb', 'Pb', 'Ca', 'Ti', 'Mo', 'Sn', 'Cd', 'Ag', 'La', 'Cs', 'W', 'Sb', 'Ta', 'V', 'Fe', 'Bi', 'Ce', 'Nb', 'Cu', 'I', 'B', 'Te', 'Al', 'Zr', 'Gd', 'Na', 'Ga', 'Cl', 'S', 'Si', 'O', 'F', 'Mn', 'Ba', 'K', 'Zn', 'N', 'Li', 'Ge', 'Y', 'Sr', 'P', 'Mg', 'Er', 'As'] "\n Chemical_Compounds = ['Ag2O', 'Al2O3', 'As2O3', 'As2O5', 'B2O3', 'BaO',\n 'Bi2O3', 'CaO', 'CdO', 'Ce2O3', 'CeO2', 'Cl', 'Cs2O',\n 'Cu2O', 'CuO', 'Er2O3', 'F', 'Fe2O3', 'Fe3O4', 'FeO',\n 'Ga2O3', 'Gd2O3', 'GeO', 'GeO2', 'I', 'K2O', 'La2O3',\n 'Li2O', 'MgO', 'Mn2O3', 'Mn2O7', 'Mn3O4', 'MnO',\n 'MnO2', 'Mo2O3', 'Mo2O5', 'MoO', 'MoO2', 'MoO3',\n 'N', 'N2O5', 'NO2', 'Na2O', 'Nb2O3', 'Nb2O5',\n 'P2O3', 'P2O5', 'Pb3O4', 'PbO', 'PbO2', 'SO2',\n 'SO3', 'Sb2O3', 'Sb2O5', 'SbO2', 'SiO', 'SiO2',\n 'Sn2O3', 'SnO', 'SnO2', 'SrO', 'Ta2O3', 'Ta2O5',\n 'TeO2', 'TeO3', 'Ti2O3', 'TiO', 'TiO2', 'V2O3',\n 'V2O5', 'VO2', 'VO6', 'WO3', 'Y2O3', 'Yb2O3', 'ZnO',\n 'ZrO2']\n " chemical__compounds = ['Ag2O', 'Al2O3', 'As2O3', 'As2O5', 'B2O3', 'BaO', 'Bi2O3', 'CaO', 'CdO', 'Ce2O3', 'CeO2', 'Cl', 'Cs2O', 'Cu2O', 'CuO', 'Er2O3', 'F', 'Fe2O3', 'Fe3O4', 'FeO', 'Ga2O3', 'Gd2O3', 'GeO2', 'I', 'K2O', 'La2O3', 'Li2O', 'MgO', 'Mn2O3', 'Mn2O7', 'Mn3O4', 'MnO', 'MnO2', 'Mo2O3', 'Mo2O5', 'MoO', 'MoO2', 'MoO3', 'N', 'N2O5', 'NO2', 'Na2O', 'Nb2O3', 'Nb2O5', 'P2O3', 'P2O5', 'Pb3O4', 'PbO', 'PbO2', 'SO2', 'SO3', 'Sb2O3', 'Sb2O5', 'SbO2', 'SiO2', 'Sn2O3', 'SnO', 'SnO2', 'SrO', 'Ta2O3', 'Ta2O5', 'TeO3', 'Ti2O3', 'TiO', 'TiO2', 'V2O3', 'V2O5', 'VO2', 'VO6', 'WO3', 'Y2O3', 'Yb2O3', 'ZnO', 'ZrO2']
# Build a Boolean mask to filter out all the 'LAX' departure flights: mask mask = df['Destination Airport'] == 'LAX' # Use the mask to subset the data: la la = df[mask] # Combine two columns of data to create a datetime series: times_tz_none times_tz_none = pd.to_datetime( la['Date (MM/DD/YYYY)'] + ' ' + la['Wheels-off Time'] ) # Localize the time to US/Central: times_tz_central times_tz_central = times_tz_none.dt.tz_localize('US/Central') # Convert the datetimes from US/Central to US/Pacific times_tz_pacific = times_tz_central.dt.tz_convert('US/Pacific')
mask = df['Destination Airport'] == 'LAX' la = df[mask] times_tz_none = pd.to_datetime(la['Date (MM/DD/YYYY)'] + ' ' + la['Wheels-off Time']) times_tz_central = times_tz_none.dt.tz_localize('US/Central') times_tz_pacific = times_tz_central.dt.tz_convert('US/Pacific')
""" Write a Python program to find the second most repeated word in a given string. """ def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 counts_x = sorted(counts.items(), key=lambda kv:kv) return counts_x[-2] print(word_count("both of these by issues fixed by postponding of of annotations."))
""" Write a Python program to find the second most repeated word in a given string. """ def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 counts_x = sorted(counts.items(), key=lambda kv: kv) return counts_x[-2] print(word_count('both of these by issues fixed by postponding of of annotations.'))
# -*- coding: utf-8 -*- """ Created on Sat Jan 19 10:52:04 2019 @author: Nihar """ marks=int(input("Enter Marks: ")) if marks >=70: print("Congrats!Distinction for you") elif 70 > marks >= 60: print("Well done! First Class !!") elif 60 > marks >= 40: print("You got Second Class") else: print("Sorry! You failed!")
""" Created on Sat Jan 19 10:52:04 2019 @author: Nihar """ marks = int(input('Enter Marks: ')) if marks >= 70: print('Congrats!Distinction for you') elif 70 > marks >= 60: print('Well done! First Class !!') elif 60 > marks >= 40: print('You got Second Class') else: print('Sorry! You failed!')
''' Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. ''' class Solution(object): def findNumberOfLIS(self, nums): length = [1]*len(nums) count = [1]*len(nums) result = 0 for end, num in enumerate(nums): for start in range(end): if num > nums[start]: if length[start] >= length[end]: length[end] = 1+length[start] count[end] = count[start] elif length[start] + 1 == length[end]: count[end] += count[start] for index, max_subs in enumerate(count): if length[index] == max(length): result += max_subs return result
""" Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. """ class Solution(object): def find_number_of_lis(self, nums): length = [1] * len(nums) count = [1] * len(nums) result = 0 for (end, num) in enumerate(nums): for start in range(end): if num > nums[start]: if length[start] >= length[end]: length[end] = 1 + length[start] count[end] = count[start] elif length[start] + 1 == length[end]: count[end] += count[start] for (index, max_subs) in enumerate(count): if length[index] == max(length): result += max_subs return result
# python3 def solve(n, v): #if sum(v) % 3 != 0: # return False res = [] values = [] s = sum(v)//3 for i in range(2**n): bit = [0 for i in range(n)] k = i p = n-1 while k!=0: bit[p] = (k%2) k = k//2 p -= 1 #print(bit) val = [a*b for a, b in zip(v, bit)] #print(val) if sum(val) == s: res.append(bit) values.append(i) #print(res) #print(values) if len(res)<3: return False for i in range(len(values)-2): for j in range(i+1, len(values)-1): for k in range(i+2, len(values)): a = values[i] b = values[j] c = values[k] if a^b^c == (2**n-1): return True return False if __name__ == '__main__': n = int(input()) v = [int(i) for i in input().split()] if solve(n, v): print("1") else: print("0")
def solve(n, v): res = [] values = [] s = sum(v) // 3 for i in range(2 ** n): bit = [0 for i in range(n)] k = i p = n - 1 while k != 0: bit[p] = k % 2 k = k // 2 p -= 1 val = [a * b for (a, b) in zip(v, bit)] if sum(val) == s: res.append(bit) values.append(i) if len(res) < 3: return False for i in range(len(values) - 2): for j in range(i + 1, len(values) - 1): for k in range(i + 2, len(values)): a = values[i] b = values[j] c = values[k] if a ^ b ^ c == 2 ** n - 1: return True return False if __name__ == '__main__': n = int(input()) v = [int(i) for i in input().split()] if solve(n, v): print('1') else: print('0')
# create string and dictionary lines = "" occurrences = {} # prompt for lines line = input("Enter line: ") while line: lines += line + " " line = input("Enter line: ") # iterate through each color and store count for word in set(lines.split()): occurrences[word] = lines.split().count(word) # print results for word in sorted(occurrences): print(word, occurrences[word])
lines = '' occurrences = {} line = input('Enter line: ') while line: lines += line + ' ' line = input('Enter line: ') for word in set(lines.split()): occurrences[word] = lines.split().count(word) for word in sorted(occurrences): print(word, occurrences[word])
""" Demonstrates swapping the values of two variables """ number1 = 65 #Declares a variable named number1 and assigns it the value 65 number2 = 27 #Declares a variable named number2 and assigns it the value 27 temp_number = number1 #Copies the reference of number1 to temp_number number1 = number2 #Copies the reference of number2 to number1 number2 = temp_number #Copies the reference of temp_number to number2 print(number1) #Prints the value referenced by number1 print(number2) #Prints the value referenced by number2
""" Demonstrates swapping the values of two variables """ number1 = 65 number2 = 27 temp_number = number1 number1 = number2 number2 = temp_number print(number1) print(number2)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root is None: return '[]' queue = [root] index = 0 while index < len(queue): node = queue[index] if node is not None: queue.append(node.left) queue.append(node.right) index += 1 while (len(queue) > 0 and queue[-1] is None): queue.pop() nodes = ['#' if n is None else str(n.val) for n in queue] return '[%s]' % (','.join(nodes)) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '[]': return None nodes = data[1: -1].split(',') root = TreeNode(int(nodes[0])) queue = [root] isLeft = True for i in range(1, len(nodes)): if nodes[i] != '#': child = TreeNode(int(nodes[i])) if isLeft: queue[0].left = child else: queue[0].right = child queue.append(child) if not isLeft: queue.pop(0) isLeft = not isLeft return root # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root is None: return '[]' queue = [root] index = 0 while index < len(queue): node = queue[index] if node is not None: queue.append(node.left) queue.append(node.right) index += 1 while len(queue) > 0 and queue[-1] is None: queue.pop() nodes = ['#' if n is None else str(n.val) for n in queue] return '[%s]' % ','.join(nodes) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '[]': return None nodes = data[1:-1].split(',') root = tree_node(int(nodes[0])) queue = [root] is_left = True for i in range(1, len(nodes)): if nodes[i] != '#': child = tree_node(int(nodes[i])) if isLeft: queue[0].left = child else: queue[0].right = child queue.append(child) if not isLeft: queue.pop(0) is_left = not isLeft return root
# python3 n, m = map(int, input().split()) clauses = [ list(map(int, input().split())) for i in range(m) ] # This solution tries all possible 2^n variable assignments. # It is too slow to pass the problem. # Implement a more efficient algorithm here. def isSatisfiable(): for mask in range(1<<n): result = [ (mask >> i) & 1 for i in range(n) ] formulaIsSatisfied = True for clause in clauses: clauseIsSatisfied = False if result[abs(clause[0]) - 1] == (clause[0] < 0): clauseIsSatisfied = True if result[abs(clause[1]) - 1] == (clause[1] < 0): clauseIsSatisfied = True if not clauseIsSatisfied: formulaIsSatisfied = False break if formulaIsSatisfied: return result return None result = isSatisfiable() if result is None: print("UNSATISFIABLE") else: print("SATISFIABLE"); print(" ".join(str(-i-1 if result[i] else i+1) for i in range(n)))
(n, m) = map(int, input().split()) clauses = [list(map(int, input().split())) for i in range(m)] def is_satisfiable(): for mask in range(1 << n): result = [mask >> i & 1 for i in range(n)] formula_is_satisfied = True for clause in clauses: clause_is_satisfied = False if result[abs(clause[0]) - 1] == (clause[0] < 0): clause_is_satisfied = True if result[abs(clause[1]) - 1] == (clause[1] < 0): clause_is_satisfied = True if not clauseIsSatisfied: formula_is_satisfied = False break if formulaIsSatisfied: return result return None result = is_satisfiable() if result is None: print('UNSATISFIABLE') else: print('SATISFIABLE') print(' '.join((str(-i - 1 if result[i] else i + 1) for i in range(n))))
""" sentence span mapping to special concepts in amr like name,date-entity,etc. """ class Span(object): def __init__(self,start,end,words,entity_tag): self.start = start self.end = end self.entity_tag = entity_tag self.words = words def set_entity_tag(self,entity_tag): self.entity_tag = entity_tag def __str__(self): return '%s: start: %s, end: %s , tag:%s'%(self.__class__.__name__,self.start,self.end,self.entity_tag) def __repr__(self): return '%s: start: %s, end: %s , tag:%s'%(self.__class__.__name__,self.start,self.end,self.entity_tag) def __eq__(self,other): return other.start == self.start and other.end == self.end def contains(self,other_span): if other_span.start >= self.start and other_span.end <= self.end and not (other_span.start == self.start and other_span.end == self.end): return True else: return False
""" sentence span mapping to special concepts in amr like name,date-entity,etc. """ class Span(object): def __init__(self, start, end, words, entity_tag): self.start = start self.end = end self.entity_tag = entity_tag self.words = words def set_entity_tag(self, entity_tag): self.entity_tag = entity_tag def __str__(self): return '%s: start: %s, end: %s , tag:%s' % (self.__class__.__name__, self.start, self.end, self.entity_tag) def __repr__(self): return '%s: start: %s, end: %s , tag:%s' % (self.__class__.__name__, self.start, self.end, self.entity_tag) def __eq__(self, other): return other.start == self.start and other.end == self.end def contains(self, other_span): if other_span.start >= self.start and other_span.end <= self.end and (not (other_span.start == self.start and other_span.end == self.end)): return True else: return False
class FlPosition: def __init__(self, position_data, column_labels, timestamps, conversion): self.position_data = position_data self.column_labels = column_labels self.timestamps = timestamps self.conversion = conversion
class Flposition: def __init__(self, position_data, column_labels, timestamps, conversion): self.position_data = position_data self.column_labels = column_labels self.timestamps = timestamps self.conversion = conversion
class Recipe: def __init__(self, name, ingredients, yt_link): self.name = name self.ingredients = ingredients self.yt_link = yt_link self.similarity = 0 self.leftChild = None self.rightChild = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, recipe): if not self.root: self.root = recipe else: self.insertNode(recipe, self.root) def insertNode(self, recipe, node): if recipe.similarity < node.similarity: if node.leftChild: self.insertNode(recipe, node.leftChild) else: node.leftChild = recipe else: if node.rightChild: self.insertNode(recipe, node.rightChild) else: node.rightChild = recipe
class Recipe: def __init__(self, name, ingredients, yt_link): self.name = name self.ingredients = ingredients self.yt_link = yt_link self.similarity = 0 self.leftChild = None self.rightChild = None class Binarysearchtree: def __init__(self): self.root = None def insert(self, recipe): if not self.root: self.root = recipe else: self.insertNode(recipe, self.root) def insert_node(self, recipe, node): if recipe.similarity < node.similarity: if node.leftChild: self.insertNode(recipe, node.leftChild) else: node.leftChild = recipe elif node.rightChild: self.insertNode(recipe, node.rightChild) else: node.rightChild = recipe
######################################################################## # Useful classes for implementing quantum heterostructures behavior # # author: Thiago Melo # # creation: 2018-11-09 # # update: 2018-11-09 # class Device(object): def __init__(self): pass
class Device(object): def __init__(self): pass
def deco(func): def temp(): print("-"*60) func() print("-"*60) return temp @deco def print_h1(): print("body") def main(): print_h1() if __name__ == "__main__": main()
def deco(func): def temp(): print('-' * 60) func() print('-' * 60) return temp @deco def print_h1(): print('body') def main(): print_h1() if __name__ == '__main__': main()
# linear search on sorted list def search(L, e): for i in range(len(L)): if L[i] == e: return True if L[i] > e: # sorted return False return False # O(n) for the loop and O(1) for the lookup to test if e == L[i] # overall complexity is O(n) where n is len(L)
def search(L, e): for i in range(len(L)): if L[i] == e: return True if L[i] > e: return False return False
def CheckPypi(auth, project): projectInfo = auth.GetJson("https://pypi.org/pypi/" + project + "/json") return projectInfo["info"]["version"]
def check_pypi(auth, project): project_info = auth.GetJson('https://pypi.org/pypi/' + project + '/json') return projectInfo['info']['version']
# Exercise 3: # # In this exercise we will create a program that identifies whether someone can # enter a super secret club. # Below are the people that are allowed in the club. # If your name is Bill Gates, Steve Jobs or Jesus, you should be allowed in the # club. # If your name is not one of the above, but your name is Maria and you are less # than 30 years old, then you should be allowed in the club. # If you don't fulfill the conditions above, but you are older than 100 years # ol,d you should also be allowed. # If none of the conditions are met, you shouldn't be allowed in the club. print("What's your name?") name = raw_input() # The raw_input() function allows you to get user input, # don't worry about functions now. print("What's your age?") age = input() if name == "Bill Gates" or name == "Steve Jobs" or name == "Jesus": # print something saying that the guest was allowed in the club # don't forget indentation. print("You are welcomed in our fancy club!") elif name == 'Maria' and age < 30: print("You are welcomed in our fancy club!") elif age > 100: print("You are welcomed in our fancy club!") else: print("Get out! This club is only for special people!") # print something saying that the guest was not allowed in the club # # Test out your program and see if it works as it is supposed to.
print("What's your name?") name = raw_input() print("What's your age?") age = input() if name == 'Bill Gates' or name == 'Steve Jobs' or name == 'Jesus': print('You are welcomed in our fancy club!') elif name == 'Maria' and age < 30: print('You are welcomed in our fancy club!') elif age > 100: print('You are welcomed in our fancy club!') else: print('Get out! This club is only for special people!')
N, K = [int(a) for a in input().split()] h = [] for _ in range(N): h.append(int(input())) sortedh = sorted(h) min_ = 1e9 for i in range(N-K+1): diff = sortedh[i+K-1] - sortedh[i] min_ = min(min_, diff) print(min_)
(n, k) = [int(a) for a in input().split()] h = [] for _ in range(N): h.append(int(input())) sortedh = sorted(h) min_ = 1000000000.0 for i in range(N - K + 1): diff = sortedh[i + K - 1] - sortedh[i] min_ = min(min_, diff) print(min_)
# slow version dp class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ sLength, pLength = len(s), len(p) matrix = [[False] * (pLength+1) for i in range(sLength+1)] matrix[0][0] = True for i in range(sLength+1): for j in range(1, pLength+1): matrix[i][j] = matrix[i][j - 2] or (i > 0 and (s[i - 1] == p[j - 2] or p[j - 2] == '.') and matrix[i - 1][j])\ if p[j - 1] == '*' else i > 0 and matrix[i - 1][j - 1] and (s[i - 1] == p[j - 1] or p[j - 1] == '.') return matrix[-1][-1]
class Solution(object): def is_match(self, s, p): """ :type s: str :type p: str :rtype: bool """ (s_length, p_length) = (len(s), len(p)) matrix = [[False] * (pLength + 1) for i in range(sLength + 1)] matrix[0][0] = True for i in range(sLength + 1): for j in range(1, pLength + 1): matrix[i][j] = matrix[i][j - 2] or (i > 0 and (s[i - 1] == p[j - 2] or p[j - 2] == '.') and matrix[i - 1][j]) if p[j - 1] == '*' else i > 0 and matrix[i - 1][j - 1] and (s[i - 1] == p[j - 1] or p[j - 1] == '.') return matrix[-1][-1]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by AKM_FAN@163.com on 2017/11/6 if __name__ == '__main__': pass
if __name__ == '__main__': pass
# -*- coding: utf-8 -*- """ Created on Tue May 19 08:27:42 2020 @author: Shivadhar SIngh """ def histogram(seq): count = dict() for elem in seq: if elem not in count: count[elem] = 1 else: count[elem] += 1 return count
""" Created on Tue May 19 08:27:42 2020 @author: Shivadhar SIngh """ def histogram(seq): count = dict() for elem in seq: if elem not in count: count[elem] = 1 else: count[elem] += 1 return count
"""Errors raised by mailmerge.""" class MailmergeError(Exception): """Top level exception raised by mailmerge functions.""" class MailmergeRateLimitError(MailmergeError): """Reuse to send message because rate limit exceeded."""
"""Errors raised by mailmerge.""" class Mailmergeerror(Exception): """Top level exception raised by mailmerge functions.""" class Mailmergeratelimiterror(MailmergeError): """Reuse to send message because rate limit exceeded."""
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Constants for fever data.""" VERIFIABLE = 'VERIFIABLE' NOT_VERIFIABLE = 'NOT VERIFIABLE' # Classes used for claim classification and labeling which evidence # support/refute the claim NOT_ENOUGH_INFO = 'NOT ENOUGH INFO' REFUTES = 'REFUTES' SUPPORTS = 'SUPPORTS' FEVER_CLASSES = [REFUTES, SUPPORTS, NOT_ENOUGH_INFO] # Classes used for scoring candidate evidence relevance MATCHING = 'MATCHING' NOT_MATCHING = 'NOT_MATCHING' EVIDENCE_MATCHING_CLASSES = [NOT_MATCHING, MATCHING] UKP_WIKI = 'ukp_wiki' UKP_PRED = 'ukp_pred' UKP_TYPES = [UKP_PRED, UKP_WIKI] DRQA = 'drqa' LUCENE = 'lucene' DOC_TYPES = [UKP_WIKI, UKP_PRED, DRQA, LUCENE]
"""Constants for fever data.""" verifiable = 'VERIFIABLE' not_verifiable = 'NOT VERIFIABLE' not_enough_info = 'NOT ENOUGH INFO' refutes = 'REFUTES' supports = 'SUPPORTS' fever_classes = [REFUTES, SUPPORTS, NOT_ENOUGH_INFO] matching = 'MATCHING' not_matching = 'NOT_MATCHING' evidence_matching_classes = [NOT_MATCHING, MATCHING] ukp_wiki = 'ukp_wiki' ukp_pred = 'ukp_pred' ukp_types = [UKP_PRED, UKP_WIKI] drqa = 'drqa' lucene = 'lucene' doc_types = [UKP_WIKI, UKP_PRED, DRQA, LUCENE]
# !/usr/bin/python # -*- coding: utf-8 -*- class Friends(object): def __init__(self, connections): super(Friends, self).__init__() self._data = {} self._add_connections(connections) def add(self, connection): is_exists = self.is_exists(connection) self._add_connection(connection) return (not is_exists) def remove(self, connection): is_exists = self.is_exists(connection) if (not is_exists): return False self._remove_connection(connection) return True def names(self): return self._data.keys() def connected(self, name): if (name not in self._data): return set() return self._data[name] def is_exists(self, connection): copy = connection.copy() first, second = copy.pop(), copy.pop() return (first in self._data and second in self._data[first]) def _add_connection(self, connection): copy = connection.copy() first, second = copy.pop(), copy.pop() add = lambda i, x: self._data[i].add(x) if i in self._data else self._data.update({i: {x}}) add(first, second) add(second, first) def _add_connections(self, connections): for connection in connections: self._add_connection(connection) def _remove_connection(self, connection): copy = connection.copy() first, second = copy.pop(), copy.pop() removeValue = lambda i, x: self._data[i].remove(x) if True else None removeKey = lambda i: self._data.pop(i) if not len(self._data[i]) else None removeValue(first, second) removeValue(second, first) removeKey(first) removeKey(second) if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing letter_friends = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) digit_friends = Friends([{"1", "2"}, {"3", "1"}]) assert letter_friends.add({"c", "d"}) is True, "Add" assert letter_friends.add({"c", "d"}) is False, "Add again" assert letter_friends.remove({"c", "d"}) is True, "Remove" assert digit_friends.remove({"c", "d"}) is False, "Remove non exists" assert letter_friends.names() == {"a", "b", "c"}, "Names" assert letter_friends.connected("d") == set(), "Non connected name" assert letter_friends.connected("a") == {"b", "c"}, "Connected name"
class Friends(object): def __init__(self, connections): super(Friends, self).__init__() self._data = {} self._add_connections(connections) def add(self, connection): is_exists = self.is_exists(connection) self._add_connection(connection) return not is_exists def remove(self, connection): is_exists = self.is_exists(connection) if not is_exists: return False self._remove_connection(connection) return True def names(self): return self._data.keys() def connected(self, name): if name not in self._data: return set() return self._data[name] def is_exists(self, connection): copy = connection.copy() (first, second) = (copy.pop(), copy.pop()) return first in self._data and second in self._data[first] def _add_connection(self, connection): copy = connection.copy() (first, second) = (copy.pop(), copy.pop()) add = lambda i, x: self._data[i].add(x) if i in self._data else self._data.update({i: {x}}) add(first, second) add(second, first) def _add_connections(self, connections): for connection in connections: self._add_connection(connection) def _remove_connection(self, connection): copy = connection.copy() (first, second) = (copy.pop(), copy.pop()) remove_value = lambda i, x: self._data[i].remove(x) if True else None remove_key = lambda i: self._data.pop(i) if not len(self._data[i]) else None remove_value(first, second) remove_value(second, first) remove_key(first) remove_key(second) if __name__ == '__main__': letter_friends = friends(({'a', 'b'}, {'b', 'c'}, {'c', 'a'}, {'a', 'c'})) digit_friends = friends([{'1', '2'}, {'3', '1'}]) assert letter_friends.add({'c', 'd'}) is True, 'Add' assert letter_friends.add({'c', 'd'}) is False, 'Add again' assert letter_friends.remove({'c', 'd'}) is True, 'Remove' assert digit_friends.remove({'c', 'd'}) is False, 'Remove non exists' assert letter_friends.names() == {'a', 'b', 'c'}, 'Names' assert letter_friends.connected('d') == set(), 'Non connected name' assert letter_friends.connected('a') == {'b', 'c'}, 'Connected name'
def table_service(*args): text, client, current_channel = args if text.lower().startswith("tables"): number = int(text.split()[-1]) result = "" for i in range(1, 11): result += f"{number} X {i} = {number*i}\n" client.chat_postMessage(channel=current_channel, text=result)
def table_service(*args): (text, client, current_channel) = args if text.lower().startswith('tables'): number = int(text.split()[-1]) result = '' for i in range(1, 11): result += f'{number} X {i} = {number * i}\n' client.chat_postMessage(channel=current_channel, text=result)
class Parameters: def __init__(self, **kwargs): self.__dict__.update(kwargs) def info(self): print("The parameters, and data-type are: ") for key,values in self.__dict__.items(): print("{} = {}, {}\n".format(key, values, type(values)))
class Parameters: def __init__(self, **kwargs): self.__dict__.update(kwargs) def info(self): print('The parameters, and data-type are: ') for (key, values) in self.__dict__.items(): print('{} = {}, {}\n'.format(key, values, type(values)))
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) max_val = max(arr) while(max_val in arr): arr.remove(max_val) print(max(arr))
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) max_val = max(arr) while max_val in arr: arr.remove(max_val) print(max(arr))
CHECKSUM_TAG = 'CHECKSUM_TAG' AVSCAN_TAG = 'AVSCAN_TAG' MAILER_TAG = 'MAILER_TAG' UNPACK_TAG = 'UNPACK_TAG' ARKADE5_TAG = 'ARKADE5_TAG' ARTIFACT_WRITER_TAG = 'ARTIFACT_WRITER_TAG' class ContainerTagParams: """ Parameter class containing dictionaries of {parameter names: image tags} for containers used during argo workflows """ def __init__(self, checksum: str, avscan: str, mailer: str, unpack: str, arkade5: str, artifact_writer_tag: str): self.checksum = {CHECKSUM_TAG: checksum} self.avscan = {AVSCAN_TAG: avscan} self.mailer = {MAILER_TAG: mailer} self.unpack = {UNPACK_TAG: unpack} self.arkade5 = {ARKADE5_TAG: arkade5} self.artifact_writer_tag = {ARTIFACT_WRITER_TAG: artifact_writer_tag} def __eq__(self, other): if isinstance(other, ContainerTagParams): return self.checksum == other.checksum and \ self.avscan == other.avscan and \ self.mailer == other.mailer and \ self.unpack == other.unpack and \ self.arkade5 == other.arkade5 and \ self.artifact_writer_tag == other.artifact_writer_tag
checksum_tag = 'CHECKSUM_TAG' avscan_tag = 'AVSCAN_TAG' mailer_tag = 'MAILER_TAG' unpack_tag = 'UNPACK_TAG' arkade5_tag = 'ARKADE5_TAG' artifact_writer_tag = 'ARTIFACT_WRITER_TAG' class Containertagparams: """ Parameter class containing dictionaries of {parameter names: image tags} for containers used during argo workflows """ def __init__(self, checksum: str, avscan: str, mailer: str, unpack: str, arkade5: str, artifact_writer_tag: str): self.checksum = {CHECKSUM_TAG: checksum} self.avscan = {AVSCAN_TAG: avscan} self.mailer = {MAILER_TAG: mailer} self.unpack = {UNPACK_TAG: unpack} self.arkade5 = {ARKADE5_TAG: arkade5} self.artifact_writer_tag = {ARTIFACT_WRITER_TAG: artifact_writer_tag} def __eq__(self, other): if isinstance(other, ContainerTagParams): return self.checksum == other.checksum and self.avscan == other.avscan and (self.mailer == other.mailer) and (self.unpack == other.unpack) and (self.arkade5 == other.arkade5) and (self.artifact_writer_tag == other.artifact_writer_tag)
def solution(A): curSlice = float('-inf') maxSlice = float('-inf') for num in A: curSlice = max(num, curSlice+num) maxSlice = max(curSlice, maxSlice) return maxSlice if __name__ == '__main__': print(solution([3,2,-6,4,0])) print(solution([-10]))
def solution(A): cur_slice = float('-inf') max_slice = float('-inf') for num in A: cur_slice = max(num, curSlice + num) max_slice = max(curSlice, maxSlice) return maxSlice if __name__ == '__main__': print(solution([3, 2, -6, 4, 0])) print(solution([-10]))
class Solution: def XXX(self, head: ListNode) -> ListNode: o = head p = None while head is not None: if p is not None and head.val == p.val: p.next = head.next else: p = head head = head.next return o
class Solution: def xxx(self, head: ListNode) -> ListNode: o = head p = None while head is not None: if p is not None and head.val == p.val: p.next = head.next else: p = head head = head.next return o
def taxicab_distance(a, b): """ Returns the Manhattan distance of the given points """ n = len(a) d = 0 for i in range(n): d += abs(a[i] - b[i]) return d PERIOD = 2 # the period of the sequence def sequ(): """ Generates the sequence corresponding to the number of steps to take at each turn when traversing memory """ step = 0 val = 1 while True: if step == PERIOD: step = 0 val += 1 yield val step += 1 # movements def right(pos): """ Move right """ return (pos[0]+1, pos[1]) def left(pos): """ Move left """ return (pos[0]-1, pos[1]) def up(pos): """ Move up """ return (pos[0], pos[1]+1) def down(pos): """ Move down """ return (pos[0], pos[1]-1) PORT_NUM = 1 # address of sole I/O port def coordinates(n): """ Returns the co-ordinates of the given address in memory """ if n == PORT_NUM: # orient ourselves w.r.t. to I/O port return (0, 0) pos = (0, 0) seq = sequ() diff = n - 1 while diff > 0: if diff == 0: # are we there yet? return pos # right branch branch_length = next(seq) for i in range(branch_length): if diff == 0: # are we there yet? return pos pos = right(pos) diff -= 1 # decrement difference # up branch branch_length = next(seq) for i in range(branch_length): if diff == 0: # are we there yet? return pos pos = up(pos) diff -= 1 # decrement difference # left branch branch_length = next(seq) for i in range(branch_length): if diff == 0: # are we there yet? return pos pos = left(pos) diff -= 1 # decrement difference # down branch branch_length = next(seq) for i in range(branch_length): if diff == 0: # are we there yet? return pos pos = down(pos) diff -= 1 # decrement difference return pos def distance(n): """ Returns the Manhattan distance from the I/O port to the given address """ port_loc = coordinates(PORT_NUM) n_loc = coordinates(n) return taxicab_distance(port_loc, n_loc) def num_steps(n): """ Returns the number of steps required to get from the given address to the I/O port """ if n == PORT_NUM: return 0 pos = coordinates(n) return distance(n) """ # tests print(num_steps(1)) # 0 print(num_steps(12)) # 3 print(num_steps(23)) # 2 print(num_steps(1024)) # 31 """ INPUT_FILE_PATH = "input.txt" def main(): with open(INPUT_FILE_PATH) as f: n = int(f.readline()) print(num_steps(n))
def taxicab_distance(a, b): """ Returns the Manhattan distance of the given points """ n = len(a) d = 0 for i in range(n): d += abs(a[i] - b[i]) return d period = 2 def sequ(): """ Generates the sequence corresponding to the number of steps to take at each turn when traversing memory """ step = 0 val = 1 while True: if step == PERIOD: step = 0 val += 1 yield val step += 1 def right(pos): """ Move right """ return (pos[0] + 1, pos[1]) def left(pos): """ Move left """ return (pos[0] - 1, pos[1]) def up(pos): """ Move up """ return (pos[0], pos[1] + 1) def down(pos): """ Move down """ return (pos[0], pos[1] - 1) port_num = 1 def coordinates(n): """ Returns the co-ordinates of the given address in memory """ if n == PORT_NUM: return (0, 0) pos = (0, 0) seq = sequ() diff = n - 1 while diff > 0: if diff == 0: return pos branch_length = next(seq) for i in range(branch_length): if diff == 0: return pos pos = right(pos) diff -= 1 branch_length = next(seq) for i in range(branch_length): if diff == 0: return pos pos = up(pos) diff -= 1 branch_length = next(seq) for i in range(branch_length): if diff == 0: return pos pos = left(pos) diff -= 1 branch_length = next(seq) for i in range(branch_length): if diff == 0: return pos pos = down(pos) diff -= 1 return pos def distance(n): """ Returns the Manhattan distance from the I/O port to the given address """ port_loc = coordinates(PORT_NUM) n_loc = coordinates(n) return taxicab_distance(port_loc, n_loc) def num_steps(n): """ Returns the number of steps required to get from the given address to the I/O port """ if n == PORT_NUM: return 0 pos = coordinates(n) return distance(n) '\n# tests\nprint(num_steps(1)) # 0\nprint(num_steps(12)) # 3\nprint(num_steps(23)) # 2\nprint(num_steps(1024)) # 31\n' input_file_path = 'input.txt' def main(): with open(INPUT_FILE_PATH) as f: n = int(f.readline()) print(num_steps(n))
#!/usr/bin/env python3 ######################################################################################################################## ##### INFORMATION ###################################################################################################### ### @PROJECT_NAME: SPLAT: Speech Processing and Linguistic Analysis Tool ### ### @VERSION_NUMBER: ### ### @PROJECT_SITE: github.com/meyersbs/SPLAT ### ### @AUTHOR_NAME: Benjamin S. Meyers ### ### @CONTACT_EMAIL: ben@splat-library.org ### ### @LICENSE_TYPE: MIT ### ######################################################################################################################## ######################################################################################################################## """ This package contains the following files: [01] POSTagger.py Provides the functionality to tokenize the given input with punctuation as separate tokens, and then does a dictionary lookup to determine the part-of-speech for each token. """
""" This package contains the following files: [01] POSTagger.py Provides the functionality to tokenize the given input with punctuation as separate tokens, and then does a dictionary lookup to determine the part-of-speech for each token. """
def start(): return def stop(): return def apply_command(self, c, e, command, arguments): pass def on_welcome(self, c, e): pass def on_invite(self, c, e): pass def on_join(self, c, e): pass def on_namreply(self, c, e): pass def on_pubmsg(self, c, e): pass def on_privmsg(self, c, e): pass
def start(): return def stop(): return def apply_command(self, c, e, command, arguments): pass def on_welcome(self, c, e): pass def on_invite(self, c, e): pass def on_join(self, c, e): pass def on_namreply(self, c, e): pass def on_pubmsg(self, c, e): pass def on_privmsg(self, c, e): pass
# Code Challenge 13 open_list = ["[", "{", "("] close_list = ["]", "}", ")"] def validate_brackets(str): stack=[] for i in str: if i in open_list: stack.append(i) elif i in close_list: x = close_list.index(i) if ((len(stack) > 0) and (open_list[x] == stack[len(stack) - 1])): stack.pop() else: return False if len(stack) == 0: return True else: return False
open_list = ['[', '{', '('] close_list = [']', '}', ')'] def validate_brackets(str): stack = [] for i in str: if i in open_list: stack.append(i) elif i in close_list: x = close_list.index(i) if len(stack) > 0 and open_list[x] == stack[len(stack) - 1]: stack.pop() else: return False if len(stack) == 0: return True else: return False
tail = input() body = input() head = input() meerkat = [tail, body, head] meerkat.reverse() print(meerkat)
tail = input() body = input() head = input() meerkat = [tail, body, head] meerkat.reverse() print(meerkat)
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. a<995 b<996 c<997 They tell us there is only one, so we only need to test for existence, not uniqueness. We have 2 equations: a2+b2=c2 a+b+c=1000 """ # Lets test all three cases for all numbers until we get the answer. # The problem told us it was unique, so we can exit. for a in range(1,1000): for b in range(1,1000): for c in range(1,1000): if a<b<c and a+b+c==1000 and a**2+b**2==c**2: print("answer:", a*b*c) exit(0)
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. a<995 b<996 c<997 They tell us there is only one, so we only need to test for existence, not uniqueness. We have 2 equations: a2+b2=c2 a+b+c=1000 """ for a in range(1, 1000): for b in range(1, 1000): for c in range(1, 1000): if a < b < c and a + b + c == 1000 and (a ** 2 + b ** 2 == c ** 2): print('answer:', a * b * c) exit(0)
num = int(input()) for i in range(num): s = input() t = input() p = input()
num = int(input()) for i in range(num): s = input() t = input() p = input()
def peopleneeded(Smax, S): needed = 0 for s in range(Smax+1): if sum(S[:s+1])<s+1: needed += s+1-sum(S[:s+1]) S[s] += s+1-sum(S[:s+1]) return needed def get_output(instance): inputdata = open(instance + ".in", 'r') output = open(instance+ ".out", 'w') T = int(inputdata.readline()) for t in range(T): Smax, S = inputdata.readline().split() Smax = int(Smax) S = [int(i) for i in list(S)] output.write('Case #' + str(t+1) +': ' + str(peopleneeded(Smax, S)) + "\n") return None
def peopleneeded(Smax, S): needed = 0 for s in range(Smax + 1): if sum(S[:s + 1]) < s + 1: needed += s + 1 - sum(S[:s + 1]) S[s] += s + 1 - sum(S[:s + 1]) return needed def get_output(instance): inputdata = open(instance + '.in', 'r') output = open(instance + '.out', 'w') t = int(inputdata.readline()) for t in range(T): (smax, s) = inputdata.readline().split() smax = int(Smax) s = [int(i) for i in list(S)] output.write('Case #' + str(t + 1) + ': ' + str(peopleneeded(Smax, S)) + '\n') return None
class Solution: def isValidSerialization(self, preorder: str) -> bool: degree = 1 # outDegree (children) - inDegree (parent) for node in preorder.split(','): degree -= 1 if degree < 0: return False if node != '#': degree += 2 return degree == 0
class Solution: def is_valid_serialization(self, preorder: str) -> bool: degree = 1 for node in preorder.split(','): degree -= 1 if degree < 0: return False if node != '#': degree += 2 return degree == 0
""" Tests as were previously formatted. Leaving here in case I want to revert to more disparate testing. """ def test_vehicle_info(client): mock_file = 'mock_vehicleinfo.json' output_file = 'output_vehicleinfo.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get(url_for('endpoints.get_vehicle_info', id=ID_GOOD)) assert response.json == correct_output def test_security_info(client): mock_file = 'mock_securityinfo.json' output_file = 'output_securityinfo.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = response = client.get('/vehicles/' + str(ID_GOOD) + '/doors') assert response.json == correct_output def test_fuel(client): mock_file = 'mock_fuelbattery.json' output_file = 'output_fuel.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get('/vehicles/' + str(ID_GOOD) + '/fuel') assert response.json == correct_output def test_battery(client): mock_file = 'mock_fuelbattery.json' output_file = 'output_battery.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get('/vehicles/' + str(ID_GOOD) + '/battery', ) assert response.json == correct_output def test_start_stop(client): mock_file = 'mock_engine.json' output_file = 'output_engine.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) headers = { 'Content-Type': 'application/json' } parameters = { "action": "START" } with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.post('/vehicles/' + str(ID_GOOD) + '/engine', headers=headers, data=json.dumps(parameters)) assert response.json == correct_output
""" Tests as were previously formatted. Leaving here in case I want to revert to more disparate testing. """ def test_vehicle_info(client): mock_file = 'mock_vehicleinfo.json' output_file = 'output_vehicleinfo.json' (mock_response, correct_output) = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get(url_for('endpoints.get_vehicle_info', id=ID_GOOD)) assert response.json == correct_output def test_security_info(client): mock_file = 'mock_securityinfo.json' output_file = 'output_securityinfo.json' (mock_response, correct_output) = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = response = client.get('/vehicles/' + str(ID_GOOD) + '/doors') assert response.json == correct_output def test_fuel(client): mock_file = 'mock_fuelbattery.json' output_file = 'output_fuel.json' (mock_response, correct_output) = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get('/vehicles/' + str(ID_GOOD) + '/fuel') assert response.json == correct_output def test_battery(client): mock_file = 'mock_fuelbattery.json' output_file = 'output_battery.json' (mock_response, correct_output) = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get('/vehicles/' + str(ID_GOOD) + '/battery') assert response.json == correct_output def test_start_stop(client): mock_file = 'mock_engine.json' output_file = 'output_engine.json' (mock_response, correct_output) = mocktest_setup(mock_file, output_file) headers = {'Content-Type': 'application/json'} parameters = {'action': 'START'} with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.post('/vehicles/' + str(ID_GOOD) + '/engine', headers=headers, data=json.dumps(parameters)) assert response.json == correct_output
""" Space : O(n) Time : O(n) """ class Solution: def rob(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] if len(nums) == 0: return 0 ans = 0 leng = len(nums)-1 one, two = [0] * leng, [0] * leng # 1st iteration for idx in range(leng): if idx < 2: one[idx] = nums[idx] else: one[idx] = nums[idx] + max(one[idx-2], one[idx-3]) ans = max(ans, one[idx]) # 2nd iteration for idx in range(leng): if idx < 2: two[idx] = nums[idx+1] else: two[idx] = nums[idx+1] + max(two[idx-2], two[idx-3]) ans = max(ans, two[idx]) return ans
""" Space : O(n) Time : O(n) """ class Solution: def rob(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] if len(nums) == 0: return 0 ans = 0 leng = len(nums) - 1 (one, two) = ([0] * leng, [0] * leng) for idx in range(leng): if idx < 2: one[idx] = nums[idx] else: one[idx] = nums[idx] + max(one[idx - 2], one[idx - 3]) ans = max(ans, one[idx]) for idx in range(leng): if idx < 2: two[idx] = nums[idx + 1] else: two[idx] = nums[idx + 1] + max(two[idx - 2], two[idx - 3]) ans = max(ans, two[idx]) return ans
class ZoneFilter: def __init__(self, rules): self.rules = rules def filter(self, record): # TODO Dummy implementation return [record]
class Zonefilter: def __init__(self, rules): self.rules = rules def filter(self, record): return [record]
class HyperparameterGrid(): def __init__(self): DEFAULT_HYPERPARAMETER_GRID = { 'lr': { 'C': [0.001, 0.01, 0.1, 1], 'penalty': ['l1', 'l2'], 'solver': ['liblinear'], 'intercept_scaling': [1, 1000], 'max_iter': [1000] }, 'dt': { 'criterion': ['gini', 'entropy'], 'max_depth': [3, 5, 10, None], 'min_samples_leaf': [0.01, 0.02, 0.05], }, 'rf': { 'n_estimators': [100, 500, 1000], 'criterion': ['gini','entropy'], 'max_depth': [3, 5, 10, None], 'min_samples_leaf': [0.01, 0.02, 0.05], }, 'xgb': { 'max_depth': [2, 3, 4, 5, 6], 'eta': [.1, .3, .5], 'eval_metric': ['auc'], 'min_child_weight': [1, 3, 5, 7, 9], 'gamma':[0], 'scale_pos_weight': [1], 'bsample': [0.8], 'n_jobs': [4], 'n_estimators': [100], 'colsample_bytree': [0.8], 'objective': ['binary:logistic'], } } self.param_grids = DEFAULT_HYPERPARAMETER_GRID
class Hyperparametergrid: def __init__(self): default_hyperparameter_grid = {'lr': {'C': [0.001, 0.01, 0.1, 1], 'penalty': ['l1', 'l2'], 'solver': ['liblinear'], 'intercept_scaling': [1, 1000], 'max_iter': [1000]}, 'dt': {'criterion': ['gini', 'entropy'], 'max_depth': [3, 5, 10, None], 'min_samples_leaf': [0.01, 0.02, 0.05]}, 'rf': {'n_estimators': [100, 500, 1000], 'criterion': ['gini', 'entropy'], 'max_depth': [3, 5, 10, None], 'min_samples_leaf': [0.01, 0.02, 0.05]}, 'xgb': {'max_depth': [2, 3, 4, 5, 6], 'eta': [0.1, 0.3, 0.5], 'eval_metric': ['auc'], 'min_child_weight': [1, 3, 5, 7, 9], 'gamma': [0], 'scale_pos_weight': [1], 'bsample': [0.8], 'n_jobs': [4], 'n_estimators': [100], 'colsample_bytree': [0.8], 'objective': ['binary:logistic']}} self.param_grids = DEFAULT_HYPERPARAMETER_GRID
def uniqueElements(myList): uniqList = [] for _var in myList: if _var not in uniqList: uniqList.append(_var) else: return "Not Unique" return "Unique" print(uniqueElements([2,99,99,12,3,11,223]))
def unique_elements(myList): uniq_list = [] for _var in myList: if _var not in uniqList: uniqList.append(_var) else: return 'Not Unique' return 'Unique' print(unique_elements([2, 99, 99, 12, 3, 11, 223]))
def magic_square(square): size_square = len(square) is_magic = True wanted_sum = 0 for index in range(0, size_square): wanted_sum += square[0][index] for row in range(0, size_square): current_sum = 0 for col in range(0, size_square): current_sum += square[row][col] if current_sum != wanted_sum: is_magic = False break for col in range(0, size_square): current_sum = 0 for row in range(0, size_square): current_sum += square[row][col] if current_sum != wanted_sum: is_magic = False break current_sum = 0 row = 0 col = 0 while row < size_square and col < size_square: current_sum += square[row][col] row += 1 col += 1 if current_sum != wanted_sum: is_magic = False current_sum = 0 row = 0 col = size_square - 1 while row < size_square and col >= 0: current_sum += square[row][col] row += 1 col -= 1 if current_sum != wanted_sum: is_magic = False return is_magic square1 = [ [23, 28, 21], [22, 24, 26], [27, 20, 25] ] square2 = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print (magic_square(square1)) print (magic_square(square2))
def magic_square(square): size_square = len(square) is_magic = True wanted_sum = 0 for index in range(0, size_square): wanted_sum += square[0][index] for row in range(0, size_square): current_sum = 0 for col in range(0, size_square): current_sum += square[row][col] if current_sum != wanted_sum: is_magic = False break for col in range(0, size_square): current_sum = 0 for row in range(0, size_square): current_sum += square[row][col] if current_sum != wanted_sum: is_magic = False break current_sum = 0 row = 0 col = 0 while row < size_square and col < size_square: current_sum += square[row][col] row += 1 col += 1 if current_sum != wanted_sum: is_magic = False current_sum = 0 row = 0 col = size_square - 1 while row < size_square and col >= 0: current_sum += square[row][col] row += 1 col -= 1 if current_sum != wanted_sum: is_magic = False return is_magic square1 = [[23, 28, 21], [22, 24, 26], [27, 20, 25]] square2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(magic_square(square1)) print(magic_square(square2))
def f(x): y=1 x=x+y return x x=3 y=2 z=f(x) print("x="+str(x)) print("y="+str(y)) print("z="+str(z))
def f(x): y = 1 x = x + y return x x = 3 y = 2 z = f(x) print('x=' + str(x)) print('y=' + str(y)) print('z=' + str(z))
__all__ = [ "mock_generation_data_frame", "test_get_monthly_net_generation", "test_rate_limit", "test_retry", ]
__all__ = ['mock_generation_data_frame', 'test_get_monthly_net_generation', 'test_rate_limit', 'test_retry']
test = { 'name': 'q1_2', 'points': 1, 'suites': [ { 'cases': [ {'code': ">>> assert trending_vids.shape[0] == '40379'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 0] == '25231'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 4] == 'Inside Edition'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[0, 'views'] == 542677.0\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[2, 'likes'] == 11390.0\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[3, 'dislikes'] == 175.0\n", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
test = {'name': 'q1_2', 'points': 1, 'suites': [{'cases': [{'code': ">>> assert trending_vids.shape[0] == '40379'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 0] == '25231'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 4] == 'Inside Edition'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[0, 'views'] == 542677.0\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[2, 'likes'] == 11390.0\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[3, 'dislikes'] == 175.0\n", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
# -*- coding: utf-8 -*- """ Created on Tue Apr 6 10:35:39 2021 @author: ELCOT """ """ Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] """ class Solution: def generate(self,n): res = [[1]] if n == 1: return res for i in range(2,n+1): r = [1] for j in range(2,i): #print(i,j) s = (r[-1] * (i-(j-1))) / (j-1) r.append(int(s)) r.append(1) res.append(r) print(res) Solution().generate(5)
""" Created on Tue Apr 6 10:35:39 2021 @author: ELCOT """ "\nGiven an integer numRows, return the first numRows of Pascal's triangle.\n\nIn Pascal's triangle, each number is the sum of the two numbers directly above it as shown:\n \nInput: numRows = 5\nOutput: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] \n" class Solution: def generate(self, n): res = [[1]] if n == 1: return res for i in range(2, n + 1): r = [1] for j in range(2, i): s = r[-1] * (i - (j - 1)) / (j - 1) r.append(int(s)) r.append(1) res.append(r) print(res) solution().generate(5)
class Income: def __init__(self): self.tranId = "" self.tradeId = "" self.symbol = "" self.incomeType = "" self.income = 0.0 self.asset = "" self.time = 0 @staticmethod def json_parse(json_data): result = Income() result.tranId = json_data.get_string("tranId") result.tradeId = json_data.get_string("tradeId") result.symbol = json_data.get_string("symbol") result.incomeType = json_data.get_string("incomeType") result.income = json_data.get_float("income") result.asset = json_data.get_string("asset") result.time = json_data.get_int("time") return result
class Income: def __init__(self): self.tranId = '' self.tradeId = '' self.symbol = '' self.incomeType = '' self.income = 0.0 self.asset = '' self.time = 0 @staticmethod def json_parse(json_data): result = income() result.tranId = json_data.get_string('tranId') result.tradeId = json_data.get_string('tradeId') result.symbol = json_data.get_string('symbol') result.incomeType = json_data.get_string('incomeType') result.income = json_data.get_float('income') result.asset = json_data.get_string('asset') result.time = json_data.get_int('time') return result
def game(input,max_turns): memory = {} turncounter = 1 most_recent_number = int(input[-1]) for i in range(len(input)): memory[int(input[i])] = [turncounter,-1] turncounter += 1 while turncounter <= max_turns: if memory[most_recent_number][1] == -1: most_recent_number = 0 else: most_recent_number = memory[most_recent_number][0] - memory[most_recent_number][1] if most_recent_number in memory: memory[most_recent_number] = [turncounter,memory[most_recent_number][0]] else: memory[most_recent_number] = [turncounter,-1] turncounter +=1 return str(most_recent_number) def main(filepath): with open(filepath) as file: rows = [x.strip() for x in file.readlines()] input = rows[0].split(",") print("Part a solution: "+game(input,2020)) print("Part b solution: "+game(input,30000000)) #takes a while to run, but less than 1 minute
def game(input, max_turns): memory = {} turncounter = 1 most_recent_number = int(input[-1]) for i in range(len(input)): memory[int(input[i])] = [turncounter, -1] turncounter += 1 while turncounter <= max_turns: if memory[most_recent_number][1] == -1: most_recent_number = 0 else: most_recent_number = memory[most_recent_number][0] - memory[most_recent_number][1] if most_recent_number in memory: memory[most_recent_number] = [turncounter, memory[most_recent_number][0]] else: memory[most_recent_number] = [turncounter, -1] turncounter += 1 return str(most_recent_number) def main(filepath): with open(filepath) as file: rows = [x.strip() for x in file.readlines()] input = rows[0].split(',') print('Part a solution: ' + game(input, 2020)) print('Part b solution: ' + game(input, 30000000))
# Copyright 2020 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. VALID_META_KEYS = ["cpu", "memory", "gpu"] def post_process(metadata): # memory should be in MB if "memory" in metadata: memory = metadata.pop("memory") metadata["mem"] = memory return metadata def meta(**kwargs): """ fiber.meta API allows you to decorate your function and provide some hints to Fiber. Currently this is mainly used for specify the resource usage of user functions. Currently, support keys are: | key | Type | Default | Notes | | --------------------- |:------|:-----|:------| | cpu | int | None | The number of CPU cores that this function needs | | memory | int | None | The size of memory space in MB this function needs | | gpu | int | None | The number of GPUs that this function needs. For how to setup Fiber with GPUs, check out [here](advanced.md#using-fiber-with-gpus) | Example usage: ```python @fiber.meta(cpu=4, memory=1000, gpu=1) def func(): do_something() ``` """ for k in kwargs: assert k in VALID_META_KEYS, "Invalid meta argument \"{}\"".format(k) def decorator(func): meta = post_process(kwargs) func.__fiber_meta__ = meta return func return decorator
valid_meta_keys = ['cpu', 'memory', 'gpu'] def post_process(metadata): if 'memory' in metadata: memory = metadata.pop('memory') metadata['mem'] = memory return metadata def meta(**kwargs): """ fiber.meta API allows you to decorate your function and provide some hints to Fiber. Currently this is mainly used for specify the resource usage of user functions. Currently, support keys are: | key | Type | Default | Notes | | --------------------- |:------|:-----|:------| | cpu | int | None | The number of CPU cores that this function needs | | memory | int | None | The size of memory space in MB this function needs | | gpu | int | None | The number of GPUs that this function needs. For how to setup Fiber with GPUs, check out [here](advanced.md#using-fiber-with-gpus) | Example usage: ```python @fiber.meta(cpu=4, memory=1000, gpu=1) def func(): do_something() ``` """ for k in kwargs: assert k in VALID_META_KEYS, 'Invalid meta argument "{}"'.format(k) def decorator(func): meta = post_process(kwargs) func.__fiber_meta__ = meta return func return decorator
def is_krampus(n): p = str(n**2) l_p = len(p) for i in range(1, l_p - 1): p_1 = int(p[:i]) p_2 = int(p[i:]) if p_1 and p_2 and p_1 + p_2 == n: return True return False def test_is_krampus(): assert is_krampus(45) assert not is_krampus(100) if __name__ == '__main__': s = 0 for n in open('input/09').readlines(): n = int(n.strip()) if is_krampus(n): s += n print(s)
def is_krampus(n): p = str(n ** 2) l_p = len(p) for i in range(1, l_p - 1): p_1 = int(p[:i]) p_2 = int(p[i:]) if p_1 and p_2 and (p_1 + p_2 == n): return True return False def test_is_krampus(): assert is_krampus(45) assert not is_krampus(100) if __name__ == '__main__': s = 0 for n in open('input/09').readlines(): n = int(n.strip()) if is_krampus(n): s += n print(s)
def adjacentElementsProduct(inputArray): first, second = 0, 1 lp = inputArray[first]*inputArray[second] for index in range(2, len(inputArray)): first = second second = index new_lp = inputArray[first]*inputArray[second] if new_lp > lp: lp = new_lp return lp
def adjacent_elements_product(inputArray): (first, second) = (0, 1) lp = inputArray[first] * inputArray[second] for index in range(2, len(inputArray)): first = second second = index new_lp = inputArray[first] * inputArray[second] if new_lp > lp: lp = new_lp return lp
def y(): pass def x(): y() for i in range(10): x()
def y(): pass def x(): y() for i in range(10): x()
INSTALLED_APPS = ( 'vkontakte_api', 'vkontakte_places', 'vkontakte_users', 'vkontakte_groups', 'vkontakte_comments', 'm2m_history', ) SOCIAL_API_TOKENS_STORAGES = []
installed_apps = ('vkontakte_api', 'vkontakte_places', 'vkontakte_users', 'vkontakte_groups', 'vkontakte_comments', 'm2m_history') social_api_tokens_storages = []
# # PySNMP MIB module AcAlarm (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AcAlarm # Produced by pysmi-0.3.4 at Wed May 1 11:33:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # AcAlarmEventType, AcAlarmProbableCause, AcAlarmSeverity = mibBuilder.importSymbols("AC-FAULT-TC", "AcAlarmEventType", "AcAlarmProbableCause", "AcAlarmSeverity") OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") SnmpEngineID, SnmpAdminString = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpEngineID", "SnmpAdminString") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") TimeTicks, enterprises, ModuleIdentity, iso, Bits, NotificationType, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, IpAddress, Counter32, Gauge32, Counter64, ObjectIdentity, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "enterprises", "ModuleIdentity", "iso", "Bits", "NotificationType", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "IpAddress", "Counter32", "Gauge32", "Counter64", "ObjectIdentity", "Integer32") TimeStamp, DateAndTime, DisplayString, RowStatus, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "DateAndTime", "DisplayString", "RowStatus", "TruthValue", "TextualConvention") audioCodes = MibIdentifier((1, 3, 6, 1, 4, 1, 5003)) acFault = MibIdentifier((1, 3, 6, 1, 4, 1, 5003, 11)) acAlarm = ModuleIdentity((1, 3, 6, 1, 4, 1, 5003, 11, 1)) acAlarm.setRevisions(('2003-12-18 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: acAlarm.setRevisionsDescriptions(('4.4. Dec. 18, 2003. Made these changes: o Initial version',)) if mibBuilder.loadTexts: acAlarm.setLastUpdated('200312180000Z') if mibBuilder.loadTexts: acAlarm.setOrganization('Audiocodes') if mibBuilder.loadTexts: acAlarm.setContactInfo('Postal: Support AudioCodes LTD 1 Hayarden Street Airport City Lod 70151, ISRAEL Tel: 972-3-9764000 Fax: 972-3-9764040 Email: support@audiocodes.com Web: www.audiocodes.com') if mibBuilder.loadTexts: acAlarm.setDescription('This MIB defines the enterprise-specific objects needed to support fault management of Audiocodes products. The MIB consists of: o Active alarm table o Alarm history table o Alarm notification varbinds') acActiveAlarm = MibIdentifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1)) acActiveAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1), ) if mibBuilder.loadTexts: acActiveAlarmTable.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTable.setDescription('Table of active alarms.') acActiveAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1), ).setIndexNames((0, "AcAlarm", "acActiveAlarmSequenceNumber")) if mibBuilder.loadTexts: acActiveAlarmEntry.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmEntry.setDescription('A conceptual row in the acActiveAlarmTable') acActiveAlarmSequenceNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmSequenceNumber.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSequenceNumber.setDescription('The sequence number of the alarm raise trap.') acActiveAlarmSysuptime = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 2), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmSysuptime.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSysuptime.setDescription('The value of sysuptime at the time the alarm raise trap was sent') acActiveAlarmTrapOID = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmTrapOID.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTrapOID.setDescription('The OID of the notification trap') acActiveAlarmDateAndTime = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 4), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmDateAndTime.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmDateAndTime.setDescription('The date and time at the time the alarm raise trap was sent.') acActiveAlarmName = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmName.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmName.setDescription('The name of the alarm that was raised. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') acActiveAlarmTextualDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 6), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmTextualDescription.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTextualDescription.setDescription('Text that descries the alarm condition.') acActiveAlarmSource = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 7), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmSource.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSource.setDescription('The component in the system which raised the alarm.') acActiveAlarmSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 8), AcAlarmSeverity()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmSeverity.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSeverity.setDescription('The severity of the alarm.') acActiveAlarmEventType = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 9), AcAlarmEventType()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmEventType.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmEventType.setDescription('The event type of the alarm.') acActiveAlarmProbableCause = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 10), AcAlarmProbableCause()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmProbableCause.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmProbableCause.setDescription('The probable cause of the alarm.') acActiveAlarmAdditionalInfo1 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 11), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') acActiveAlarmAdditionalInfo2 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 12), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') acActiveAlarmAdditionalInfo3 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 13), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2)) acAlarmHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1), ) if mibBuilder.loadTexts: acAlarmHistoryTable.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTable.setDescription('A table of all raise-alarm and clear-alarm traps sent by the system. Internal to the system, this table of traps is a fixed size. Once the table reaches this size, older traps are removed to make room for new traps. The size of the table is the value of the nlmConfigLogEntryLimit (NOTIFICATION-LOG-MIB).') acAlarmHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1), ).setIndexNames((0, "AcAlarm", "acAlarmHistorySequenceNumber")) if mibBuilder.loadTexts: acAlarmHistoryEntry.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryEntry.setDescription('A conceptual row in the acAlarmHistoryTable') acAlarmHistorySequenceNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistorySequenceNumber.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySequenceNumber.setDescription('The sequence number of the alarm raise or clear trap.') acAlarmHistorySysuptime = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 2), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistorySysuptime.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySysuptime.setDescription('The value of sysuptime at the time the alarm raise or clear trap was sent') acAlarmHistoryTrapOID = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryTrapOID.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTrapOID.setDescription('The OID of the notification trap') acAlarmHistoryDateAndTime = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 4), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryDateAndTime.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryDateAndTime.setDescription('The date and time at the time the alarm raise or clear trap was sent.') acAlarmHistoryName = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryName.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryName.setDescription('The name of the alarm that was raised or cleared. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') acAlarmHistoryTextualDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 6), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryTextualDescription.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTextualDescription.setDescription('Text that descries the alarm condition.') acAlarmHistorySource = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 7), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistorySource.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySource.setDescription('The component in the system which raised or cleared the alarm.') acAlarmHistorySeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 8), AcAlarmSeverity()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistorySeverity.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySeverity.setDescription('The severity of the alarm. A severity of warning, minor, major or critical indicates a raise trap. A severity of cleared indicates a clear trap.') acAlarmHistoryEventType = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 9), AcAlarmEventType()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryEventType.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryEventType.setDescription('The event type of the alarm.') acAlarmHistoryProbableCause = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 10), AcAlarmProbableCause()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryProbableCause.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryProbableCause.setDescription('The probable cause of the alarm.') acAlarmHistoryAdditionalInfo1 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 11), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmHistoryAdditionalInfo2 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 12), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmHistoryAdditionalInfo3 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 13), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmVarbinds = MibIdentifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3)) acAlarmVarbindsSequenceNumber = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 1), Unsigned32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsSequenceNumber.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSequenceNumber.setDescription('The sequence number of the alarm raise or clear trap.') acAlarmVarbindsDateAndTime = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 2), DateAndTime()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsDateAndTime.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsDateAndTime.setDescription('The date and time at the time the alarm raise or clear trap was sent.') acAlarmVarbindsAlarmName = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 3), Unsigned32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsAlarmName.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAlarmName.setDescription('The name of the alarm that was raised or cleared. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') acAlarmVarbindsTextualDescription = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 4), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsTextualDescription.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsTextualDescription.setDescription('Text that descries the alarm condition.') acAlarmVarbindsSource = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 5), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsSource.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSource.setDescription('The component in the system which raised or cleared the alarm.') acAlarmVarbindsSeverity = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 6), AcAlarmSeverity()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsSeverity.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSeverity.setDescription('The severity of the alarm. A severity of warning, minor, major or critical indicates a raise trap. A severity of cleared indicates a clear trap.') acAlarmVarbindsEventType = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 7), AcAlarmEventType()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsEventType.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsEventType.setDescription('The event type of the alarm.') acAlarmVarbindsProbableCause = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 8), AcAlarmProbableCause()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsProbableCause.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsProbableCause.setDescription('The probable cause of the alarm.') acAlarmVarbindsAdditionalInfo1 = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 9), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmVarbindsAdditionalInfo2 = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 10), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmVarbindsAdditionalInfo3 = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 11), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') mibBuilder.exportSymbols("AcAlarm", acAlarmVarbinds=acAlarmVarbinds, acActiveAlarmSource=acActiveAlarmSource, acActiveAlarmSeverity=acActiveAlarmSeverity, audioCodes=audioCodes, acAlarmHistorySequenceNumber=acAlarmHistorySequenceNumber, acAlarmVarbindsSource=acAlarmVarbindsSource, acAlarmHistory=acAlarmHistory, acActiveAlarmEventType=acActiveAlarmEventType, acAlarmHistoryEventType=acAlarmHistoryEventType, acActiveAlarmTable=acActiveAlarmTable, acActiveAlarmSysuptime=acActiveAlarmSysuptime, acAlarmVarbindsDateAndTime=acAlarmVarbindsDateAndTime, acAlarmVarbindsSeverity=acAlarmVarbindsSeverity, acAlarmVarbindsTextualDescription=acAlarmVarbindsTextualDescription, acActiveAlarmName=acActiveAlarmName, acAlarmVarbindsEventType=acAlarmVarbindsEventType, acActiveAlarmSequenceNumber=acActiveAlarmSequenceNumber, acActiveAlarm=acActiveAlarm, acAlarmHistoryAdditionalInfo2=acAlarmHistoryAdditionalInfo2, acActiveAlarmTextualDescription=acActiveAlarmTextualDescription, acAlarmHistoryProbableCause=acAlarmHistoryProbableCause, acAlarmHistoryAdditionalInfo3=acAlarmHistoryAdditionalInfo3, acActiveAlarmTrapOID=acActiveAlarmTrapOID, acAlarmVarbindsSequenceNumber=acAlarmVarbindsSequenceNumber, acAlarmVarbindsAlarmName=acAlarmVarbindsAlarmName, acAlarmVarbindsAdditionalInfo2=acAlarmVarbindsAdditionalInfo2, acAlarmHistoryTrapOID=acAlarmHistoryTrapOID, acActiveAlarmDateAndTime=acActiveAlarmDateAndTime, acAlarmHistoryDateAndTime=acAlarmHistoryDateAndTime, acAlarmHistoryEntry=acAlarmHistoryEntry, acAlarm=acAlarm, acAlarmHistoryName=acAlarmHistoryName, acActiveAlarmProbableCause=acActiveAlarmProbableCause, acActiveAlarmAdditionalInfo2=acActiveAlarmAdditionalInfo2, acAlarmHistorySource=acAlarmHistorySource, acActiveAlarmEntry=acActiveAlarmEntry, acAlarmHistoryTable=acAlarmHistoryTable, acActiveAlarmAdditionalInfo3=acActiveAlarmAdditionalInfo3, acAlarmHistoryAdditionalInfo1=acAlarmHistoryAdditionalInfo1, acAlarmVarbindsAdditionalInfo1=acAlarmVarbindsAdditionalInfo1, acAlarmVarbindsAdditionalInfo3=acAlarmVarbindsAdditionalInfo3, PYSNMP_MODULE_ID=acAlarm, acActiveAlarmAdditionalInfo1=acActiveAlarmAdditionalInfo1, acAlarmVarbindsProbableCause=acAlarmVarbindsProbableCause, acFault=acFault, acAlarmHistoryTextualDescription=acAlarmHistoryTextualDescription, acAlarmHistorySysuptime=acAlarmHistorySysuptime, acAlarmHistorySeverity=acAlarmHistorySeverity)
(ac_alarm_event_type, ac_alarm_probable_cause, ac_alarm_severity) = mibBuilder.importSymbols('AC-FAULT-TC', 'AcAlarmEventType', 'AcAlarmProbableCause', 'AcAlarmSeverity') (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint') (snmp_engine_id, snmp_admin_string) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (time_ticks, enterprises, module_identity, iso, bits, notification_type, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, ip_address, counter32, gauge32, counter64, object_identity, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'enterprises', 'ModuleIdentity', 'iso', 'Bits', 'NotificationType', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'IpAddress', 'Counter32', 'Gauge32', 'Counter64', 'ObjectIdentity', 'Integer32') (time_stamp, date_and_time, display_string, row_status, truth_value, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'TimeStamp', 'DateAndTime', 'DisplayString', 'RowStatus', 'TruthValue', 'TextualConvention') audio_codes = mib_identifier((1, 3, 6, 1, 4, 1, 5003)) ac_fault = mib_identifier((1, 3, 6, 1, 4, 1, 5003, 11)) ac_alarm = module_identity((1, 3, 6, 1, 4, 1, 5003, 11, 1)) acAlarm.setRevisions(('2003-12-18 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: acAlarm.setRevisionsDescriptions(('4.4. Dec. 18, 2003. Made these changes: o Initial version',)) if mibBuilder.loadTexts: acAlarm.setLastUpdated('200312180000Z') if mibBuilder.loadTexts: acAlarm.setOrganization('Audiocodes') if mibBuilder.loadTexts: acAlarm.setContactInfo('Postal: Support AudioCodes LTD 1 Hayarden Street Airport City Lod 70151, ISRAEL Tel: 972-3-9764000 Fax: 972-3-9764040 Email: support@audiocodes.com Web: www.audiocodes.com') if mibBuilder.loadTexts: acAlarm.setDescription('This MIB defines the enterprise-specific objects needed to support fault management of Audiocodes products. The MIB consists of: o Active alarm table o Alarm history table o Alarm notification varbinds') ac_active_alarm = mib_identifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1)) ac_active_alarm_table = mib_table((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1)) if mibBuilder.loadTexts: acActiveAlarmTable.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTable.setDescription('Table of active alarms.') ac_active_alarm_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1)).setIndexNames((0, 'AcAlarm', 'acActiveAlarmSequenceNumber')) if mibBuilder.loadTexts: acActiveAlarmEntry.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmEntry.setDescription('A conceptual row in the acActiveAlarmTable') ac_active_alarm_sequence_number = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 1), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmSequenceNumber.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSequenceNumber.setDescription('The sequence number of the alarm raise trap.') ac_active_alarm_sysuptime = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 2), time_stamp()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmSysuptime.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSysuptime.setDescription('The value of sysuptime at the time the alarm raise trap was sent') ac_active_alarm_trap_oid = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 3), object_identifier()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmTrapOID.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTrapOID.setDescription('The OID of the notification trap') ac_active_alarm_date_and_time = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 4), date_and_time()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmDateAndTime.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmDateAndTime.setDescription('The date and time at the time the alarm raise trap was sent.') ac_active_alarm_name = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 5), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmName.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmName.setDescription('The name of the alarm that was raised. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') ac_active_alarm_textual_description = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 6), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmTextualDescription.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTextualDescription.setDescription('Text that descries the alarm condition.') ac_active_alarm_source = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 7), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmSource.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSource.setDescription('The component in the system which raised the alarm.') ac_active_alarm_severity = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 8), ac_alarm_severity()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmSeverity.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSeverity.setDescription('The severity of the alarm.') ac_active_alarm_event_type = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 9), ac_alarm_event_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmEventType.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmEventType.setDescription('The event type of the alarm.') ac_active_alarm_probable_cause = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 10), ac_alarm_probable_cause()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmProbableCause.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmProbableCause.setDescription('The probable cause of the alarm.') ac_active_alarm_additional_info1 = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 11), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') ac_active_alarm_additional_info2 = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 12), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') ac_active_alarm_additional_info3 = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 13), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') ac_alarm_history = mib_identifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2)) ac_alarm_history_table = mib_table((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1)) if mibBuilder.loadTexts: acAlarmHistoryTable.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTable.setDescription('A table of all raise-alarm and clear-alarm traps sent by the system. Internal to the system, this table of traps is a fixed size. Once the table reaches this size, older traps are removed to make room for new traps. The size of the table is the value of the nlmConfigLogEntryLimit (NOTIFICATION-LOG-MIB).') ac_alarm_history_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1)).setIndexNames((0, 'AcAlarm', 'acAlarmHistorySequenceNumber')) if mibBuilder.loadTexts: acAlarmHistoryEntry.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryEntry.setDescription('A conceptual row in the acAlarmHistoryTable') ac_alarm_history_sequence_number = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 1), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistorySequenceNumber.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySequenceNumber.setDescription('The sequence number of the alarm raise or clear trap.') ac_alarm_history_sysuptime = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 2), time_stamp()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistorySysuptime.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySysuptime.setDescription('The value of sysuptime at the time the alarm raise or clear trap was sent') ac_alarm_history_trap_oid = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 3), object_identifier()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryTrapOID.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTrapOID.setDescription('The OID of the notification trap') ac_alarm_history_date_and_time = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 4), date_and_time()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryDateAndTime.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryDateAndTime.setDescription('The date and time at the time the alarm raise or clear trap was sent.') ac_alarm_history_name = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 5), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryName.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryName.setDescription('The name of the alarm that was raised or cleared. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') ac_alarm_history_textual_description = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 6), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryTextualDescription.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTextualDescription.setDescription('Text that descries the alarm condition.') ac_alarm_history_source = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 7), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistorySource.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySource.setDescription('The component in the system which raised or cleared the alarm.') ac_alarm_history_severity = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 8), ac_alarm_severity()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistorySeverity.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySeverity.setDescription('The severity of the alarm. A severity of warning, minor, major or critical indicates a raise trap. A severity of cleared indicates a clear trap.') ac_alarm_history_event_type = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 9), ac_alarm_event_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryEventType.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryEventType.setDescription('The event type of the alarm.') ac_alarm_history_probable_cause = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 10), ac_alarm_probable_cause()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryProbableCause.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryProbableCause.setDescription('The probable cause of the alarm.') ac_alarm_history_additional_info1 = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 11), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') ac_alarm_history_additional_info2 = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 12), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') ac_alarm_history_additional_info3 = mib_table_column((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 13), snmp_admin_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') ac_alarm_varbinds = mib_identifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3)) ac_alarm_varbinds_sequence_number = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 1), unsigned32()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsSequenceNumber.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSequenceNumber.setDescription('The sequence number of the alarm raise or clear trap.') ac_alarm_varbinds_date_and_time = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 2), date_and_time()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsDateAndTime.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsDateAndTime.setDescription('The date and time at the time the alarm raise or clear trap was sent.') ac_alarm_varbinds_alarm_name = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 3), unsigned32()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsAlarmName.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAlarmName.setDescription('The name of the alarm that was raised or cleared. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') ac_alarm_varbinds_textual_description = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 4), snmp_admin_string()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsTextualDescription.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsTextualDescription.setDescription('Text that descries the alarm condition.') ac_alarm_varbinds_source = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 5), snmp_admin_string()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsSource.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSource.setDescription('The component in the system which raised or cleared the alarm.') ac_alarm_varbinds_severity = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 6), ac_alarm_severity()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsSeverity.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSeverity.setDescription('The severity of the alarm. A severity of warning, minor, major or critical indicates a raise trap. A severity of cleared indicates a clear trap.') ac_alarm_varbinds_event_type = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 7), ac_alarm_event_type()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsEventType.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsEventType.setDescription('The event type of the alarm.') ac_alarm_varbinds_probable_cause = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 8), ac_alarm_probable_cause()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsProbableCause.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsProbableCause.setDescription('The probable cause of the alarm.') ac_alarm_varbinds_additional_info1 = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 9), snmp_admin_string()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') ac_alarm_varbinds_additional_info2 = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 10), snmp_admin_string()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') ac_alarm_varbinds_additional_info3 = mib_scalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 11), snmp_admin_string()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') mibBuilder.exportSymbols('AcAlarm', acAlarmVarbinds=acAlarmVarbinds, acActiveAlarmSource=acActiveAlarmSource, acActiveAlarmSeverity=acActiveAlarmSeverity, audioCodes=audioCodes, acAlarmHistorySequenceNumber=acAlarmHistorySequenceNumber, acAlarmVarbindsSource=acAlarmVarbindsSource, acAlarmHistory=acAlarmHistory, acActiveAlarmEventType=acActiveAlarmEventType, acAlarmHistoryEventType=acAlarmHistoryEventType, acActiveAlarmTable=acActiveAlarmTable, acActiveAlarmSysuptime=acActiveAlarmSysuptime, acAlarmVarbindsDateAndTime=acAlarmVarbindsDateAndTime, acAlarmVarbindsSeverity=acAlarmVarbindsSeverity, acAlarmVarbindsTextualDescription=acAlarmVarbindsTextualDescription, acActiveAlarmName=acActiveAlarmName, acAlarmVarbindsEventType=acAlarmVarbindsEventType, acActiveAlarmSequenceNumber=acActiveAlarmSequenceNumber, acActiveAlarm=acActiveAlarm, acAlarmHistoryAdditionalInfo2=acAlarmHistoryAdditionalInfo2, acActiveAlarmTextualDescription=acActiveAlarmTextualDescription, acAlarmHistoryProbableCause=acAlarmHistoryProbableCause, acAlarmHistoryAdditionalInfo3=acAlarmHistoryAdditionalInfo3, acActiveAlarmTrapOID=acActiveAlarmTrapOID, acAlarmVarbindsSequenceNumber=acAlarmVarbindsSequenceNumber, acAlarmVarbindsAlarmName=acAlarmVarbindsAlarmName, acAlarmVarbindsAdditionalInfo2=acAlarmVarbindsAdditionalInfo2, acAlarmHistoryTrapOID=acAlarmHistoryTrapOID, acActiveAlarmDateAndTime=acActiveAlarmDateAndTime, acAlarmHistoryDateAndTime=acAlarmHistoryDateAndTime, acAlarmHistoryEntry=acAlarmHistoryEntry, acAlarm=acAlarm, acAlarmHistoryName=acAlarmHistoryName, acActiveAlarmProbableCause=acActiveAlarmProbableCause, acActiveAlarmAdditionalInfo2=acActiveAlarmAdditionalInfo2, acAlarmHistorySource=acAlarmHistorySource, acActiveAlarmEntry=acActiveAlarmEntry, acAlarmHistoryTable=acAlarmHistoryTable, acActiveAlarmAdditionalInfo3=acActiveAlarmAdditionalInfo3, acAlarmHistoryAdditionalInfo1=acAlarmHistoryAdditionalInfo1, acAlarmVarbindsAdditionalInfo1=acAlarmVarbindsAdditionalInfo1, acAlarmVarbindsAdditionalInfo3=acAlarmVarbindsAdditionalInfo3, PYSNMP_MODULE_ID=acAlarm, acActiveAlarmAdditionalInfo1=acActiveAlarmAdditionalInfo1, acAlarmVarbindsProbableCause=acAlarmVarbindsProbableCause, acFault=acFault, acAlarmHistoryTextualDescription=acAlarmHistoryTextualDescription, acAlarmHistorySysuptime=acAlarmHistorySysuptime, acAlarmHistorySeverity=acAlarmHistorySeverity)
"""Set up dependency to tensorflow pip package.""" def _find_tf_include_path(repo_ctx): exec_result = repo_ctx.execute( [ "python3", "-c", "import tensorflow as tf; import sys; " + "sys.stdout.write(tf.sysconfig.get_include())", ], quiet = True, ) if exec_result.return_code != 0: fail("Could not locate tensorflow. Please install TensorFlow pip package first.") return exec_result.stdout.splitlines()[-1] def _find_tf_lib_path(repo_ctx): exec_result = repo_ctx.execute( [ "python3", "-c", "import tensorflow as tf; import sys; " + "sys.stdout.write(tf.sysconfig.get_lib())", ], quiet = True, ) if exec_result.return_code != 0: fail("Could not locate tensorflow. Please install TensorFlow pip package first.") return exec_result.stdout.splitlines()[-1] def _tensorflow_includes_repo_impl(repo_ctx): tf_include_path = _find_tf_include_path(repo_ctx) repo_ctx.symlink(tf_include_path, "tensorflow_includes") repo_ctx.file( "BUILD", content = """ cc_library( name = "includes", hdrs = glob(["tensorflow_includes/**/*.h", "tensorflow_includes/third_party/eigen3/**"]), includes = ["tensorflow_includes"], deps = ["@absl_includes//:includes", "@eigen_archive//:includes", "@protobuf_archive//:includes", "@zlib_includes//:includes",], visibility = ["//visibility:public"], ) """, executable = False, ) def _tensorflow_solib_repo_impl(repo_ctx): tf_lib_path = _find_tf_lib_path(repo_ctx) repo_ctx.symlink(tf_lib_path, "tensorflow_solib") repo_ctx.file( "BUILD", content = """ cc_library( name = "framework_lib", srcs = ["tensorflow_solib/libtensorflow_framework.so.2"], visibility = ["//visibility:public"], ) """, ) def tf_configure(): """Autoconf pre-installed tensorflow pip package.""" make_tfinc_repo = repository_rule( implementation = _tensorflow_includes_repo_impl, ) make_tfinc_repo(name = "tensorflow_includes") make_tflib_repo = repository_rule( implementation = _tensorflow_solib_repo_impl, ) make_tflib_repo(name = "tensorflow_solib")
"""Set up dependency to tensorflow pip package.""" def _find_tf_include_path(repo_ctx): exec_result = repo_ctx.execute(['python3', '-c', 'import tensorflow as tf; import sys; ' + 'sys.stdout.write(tf.sysconfig.get_include())'], quiet=True) if exec_result.return_code != 0: fail('Could not locate tensorflow. Please install TensorFlow pip package first.') return exec_result.stdout.splitlines()[-1] def _find_tf_lib_path(repo_ctx): exec_result = repo_ctx.execute(['python3', '-c', 'import tensorflow as tf; import sys; ' + 'sys.stdout.write(tf.sysconfig.get_lib())'], quiet=True) if exec_result.return_code != 0: fail('Could not locate tensorflow. Please install TensorFlow pip package first.') return exec_result.stdout.splitlines()[-1] def _tensorflow_includes_repo_impl(repo_ctx): tf_include_path = _find_tf_include_path(repo_ctx) repo_ctx.symlink(tf_include_path, 'tensorflow_includes') repo_ctx.file('BUILD', content='\ncc_library(\n name = "includes",\n hdrs = glob(["tensorflow_includes/**/*.h",\n "tensorflow_includes/third_party/eigen3/**"]),\n includes = ["tensorflow_includes"],\n deps = ["@absl_includes//:includes",\n "@eigen_archive//:includes",\n "@protobuf_archive//:includes",\n "@zlib_includes//:includes",],\n visibility = ["//visibility:public"],\n)\n', executable=False) def _tensorflow_solib_repo_impl(repo_ctx): tf_lib_path = _find_tf_lib_path(repo_ctx) repo_ctx.symlink(tf_lib_path, 'tensorflow_solib') repo_ctx.file('BUILD', content='\ncc_library(\n name = "framework_lib",\n srcs = ["tensorflow_solib/libtensorflow_framework.so.2"],\n visibility = ["//visibility:public"],\n)\n') def tf_configure(): """Autoconf pre-installed tensorflow pip package.""" make_tfinc_repo = repository_rule(implementation=_tensorflow_includes_repo_impl) make_tfinc_repo(name='tensorflow_includes') make_tflib_repo = repository_rule(implementation=_tensorflow_solib_repo_impl) make_tflib_repo(name='tensorflow_solib')
''' Processing of data via :py:mod:`.json_io`. Utilities for Excel conversion in :py:mod:`.convert` and :py:mod:`.service_sheet`. Example code in :py:mod:`.cli_examples` and :py:mod:`.plots`. '''
""" Processing of data via :py:mod:`.json_io`. Utilities for Excel conversion in :py:mod:`.convert` and :py:mod:`.service_sheet`. Example code in :py:mod:`.cli_examples` and :py:mod:`.plots`. """
# Create by Packetsss # Personal use is allowed # Commercial use is prohibited name = input("Enter your baphoon:") age = input("Enter your chikka:") print("WTF " + name + "! You are " + age + "??") num1 = input("Number 1:") num2 = input("Number 2:") result = num1 + num2
name = input('Enter your baphoon:') age = input('Enter your chikka:') print('WTF ' + name + '! You are ' + age + '??') num1 = input('Number 1:') num2 = input('Number 2:') result = num1 + num2
####!/usr/bin/env python3 """ Parse data files with json output for estack bulk load """ def elk_index(elk_index_name): """ Index setup for ELK Stack bulk install """ index_tag_full = {} index_tag_inner = {} index_tag_inner['_index'] = elk_index_name index_tag_inner['_type'] = elk_index_name index_tag_full['index'] = index_tag_inner return index_tag_full if __name__ == '__main__': elk_index()
""" Parse data files with json output for estack bulk load """ def elk_index(elk_index_name): """ Index setup for ELK Stack bulk install """ index_tag_full = {} index_tag_inner = {} index_tag_inner['_index'] = elk_index_name index_tag_inner['_type'] = elk_index_name index_tag_full['index'] = index_tag_inner return index_tag_full if __name__ == '__main__': elk_index()