content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# # PySNMP MIB module RADLAN-CDB-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-CDB-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:45:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ...
# atom # : OPEN_PAREN (yield_expr | testlist_comp)? CLOSE_PAREN # | OPEN_BRACKET testlist_comp? CLOSE_BRACKET # | OPEN_BRACE dictorsetmaker? CLOSE_BRACE # | REVERSE_QUOTE testlist COMMA? REVERSE_QUOTE # | dotted_name # | ELLIPSIS # | name # | PRINT # | EXEC # | MINUS? number # ...
() def f(): yield (x, a, q == 1) [] [1, 3, b, p == 1] {} {x: y for (x, y) in a} b.a ... f 90 -1 None '12312313' '1231231123151'
name = "Maciek" age = 22 print("imie:", name, "\nwiek:", age) fovoruite_language = "Python" print(age + 4) fact_or_fiction = 3 < 5 print(fact_or_fiction)
name = 'Maciek' age = 22 print('imie:', name, '\nwiek:', age) fovoruite_language = 'Python' print(age + 4) fact_or_fiction = 3 < 5 print(fact_or_fiction)
# def test_one(): # assert sum([1, 12], 2) == 15 # # # test_one() def my_unit_test(func): def wrapper(a): print(f'my unit test started for {a}') func(a) print('my unit test ended') return wrapper # @my_unit_test # def test_one(a): # assert sum([1, 12], a) == 15 # test_one(1)...
def my_unit_test(func): def wrapper(a): print(f'my unit test started for {a}') func(a) print('my unit test ended') return wrapper @my_unit_test def test_2(a): assert a in [1, 2, 3] test_2(1) my_unit_test(test_2(3))
''' this util is made to validate the subdomains getting added into the hosts if they're like the main subdomain the program is scanning. then it should pass otherwise it shouldn't return anything ''' def vSubdomains(sList, huntingTarget): mainSubdomains = [] for singleSubdomain in sList: if singleSub...
""" this util is made to validate the subdomains getting added into the hosts if they're like the main subdomain the program is scanning. then it should pass otherwise it shouldn't return anything """ def v_subdomains(sList, huntingTarget): main_subdomains = [] for single_subdomain in sList: if singleS...
n = int(input('Enter number: ')) flag = False if n > 1: for i in range(2, int(n**0.5)+1): # we only need to check up to square root if n % i == 0: print(f"{n} divides by {i}") flag = True break if flag: print(n, 'is not a prime number') else: print(n, 'is a prime ...
n = int(input('Enter number: ')) flag = False if n > 1: for i in range(2, int(n ** 0.5) + 1): if n % i == 0: print(f'{n} divides by {i}') flag = True break if flag: print(n, 'is not a prime number') else: print(n, 'is a prime number')
# https://github.com/carpedm20/emoji # http://www.unicode.org/emoji/charts/full-emoji-list.html class Button: Camera = u'\U0001F4F7' FileFolder = u'\U0001F4C1' FileFolderOpen = u'\U0001F4C2' RightArrowUp = u'\U00002934' RightArrowDown = u'\U00002935' CrossMarkRed = u'\U0000274C' CheckMark ...
class Button: camera = u'πŸ“·' file_folder = u'πŸ“' file_folder_open = u'πŸ“‚' right_arrow_up = u'‴' right_arrow_down = u'‡' cross_mark_red = u'❌' check_mark = u'βœ”' check_mark_green = u'βœ…' circle_arrow = u'πŸ”„' question_mark = u'❔' mark_warning = u'⚠' no_entry = u'β›”' like =...
def parse_password_data(string): # This function the password data into the 4 usable components: e.g. "1-9 x: xwjgxtmrzxzmkx" minbound, maxbound, letter, passwords = [], [], [], [] for line in string: firstpart = line.split(sep = '-') secondpart = firstpart[-1].split(sep = ' ', ma...
def parse_password_data(string): (minbound, maxbound, letter, passwords) = ([], [], [], []) for line in string: firstpart = line.split(sep='-') secondpart = firstpart[-1].split(sep=' ', maxsplit=1) thirdpart = secondpart[-1].split(sep=': ') minbound.append(int(firstpart[0])) ...
def indenter(): return " " * 4 def indent(n, lines, start, stop): i = n * indenter() for j in range(start, stop): lines[j] = i + lines[j] return lines def check_shape(shape, typename): if len(shape) == 1 and typename == "Polyvertex": return True if len(shape) != 2: r...
def indenter(): return ' ' * 4 def indent(n, lines, start, stop): i = n * indenter() for j in range(start, stop): lines[j] = i + lines[j] return lines def check_shape(shape, typename): if len(shape) == 1 and typename == 'Polyvertex': return True if len(shape) != 2: retu...
__all__ = [ 'CommandHelpers', 'CommandManager', 'CommandRegistry', 'CommandManagerCallback' ]
__all__ = ['CommandHelpers', 'CommandManager', 'CommandRegistry', 'CommandManagerCallback']
""" Given an integer, n, and n space-separated integers as input, create a tuple, t, of those n integers. Then compute and print the result of hash(t). Note: hash() is one of the functions in the __builtins__ module, so it need not be imported. """ if __name__ == '__main__': n = int(input("Enter the length\n")) ...
""" Given an integer, n, and n space-separated integers as input, create a tuple, t, of those n integers. Then compute and print the result of hash(t). Note: hash() is one of the functions in the __builtins__ module, so it need not be imported. """ if __name__ == '__main__': n = int(input('Enter the length\n')) ...
# ------------------------------------------------------------------------ # File: model_info.py # ------------------------------------------------------------------------ # Licensed Materials - Property of IBM # 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21 # Copyright IBM Corporation 2008, 2020. All ...
"""Modeling information IDs returned by the Callable Library. This module defines symbolic names for the integer modeling information IDs returned by the Callable Library. The names to which the modeling information IDs are assigned are the same names used in the Callable Library, all of which begin with CPXMI. The mo...
def test_checkboxes(env, similar, template, expected): template = env.from_string(template) assert similar(template.render(), expected) def test_checkboxes_with_id_and_name(env, similar, template, expected): template = env.from_string(template) assert similar(template.render(), expected) def test_ch...
def test_checkboxes(env, similar, template, expected): template = env.from_string(template) assert similar(template.render(), expected) def test_checkboxes_with_id_and_name(env, similar, template, expected): template = env.from_string(template) assert similar(template.render(), expected) def test_chec...
with open('assets/day08.txt', 'r') as file: lines = [line for line in file.read().splitlines()] collection = [] for line in lines: inputs, outputs = tuple(line.split('|')) collection.append({ 'input': [digit for digit in inputs.strip().split(' ')], 'output': [digit for digit in outputs.str...
with open('assets/day08.txt', 'r') as file: lines = [line for line in file.read().splitlines()] collection = [] for line in lines: (inputs, outputs) = tuple(line.split('|')) collection.append({'input': [digit for digit in inputs.strip().split(' ')], 'output': [digit for digit in outputs.strip().split(' ')]}...
''' try: f = open('file1.txt', 'r') except IOError: print('Problem with Input Output...\n') else: print('No Problem with Input Output...') ''' try: f = open('file1.txt', 'w') except IOError: print('Problem with Input Output...\n') else: print('No Problem with Input Output...')
""" try: f = open('file1.txt', 'r') except IOError: print('Problem with Input Output... ') else: print('No Problem with Input Output...') """ try: f = open('file1.txt', 'w') except IOError: print('Problem with Input Output...\n') else: print('No Problem with Input Output...')
lines_colors = [ "Red", "DodgerBlue", "LimeGreen", "Gold", "MediumSlateBlue", "Brown", "Olive", "Orange", "DarkGoldenRod", "Salmon", "Fuchsia", "Aqua", "LightSlateGray", "MediumBlue", "GreenYellow", "DarkRed", "DarkMagenta", "Khaki", "MediumSp...
lines_colors = ['Red', 'DodgerBlue', 'LimeGreen', 'Gold', 'MediumSlateBlue', 'Brown', 'Olive', 'Orange', 'DarkGoldenRod', 'Salmon', 'Fuchsia', 'Aqua', 'LightSlateGray', 'MediumBlue', 'GreenYellow', 'DarkRed', 'DarkMagenta', 'Khaki', 'MediumSpringGreen', 'OrangeRed', 'DarkGreen', 'LightPink', 'DarkSlateBlue', 'Yellow', ...
#main class class Characters: def __init__(self, name="none", lastname="none", age="none", hp="50", title="none", language="none", race="human or unknown", weakness="none" ...
class Characters: def __init__(self, name='none', lastname='none', age='none', hp='50', title='none', language='none', race='human or unknown', weakness='none'): self.name = name self.lastname = lastname self.age = age self.hp = hp self.title = title self.race = race...
#!/usr/bin/python3 # -*- coding: utf-8 -*- class SimParameters(object): def __init__(self): self.run_time = 0 self.name = "default" def debug(self): print('SimParameters instance :') print('---------------------------------------------------')
class Simparameters(object): def __init__(self): self.run_time = 0 self.name = 'default' def debug(self): print('SimParameters instance :') print('---------------------------------------------------')
class Digit(object): def __init__(self, representation): self._digit_representation = representation def scale(self, scale_factor=1): if scale_factor == 1: return self scaled_lines = [] for line in self._digit_representation: scaled_lines.append(line[0] +...
class Digit(object): def __init__(self, representation): self._digit_representation = representation def scale(self, scale_factor=1): if scale_factor == 1: return self scaled_lines = [] for line in self._digit_representation: scaled_lines.append(line[0] ...
def mult(m,n): ans = 0 while n>0: ans+=m n-=1 return ans
def mult(m, n): ans = 0 while n > 0: ans += m n -= 1 return ans
loci = 20000000 #!!! sample = 26 mu = 2e-6 rr = 1.05e-6 Na = 1000 Bt = 67
loci = 20000000 sample = 26 mu = 2e-06 rr = 1.05e-06 na = 1000 bt = 67
# # PySNMP MIB module ELTEX-MES-SMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-SMON-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:01:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ...
try: number=float(input("Enter a number between 0.0 and 1.0: ")) if number < 0 or number > 1: print("Bad score!") elif number >= 0.9: print("A") elif number >= 0.8: print("B") elif number >= 0.7: print("C") elif number >= 0.6: print("D") else: print("F") except: print("Bad score!")
try: number = float(input('Enter a number between 0.0 and 1.0: ')) if number < 0 or number > 1: print('Bad score!') elif number >= 0.9: print('A') elif number >= 0.8: print('B') elif number >= 0.7: print('C') elif number >= 0.6: print('D') else: ...
""" class BinaryTreeNode(object): def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(v...
""" class BinaryTreeNode(object): def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(v...
# Any or All # Problem Link: https://www.hackerrank.com/challenges/any-or-all/problem _ = int(input()) l = input().split() print(all([int(i) > 0 for i in l]) and any([j == j[::-1] for j in l]))
_ = int(input()) l = input().split() print(all([int(i) > 0 for i in l]) and any([j == j[::-1] for j in l]))
print(2 not in [1,2,3]) print(2 not in [4,5]) print(1 not in [1] not in [[1]]) print(3 not in [1] not in [[1]])
print(2 not in [1, 2, 3]) print(2 not in [4, 5]) print(1 not in [1] not in [[1]]) print(3 not in [1] not in [[1]])
def sum_of_numbers_in_an_integer(num): answer = 0 while num > 0: last_num = num % 10 num = num // 10 answer += last_num print(answer) def main(): num = int(input("Enter a number: " )) sum_of_numbers_in_an_integer(num) main()
def sum_of_numbers_in_an_integer(num): answer = 0 while num > 0: last_num = num % 10 num = num // 10 answer += last_num print(answer) def main(): num = int(input('Enter a number: ')) sum_of_numbers_in_an_integer(num) main()
''' Created on 2017. 4. 12. @author: Byoungho Kang ''' class Calculator: def __init__(self, first, second): self.first = first self.second = second def plus(self): return self.first + self.second def minus(self): return self.first - self.s...
""" Created on 2017. 4. 12. @author: Byoungho Kang """ class Calculator: def __init__(self, first, second): self.first = first self.second = second def plus(self): return self.first + self.second def minus(self): return self.first - self.second def multiply(self): ...
#Questao 9 fila = [] print("Fila: ", fila) fila.append("Tarefa E") print("Inserindo um elemento no final da fila: ", fila) fila.append("Tarefa I") print("Inserindo outro elemento no final da fila: ", fila) fila.append("Tarefa C") print("Inserindo outro elemento no final da fila: ", fila) fila.append("Tarefa F") pri...
fila = [] print('Fila: ', fila) fila.append('Tarefa E') print('Inserindo um elemento no final da fila: ', fila) fila.append('Tarefa I') print('Inserindo outro elemento no final da fila: ', fila) fila.append('Tarefa C') print('Inserindo outro elemento no final da fila: ', fila) fila.append('Tarefa F') print('Inserindo o...
def hello(verb, path, query): return "Server received your " + verb + " request" + str(query) + "\r\n" def register(urlMapper): urlMapper["/hello"] = hello
def hello(verb, path, query): return 'Server received your ' + verb + ' request' + str(query) + '\r\n' def register(urlMapper): urlMapper['/hello'] = hello
""" Copyright (c) Facebook, Inc. and its affiliates. """ BEFORE = """ <!-- Bootstrap v3.0.3 --> <link href="https://s3.amazonaws.com/mturk-public/bs30/css/bootstrap.min.css" rel="stylesheet" /> <section class="container" id="Other" style="margin-bottom:15px; padding: 10px 10px; font-family: Verdana, Geneva, sans-seri...
""" Copyright (c) Facebook, Inc. and its affiliates. """ before = '\n<!-- Bootstrap v3.0.3 -->\n<link href="https://s3.amazonaws.com/mturk-public/bs30/css/bootstrap.min.css" rel="stylesheet" />\n<section class="container" id="Other" style="margin-bottom:15px; padding: 10px 10px;\n font-family: Verdana, Geneva, sans-se...
class Logger(object): """ La classe modellizza un logger, per generare un file di testo di output """ def __init__(self, fp): self.fp = open(fp, 'w') def log(self, msg): self.fp.write(msg + '\n') def close(self): self.fp.close()
class Logger(object): """ La classe modellizza un logger, per generare un file di testo di output """ def __init__(self, fp): self.fp = open(fp, 'w') def log(self, msg): self.fp.write(msg + '\n') def close(self): self.fp.close()
#!/usr/bin/python # -*- coding: utf-8 -*- # cython: language_level=2, boundscheck=False class NoValidVersion(Exception): pass class VersionZero(Exception): pass class ExceededPaddingVersion(Exception): pass class NoVersionNumber(Exception): pass
class Novalidversion(Exception): pass class Versionzero(Exception): pass class Exceededpaddingversion(Exception): pass class Noversionnumber(Exception): pass
""" Various container utilities """ def get_from_dict(d, path): """ Extract a value pointed by ``path`` from a nested dict. Example: >>> d = { ... "path": { ... "to": { ... "item": "value" ... } ... } ... } >>> get_from_dict(d, "/path/to...
""" Various container utilities """ def get_from_dict(d, path): """ Extract a value pointed by ``path`` from a nested dict. Example: >>> d = { ... "path": { ... "to": { ... "item": "value" ... } ... } ... } >>> get_from_dict(d, "/path/to/...
name = input("[>] Enter name: ") email = input("[>] Enter email: ") if "@" not in name and "@" in email: print("[+] OK") elif "@" not in name and "@" not in email: print("[-] Incorrect email") elif "@" in name and "@" in email: print("[-] Incorrect login") elif "@" in name and "@" not in email: print("...
name = input('[>] Enter name: ') email = input('[>] Enter email: ') if '@' not in name and '@' in email: print('[+] OK') elif '@' not in name and '@' not in email: print('[-] Incorrect email') elif '@' in name and '@' in email: print('[-] Incorrect login') elif '@' in name and '@' not in email: print('[...
# # PySNMP MIB module CISCO-ROUTE-POLICIES-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ROUTE-POLICIES-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:54:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) ...
# Copyright 2018-2020 Stanislav Pidhorskyi # # 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 i...
def find_maximum(f, min_x, max_x, epsilon=1e-05): def binary_search(l, r, fl, fr, epsilon): mid = l + (r - l) / 2 fm = f(mid) binary_search.eval_count += 1 if fm == fl and fm == fr or r - l < epsilon: return (mid, fm) if fl > fm >= fr: return binary_s...
class GPIOBus(object): """ This is a helper class for when your pins don't line up with ports. """ def __init__(self, pins): self.pins = pins self.width = len(pins) self.max = pow(2, len(pins)) - 1 def write(self, value): if value > self.max: raise AttributeErro...
class Gpiobus(object): """ This is a helper class for when your pins don't line up with ports. """ def __init__(self, pins): self.pins = pins self.width = len(pins) self.max = pow(2, len(pins)) - 1 def write(self, value): if value > self.max: raise attribute_err...
#!/usr/bin/env python3 ''' homework/data_structure/1_17_k_fib.py count the $(m)th $(k)-Fibonacci number with time complexity of O(n) ''' class FibCache: ''' Acts like heap? Make sure you DON'T re-use the instance! ''' def __init__(self, k): ''' initialize FibCache instance...
""" homework/data_structure/1_17_k_fib.py count the $(m)th $(k)-Fibonacci number with time complexity of O(n) """ class Fibcache: """ Acts like heap? Make sure you DON'T re-use the instance! """ def __init__(self, k): """ initialize FibCache instance """ self._max_size ...
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for number in numbers: # Lewatkan loop untuk angka yang dapat di bagi 3 if number % 3 == 0: continue print(number)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for number in numbers: if number % 3 == 0: continue print(number)
# Conner Skoumal # Matchmaker Lite print("") print("Matchmaker 2021") print("") print("[[Your instruction here.]]") print("") userResponse1 = int(input("Ironclad Robotics rocks!")) desiredResponse1 = 5 compatibility1 = 5 - abs(userResponse1 - desiredResponse1) print("Question 1 Compatibility: " + str(compatibility1))...
print('') print('Matchmaker 2021') print('') print('[[Your instruction here.]]') print('') user_response1 = int(input('Ironclad Robotics rocks!')) desired_response1 = 5 compatibility1 = 5 - abs(userResponse1 - desiredResponse1) print('Question 1 Compatibility: ' + str(compatibility1)) print('') user_response2 = int(inp...
def main(): print("Please enter a sentence: ") user_sentence = input() str_for_checking = prepare_str_for_palindrome_checking(user_sentence) res = is_palindrome(str_for_checking) if(res == True): print("Your sentence is a palindrome") else: print(("Your sentence is not a palindro...
def main(): print('Please enter a sentence: ') user_sentence = input() str_for_checking = prepare_str_for_palindrome_checking(user_sentence) res = is_palindrome(str_for_checking) if res == True: print('Your sentence is a palindrome') else: print('Your sentence is not a palindrome...
#kpbochenek@gmail.com def swap_sort(array): array = list(array[:]) result = [] for i in range(1, len(array)): j = i-1 k = i while j >= 0 and array[j] > array[k]: array[k], array[j] = array[j], array[k] result.append("%d%d" % (j, k)) j -= 1 ...
def swap_sort(array): array = list(array[:]) result = [] for i in range(1, len(array)): j = i - 1 k = i while j >= 0 and array[j] > array[k]: (array[k], array[j]) = (array[j], array[k]) result.append('%d%d' % (j, k)) j -= 1 k -= 1 r...
name = "Fahad Hafeez" print(len(name)) if len(name) < 3: print("Name must be at least 3 characters long") elif len(name) > 50: print("Name must be a maximum of 50 characters long") else: print("Name looks good")
name = 'Fahad Hafeez' print(len(name)) if len(name) < 3: print('Name must be at least 3 characters long') elif len(name) > 50: print('Name must be a maximum of 50 characters long') else: print('Name looks good')
#!/usr/bin/env python3 def MakeCaseAgnostic(choices): def find_choice(choice): for key, item in enumerate(choice.lower() for choice in choices): if choice.lower() == item: return choices[key] return choice return find_choice
def make_case_agnostic(choices): def find_choice(choice): for (key, item) in enumerate((choice.lower() for choice in choices)): if choice.lower() == item: return choices[key] return choice return find_choice
class Config(object): def __init__(self): # model params self.model = "AR" self.nsteps = 10 # equivalent to x_len self.msteps = 7 self.nbins = 4 self.attention_size = 16 self.num_filters = 32 self.kernel_sizes = [3] self.l2_lambda = 1e-3...
class Config(object): def __init__(self): self.model = 'AR' self.nsteps = 10 self.msteps = 7 self.nbins = 4 self.attention_size = 16 self.num_filters = 32 self.kernel_sizes = [3] self.l2_lambda = 0.001 self.hidden_units = 512 self.num_...
# General info COMPANY_NAME = "Shore East" SITENAME = "Cloudy Memory" EMAIL_PREFIX = "[ %s ] " % SITENAME APPNAME = "cloudmemory-app" BASE = "http://%s.appspot.com" % APPNAME API_AUTH = "waywayb4ck" PLAY_STORE_LINK = "" DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] # Branding...
company_name = 'Shore East' sitename = 'Cloudy Memory' email_prefix = '[ %s ] ' % SITENAME appname = 'cloudmemory-app' base = 'http://%s.appspot.com' % APPNAME api_auth = 'waywayb4ck' play_store_link = '' days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] cl_primary = '#409777' cl_pri...
# # PySNMP MIB module HUAWEI-MUSA-MA5100-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-MUSA-MA5100-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:32:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) ...
class WeightRegularizerMixin: def __init__(self, regularizer=None, reg_weight=1, **kwargs): super().__init__(**kwargs) self.regularizer = regularizer self.reg_weight = reg_weight def regularization_loss(self, weights): if self.regularizer is None: return 0 ...
class Weightregularizermixin: def __init__(self, regularizer=None, reg_weight=1, **kwargs): super().__init__(**kwargs) self.regularizer = regularizer self.reg_weight = reg_weight def regularization_loss(self, weights): if self.regularizer is None: return 0 r...
def whatday(num): if num == 1: return "Sunday" elif num == 2: return "Monday" elif num == 3: return "Tuesday" elif num == 4: return "Wednesday" elif num == 5: return "Thursday" elif num == 6: return "Friday" elif num == 7: return "Saturday" else: return "W...
def whatday(num): if num == 1: return 'Sunday' elif num == 2: return 'Monday' elif num == 3: return 'Tuesday' elif num == 4: return 'Wednesday' elif num == 5: return 'Thursday' elif num == 6: return 'Friday' elif num == 7: return 'Satur...
# rects using framebuf display.fill(0) for i in range(0, 15): j = 6 * i display.framebuf.fill_rect(j, j, 12, 12, i) display.framebuf.rect(90 - (j), j, 12, 12, i) display.show()
display.fill(0) for i in range(0, 15): j = 6 * i display.framebuf.fill_rect(j, j, 12, 12, i) display.framebuf.rect(90 - j, j, 12, 12, i) display.show()
wildcards = dict() ## experiments x params x wildcards['/lustre/projects/project-broaddus/denoise_experiments/flower/e01/n2v2/'] = "mask_{n}_{m}/table.csv" wildcards['/lustre/projects/project-broaddus/denoise_experiments/flower/e01/n2gt/'] = "d{a}/table.csv" wildcards['/lustre/projects/project-broaddus/denoise_experi...
wildcards = dict() wildcards['/lustre/projects/project-broaddus/denoise_experiments/flower/e01/n2v2/'] = 'mask_{n}_{m}/table.csv' wildcards['/lustre/projects/project-broaddus/denoise_experiments/flower/e01/n2gt/'] = 'd{a}/table.csv' wildcards['/lustre/projects/project-broaddus/denoise_experiments/flower/e01/nlm/'] = 'd...
class AlmaException(Exception): class_message = "An exception occurred." def __init__(self, message=None, **kwargs): if message: self._message = message % kwargs else: self._message = self.class_message % kwargs def __repr__(self): return self._message ...
class Almaexception(Exception): class_message = 'An exception occurred.' def __init__(self, message=None, **kwargs): if message: self._message = message % kwargs else: self._message = self.class_message % kwargs def __repr__(self): return self._message ...
def test_get_wallet_not_authenticated(api_client): rsp = api_client.get("/api/wallet/") assert rsp.status_code == 401 def test_get_wallet_success(api_client, wallet): api_client.force_authenticate(wallet.user) rsp = api_client.get("/api/wallet/") assert rsp.status_code == 200 print(rsp.cont...
def test_get_wallet_not_authenticated(api_client): rsp = api_client.get('/api/wallet/') assert rsp.status_code == 401 def test_get_wallet_success(api_client, wallet): api_client.force_authenticate(wallet.user) rsp = api_client.get('/api/wallet/') assert rsp.status_code == 200 print(rsp.content)...
STARTING_CHAR_FOR_SHAPE_NAME = "@" class Shape(object): def __init__(self, name, class_uri, statements): self._name = name self._class_uri = class_uri self._statements = statements @property def name(self): return self._name @property def class_uri(self): ...
starting_char_for_shape_name = '@' class Shape(object): def __init__(self, name, class_uri, statements): self._name = name self._class_uri = class_uri self._statements = statements @property def name(self): return self._name @property def class_uri(self): ...
# # PySNMP MIB module CXLlcFrConv-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXLlcFrConv-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:33:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ...
number = int(input("Input an int: ")) oddNum = 1 for x in range(number): print(oddNum) oddNum += 2
number = int(input('Input an int: ')) odd_num = 1 for x in range(number): print(oddNum) odd_num += 2
""" Tema: Listas, mutabilidad y clonacion. Curso: Pensamiento computacional. Plataforma: Platzi. Profesor: David Aroesti. Alumno: @edinsonrequena. """ a = [1, 2, 3] b = a print(b) print(id(a)) # Aca podemos ver como a y b estan en el mismo lugar de print(id(b)) # memoria, lo que quiere decir que son la misma lista....
""" Tema: Listas, mutabilidad y clonacion. Curso: Pensamiento computacional. Plataforma: Platzi. Profesor: David Aroesti. Alumno: @edinsonrequena. """ a = [1, 2, 3] b = a print(b) print(id(a)) print(id(b)) c = list(a) print(c) print(id(c)) a.append(5) print(a) print(c) d = a[:] print(d) print(id(d)) e = a[0:2] print(...
"""Top-level package for webml.""" __author__ = """BlueML AI""" __email__ = 'james.liang.cje@gmail.com' __version__ = '0.1.0'
"""Top-level package for webml.""" __author__ = 'BlueML AI' __email__ = 'james.liang.cje@gmail.com' __version__ = '0.1.0'
''' Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None...
""" Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. """ class Treenode(object): def __init__(self, val=0, left=None, right=None): self.val = val sel...
class IridaConnectionError(Exception): """ This error is thrown when the api cannot connect to the IRIDA api Either the server is unreachable or the credentials are invalid All calls to the api should expect this error """ pass
class Iridaconnectionerror(Exception): """ This error is thrown when the api cannot connect to the IRIDA api Either the server is unreachable or the credentials are invalid All calls to the api should expect this error """ pass
set1 = set() set1.add(1) set1.add(3) set1.add(1) set1.add(2) print(set1) set2 = set([1, 3, 5, 7, 9]) print(set2) # union print(set1 | set2) # intersection print(set1 & set2) # difference print(set1 - set2) set3 = {"a", "b"} print(set3) # immutable set set4 = frozenset([9, 10])
set1 = set() set1.add(1) set1.add(3) set1.add(1) set1.add(2) print(set1) set2 = set([1, 3, 5, 7, 9]) print(set2) print(set1 | set2) print(set1 & set2) print(set1 - set2) set3 = {'a', 'b'} print(set3) set4 = frozenset([9, 10])
"""Setting file for the Cloud SQL guestbook""" CLOUDSQL_INSTANCE = 'ReplaceWithYourInstanceName' DATABASE_NAME = 'guestbook' USER_NAME = 'ReplaceWithYourDatabaseUserName' PASSWORD = 'ReplaceWithYourDatabasePassword'
"""Setting file for the Cloud SQL guestbook""" cloudsql_instance = 'ReplaceWithYourInstanceName' database_name = 'guestbook' user_name = 'ReplaceWithYourDatabaseUserName' password = 'ReplaceWithYourDatabasePassword'
# -------------- class_1=['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2=['Hilary Mason','Carla Gentry', 'Corinna Cortes'] new_class=class_1+class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) courses={'Math'...
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) courses = {'Math': 65, 'English...
def combo(ls, c): if c == 0: return [[]] l =[] for i in range(0, len(ls)): m = ls[i] remLst = ls[i + 1:] for p in combo(remLst, c-1): l.append([m]+p) return l a =str("input") n =int(input("combo :")) list_1 =...
def combo(ls, c): if c == 0: return [[]] l = [] for i in range(0, len(ls)): m = ls[i] rem_lst = ls[i + 1:] for p in combo(remLst, c - 1): l.append([m] + p) return l a = str('input') n = int(input('combo :')) list_1 = [i for i in a] print('combination :', combo...
""" Sample module docstring """ def world(): """ Sample function docstring """ print('world')
""" Sample module docstring """ def world(): """ Sample function docstring """ print('world')
# https://www.hackerrank.com/challenges/strange-code/problem def strangeCounter(t): k = 3 while t > k: t -= k k *= 2 return k - t + 1 if __name__ == '__main__': t0 = 6 assert strangeCounter(t0) == 4
def strange_counter(t): k = 3 while t > k: t -= k k *= 2 return k - t + 1 if __name__ == '__main__': t0 = 6 assert strange_counter(t0) == 4
SECRET_KEY = 'fake-key' INSTALLED_APPS = [ 'django_mercadopago', 'tests', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'djang...
secret_key = 'fake-key' installed_apps = ['django_mercadopago', 'tests'] middleware = ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.Me...
def print_name(firstName, lastName, reverse=False): """ :param firstName: String first name :param lastName: String last name :param reverse: boolean :return: None """ if reverse: print(lastName, ',', firstName) else: print(firstName, lastName) print_name("Eric", "Gr...
def print_name(firstName, lastName, reverse=False): """ :param firstName: String first name :param lastName: String last name :param reverse: boolean :return: None """ if reverse: print(lastName, ',', firstName) else: print(firstName, lastName) print_name('Eric', 'Grims...
class PrivateMessage: def __init__(self, type, author, body, filename=None, waID=None, tgID=None): self.type = type self.author = author self.body = body self.waID = waID self.tgID = tgID self.filename = filename class GroupMessage: def __init__(self, type, auth...
class Privatemessage: def __init__(self, type, author, body, filename=None, waID=None, tgID=None): self.type = type self.author = author self.body = body self.waID = waID self.tgID = tgID self.filename = filename class Groupmessage: def __init__(self, type, aut...
# Create phone number def create_phone_number(n): full_str = ''.join([str(numb) for numb in x]) return f'({full_str[0:3]})' + ' ' + f'{full_str[3:6]}' + '-' + f'{full_str[6:10]}' def create_phone_number_2(x): phone_number = "({}{}{}) {}{}{}-{}{}{}{}".format(*x) return phone_...
def create_phone_number(n): full_str = ''.join([str(numb) for numb in x]) return f'({full_str[0:3]})' + ' ' + f'{full_str[3:6]}' + '-' + f'{full_str[6:10]}' def create_phone_number_2(x): phone_number = '({}{}{}) {}{}{}-{}{}{}{}'.format(*x) return phone_number
# -*- coding: utf-8 -*- def shape(src_str, prefix_str, suffix_str): prefix_pos = src_str.find(prefix_str); if prefix_pos == -1: return None; #endif prefix_pos = prefix_pos + len(prefix_str); temp_str = src_str[prefix_pos:]; suffix_pos = temp_str.find(suffix_str); if suffix_pos == -1: return None; #e...
def shape(src_str, prefix_str, suffix_str): prefix_pos = src_str.find(prefix_str) if prefix_pos == -1: return None prefix_pos = prefix_pos + len(prefix_str) temp_str = src_str[prefix_pos:] suffix_pos = temp_str.find(suffix_str) if suffix_pos == -1: return None dest_str = temp...
fileout = open("makeshingles.sh", "w") for i in range(1,57): if i >= 10: s = "0" + str(i) else: s = "00" + str(i) fileout.write("./a.out TEMPF/OUT-" + s + ".txt TEMPK/KEYWORDS-" + s + ".txt\n") fileout.close()
fileout = open('makeshingles.sh', 'w') for i in range(1, 57): if i >= 10: s = '0' + str(i) else: s = '00' + str(i) fileout.write('./a.out TEMPF/OUT-' + s + '.txt TEMPK/KEYWORDS-' + s + '.txt\n') fileout.close()
""" n & (n - 1) == 0 """ class Solution(object): def isPowerOfTwo(self, n): if n == 0: return False return n & (n - 1) == 0 """ n&(-n) == n """ class Solution(object): def isPowerOfTwo(self, n): if n == 0: return False return n & (-n) == n """ log N...
""" n & (n - 1) == 0 """ class Solution(object): def is_power_of_two(self, n): if n == 0: return False return n & n - 1 == 0 '\n\nn&(-n) == n\n\n' class Solution(object): def is_power_of_two(self, n): if n == 0: return False return n & -n == n '\n\nl...
# 0: 1: 2: 3: 4: # aaaa .... aaaa aaaa .... # b c . c . c . c b c # b c . c . c . c b c # .... .... dddd dddd dddd # e f . f e . . f . f # e f . f e . . f . f # gggg .... gggg gggg .....
with open('input') as f: values = [line.split(' | ') for line in f.read().strip().split('\n')] count = 0 for (_, outputs) in values: for o in outputs.split(): count += len(o) in (2, 3, 4, 7) print(count) mapping = {'abcefg': '0', 'cf': '1', 'acdeg': '2', 'acdfg': '3', 'bcdf': '4', 'abdfg': '5', 'abdefg'...
class Error (Exception): pass class NotEnoughPlayersError (Error): """ when too many cards have been drawn """ def __init__(self, message): self.message = "must have more than one player!" class BetTooSmallError (Error): """ too little has been bet """ def __init__(self, messag...
class Error(Exception): pass class Notenoughplayerserror(Error): """ when too many cards have been drawn """ def __init__(self, message): self.message = 'must have more than one player!' class Bettoosmallerror(Error): """ too little has been bet """ def __init__(self, message): ...
def subset(array,n,ans): subs = [None]*n helper(n,array,subs,0,ans) return ans def helper(n,array,subs,i,ans): if i==n: lis=[] if any(subs): for j in range(len(subs)): if subs[j]!=None: lis.append(subs[j]) ans.append(lis) ...
def subset(array, n, ans): subs = [None] * n helper(n, array, subs, 0, ans) return ans def helper(n, array, subs, i, ans): if i == n: lis = [] if any(subs): for j in range(len(subs)): if subs[j] != None: lis.append(subs[j]) ans...
while True: username = input("Enter username: ") if username == 'pypy': break else: continue
while True: username = input('Enter username: ') if username == 'pypy': break else: continue
lados = [float(x) for x in input().split()] lados.sort() lados = lados[::-1] a, b, c = list(lados) if a >= b + c: print('NAO FORMA TRIANGULO') else: if a ** 2 == b ** 2 + c ** 2: print('TRIANGULO RETANGULO') if a ** 2 > b ** 2 + c ** 2: print('TRIANGULO OBTUSANGULO') if a ** 2 < b ** 2 ...
lados = [float(x) for x in input().split()] lados.sort() lados = lados[::-1] (a, b, c) = list(lados) if a >= b + c: print('NAO FORMA TRIANGULO') else: if a ** 2 == b ** 2 + c ** 2: print('TRIANGULO RETANGULO') if a ** 2 > b ** 2 + c ** 2: print('TRIANGULO OBTUSANGULO') if a ** 2 < b ** 2...
char = [] string = "ppphhpphhppppphhhhhhhpphhpppphhpphpp" for i in range(len(string)): if string[i] == 'p' or string[i] == 'P': char.append('P') else: char.append('H') print(char)
char = [] string = 'ppphhpphhppppphhhhhhhpphhpppphhpphpp' for i in range(len(string)): if string[i] == 'p' or string[i] == 'P': char.append('P') else: char.append('H') print(char)
def pal(p): # str.isalpha is function form of the method .isalpha() np = list(filter(str.isalpha, p.lower())) # remove non-letters return np == np[::-1] and len(np) > 0 # check if palindrome # py.test exercise_10_26_16.py --cov=exercise_10_26_16.py --cov-report=html def test_pal(): assert pal('mom') ...
def pal(p): np = list(filter(str.isalpha, p.lower())) return np == np[::-1] and len(np) > 0 def test_pal(): assert pal('mom') assert pal('dog') is False assert pal('9874^&') is False assert pal("Go hang a salami I'm a lasagna hog.") if __name__ == '__main__': t = input('Text: ') print(p...
class ParkingSystem: # # Instance Variables (Accepted), O(1) time, O(1) space wrt addCar # def __init__(self, big: int, medium: int, small: int): # self.big = big # self.medium = medium # self.small = small # def addCar(self, carType: int) -> bool: # if carType == 1: # ...
class Parkingsystem: def __init__(self, big, medium, small): self.A = [big, medium, small] def add_car(self, carType): self.A[carType - 1] -= 1 return self.A[carType - 1] >= 0
numero = int(input("Introduzca el numero= ")) if numero >= 10: numero *= 3 print(numero) else: numero *=4 print(numero)
numero = int(input('Introduzca el numero= ')) if numero >= 10: numero *= 3 print(numero) else: numero *= 4 print(numero)
#Week1 #Exercise 1: Use input to ask name, age, and hometown. #Print Hello, my name is {}. I am {} years old and I live in {} name=input("Enter your name: ") age=input("Enter your age: ") hometown=input("Enter your hometown: ") print("Hello, my name is {}. I am {} years old and I live in {}".format(name, age, hometown)...
name = input('Enter your name: ') age = input('Enter your age: ') hometown = input('Enter your hometown: ') print('Hello, my name is {}. I am {} years old and I live in {}'.format(name, age, hometown)) number1 = float(input('Enter your number1: ')) number2 = float(input('Enter your number2: ')) number3 = float(input('E...
class Solution: def binaryGap(self, N): """ :type N: int :rtype: int """ dis = 0 last = 0 now = 1 while N > 0: bit = N & 0x01 if bit == 1 and last == 0: last = now elif bit == 1: dis...
class Solution: def binary_gap(self, N): """ :type N: int :rtype: int """ dis = 0 last = 0 now = 1 while N > 0: bit = N & 1 if bit == 1 and last == 0: last = now elif bit == 1: dis = ...
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '\x126h\x8d\xec\x81\xa9\x13 O\x084\xd7\xbc\xd3\x17' _lr_action_items = {'RPAREN':([1,2,4,8,11,12,13,14,15,],[-1,-7,-6,13,-5,-4,-8,-2,-3,]),'DIVIDE':([1,2,4,11,12,13,14,15,],[6,-7,-6,-5,-4,-...
_tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '\x126h\x8dì\x81©\x13 O\x084×¼Ó\x17' _lr_action_items = {'RPAREN': ([1, 2, 4, 8, 11, 12, 13, 14, 15], [-1, -7, -6, 13, -5, -4, -8, -2, -3]), 'DIVIDE': ([1, 2, 4, 11, 12, 13, 14, 15], [6, -7, -6, -5, -4, -8, 6, 6]), 'NUMBER': ([0, 3, 6, 7, 9, 10], [2, 2, 2, 2, 2, 2...
# https://leetcode.com/problems/license-key-formatting/ class Solution: def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = ''.join(s.upper() for s in S if s.isalnum()) first_group = len(S) % K out = [] is...
class Solution: def license_key_formatting(self, S, K): """ :type S: str :type K: int :rtype: str """ s = ''.join((s.upper() for s in S if s.isalnum())) first_group = len(S) % K out = [] is_first_group = first_group > 0 i = 0 f...
# # PySNMP MIB module PDN-SYSLOG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-SYSLOG-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:30:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ...
BASE_NAME = "GTR Tool Rack Stereo" BUFFER_SIZE = 255 def main(): log('\n') # Get the track name proj_index = 0 track_index = 0 track = RPR_GetTrack(proj_index, track_index) response = RPR_GetSetMediaTrackInfo_String(track, 'P_NAME', '', False) (succeeded, track, param_name, track_name, set_...
base_name = 'GTR Tool Rack Stereo' buffer_size = 255 def main(): log('\n') proj_index = 0 track_index = 0 track = rpr__get_track(proj_index, track_index) response = rpr__get_set_media_track_info__string(track, 'P_NAME', '', False) (succeeded, track, param_name, track_name, set_new_value) = resp...
""" notation_instances.py """ population = [{ 'Name': 'Shlaer-Mellor', 'About': 'Source of Executable UML / xUML modeling semantics', 'Why use it': 'Designed for fast easy hand drawing.Great for whiteboards and notes!' }, { 'Name': 'Starr', 'About': 'Stealth mode! Mimimal drawing clutter to put the...
""" notation_instances.py """ population = [{'Name': 'Shlaer-Mellor', 'About': 'Source of Executable UML / xUML modeling semantics', 'Why use it': 'Designed for fast easy hand drawing.Great for whiteboards and notes!'}, {'Name': 'Starr', 'About': 'Stealth mode! Mimimal drawing clutter to put the focus on the subject. E...
def isPrime(n): # 1 is not a prime number by definition if n < 2: return False return sum(d for d in xrange(2, n) if n % d == 0) == 0 def UnitTests(): assert isPrime(1) == False assert isPrime(2) == True assert isPrime(3) == True assert isPrime(4) == False assert isPrime(13) == True assert isPrime(23) == ...
def is_prime(n): if n < 2: return False return sum((d for d in xrange(2, n) if n % d == 0)) == 0 def unit_tests(): assert is_prime(1) == False assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(13) == True assert is_prime(23) == Tru...
# pylint: disable=missing-module-docstring __all__ = [ 'conftest', 'standard', 'test_main_layout', 'test_root_index', 'utils', ]
__all__ = ['conftest', 'standard', 'test_main_layout', 'test_root_index', 'utils']
# Check input files to see if 200 sample id's match def main(): file_a = "1kg-200samples.tsv" file_b = "1000genomes.low_coverage.GRCh38DH.alignment.index" sample_ids_a = [] sample_ids_b = [] fh_a = open(file_a, "r") fh_a.readline() for line in fh_a: sample_id = line.strip().split(...
def main(): file_a = '1kg-200samples.tsv' file_b = '1000genomes.low_coverage.GRCh38DH.alignment.index' sample_ids_a = [] sample_ids_b = [] fh_a = open(file_a, 'r') fh_a.readline() for line in fh_a: sample_id = line.strip().split('\t')[-1] sample_ids_a.append(sample_id) fh...
def solution(X, A): leaves = set(range(1, X+1)) for second, leaf in enumerate(A): if leaf in leaves: leaves.remove(leaf) if not leaves: return second return -1 def test_solution(): assert solution(5, [1, 3, 1, 4, 2, 3, 5, 4]) == 6
def solution(X, A): leaves = set(range(1, X + 1)) for (second, leaf) in enumerate(A): if leaf in leaves: leaves.remove(leaf) if not leaves: return second return -1 def test_solution(): assert solution(5, [1, 3, 1, 4, 2, 3, 5, 4]) == 6
def frequency(lst, search_term): """Return frequency of term in lst. >>> frequency([1, 4, 3, 4, 4], 4) 3 >>> frequency([1, 4, 3], 7) 0 """ d = {} for x in lst: if x in d: d[x] = d[x] + 1 else: d[x] = 1 if search_term in d: ...
def frequency(lst, search_term): """Return frequency of term in lst. >>> frequency([1, 4, 3, 4, 4], 4) 3 >>> frequency([1, 4, 3], 7) 0 """ d = {} for x in lst: if x in d: d[x] = d[x] + 1 else: d[x] = 1 if search_term in d: ...
# -------------------- PATH --------------------- #ROOT_PATH = "/local/data2/pxu4/TypeClassification" ROOT_PATH = "." DATA_PATH = "%s/data" % ROOT_PATH ONTONOTES_DATA_PATH = "%s/OntoNotes" % DATA_PATH BBN_DATA_PATH="%s/BBN" % DATA_PATH LOG_DIR = "%s/log" % ROOT_PATH CHECKPOINT_DIR = "%s/checkpoint" % ROOT_PATH OUTPUT_...
root_path = '.' data_path = '%s/data' % ROOT_PATH ontonotes_data_path = '%s/OntoNotes' % DATA_PATH bbn_data_path = '%s/BBN' % DATA_PATH log_dir = '%s/log' % ROOT_PATH checkpoint_dir = '%s/checkpoint' % ROOT_PATH output_dir = '%s/output' % ROOT_PATH pkl_dir = './pkl' embedding_data = '%s/glove.840B.300d.txt' % DATA_PATH...
""" Reservoir sampling. Sample from stream of unknown length usage: from statistics import median res = initialize_res_samples(fields) num_samples = 50 random_generator = random.Random() random_generator.seed(42) for row_index, row in enumerate(stream): for field in fields: value = row[field] upda...
""" Reservoir sampling. Sample from stream of unknown length usage: from statistics import median res = initialize_res_samples(fields) num_samples = 50 random_generator = random.Random() random_generator.seed(42) for row_index, row in enumerate(stream): for field in fields: value = row[field] upda...
s = 0 for i in range(5): a = int(input()) if a < 40: a = 40 s += a print(int(s / 5))
s = 0 for i in range(5): a = int(input()) if a < 40: a = 40 s += a print(int(s / 5))
def fill_nan(df): # fill NaN in df sets and categorize columns datatype # adding missing column for the missing imputed values for column in df.columns: if column in numerical_feature_names: df[column+'_missing'] = df[column].isnull() mean = np.nanmean(df[column].values) ...
def fill_nan(df): for column in df.columns: if column in numerical_feature_names: df[column + '_missing'] = df[column].isnull() mean = np.nanmean(df[column].values) df.loc[df[column].isnull(), column] = mean else: df.loc[df[column].isnull(), column] = ...
metric_dimension = { "post_all_days": { "metric": [ "post_impressions_unique", "post_engaged_users", "post_impressions_paid_unique" ], "period": [ "lifetime", ], "date_window": "lifetime", "dimension": [ "pos...
metric_dimension = {'post_all_days': {'metric': ['post_impressions_unique', 'post_engaged_users', 'post_impressions_paid_unique'], 'period': ['lifetime'], 'date_window': 'lifetime', 'dimension': ['post_id', 'period']}}