content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
matrika = list() for i in list(open('euler82.txt', 'r')): matrika.append(i.replace('\n', '').split(',')) najboljsa_pot = dict() for vrstica in range(80): najboljsa_pot[(0, vrstica)] = int(matrika[vrstica][0]) for stolpec in range(1, 80): for vrstica in range(80): najboljsa_pot[(stolpec, vrstica)] ...
matrika = list() for i in list(open('euler82.txt', 'r')): matrika.append(i.replace('\n', '').split(',')) najboljsa_pot = dict() for vrstica in range(80): najboljsa_pot[0, vrstica] = int(matrika[vrstica][0]) for stolpec in range(1, 80): for vrstica in range(80): najboljsa_pot[stolpec, vrstica] = min(...
def thread_lock(lock): '''Use an existing thread lock to thread-lock a function This prevents the function from being executed by multiple threads at once Example: import threading lock = threading.Lock() @thread_lock(lock) def my_function(a, b, c): print a, b, c ''' def l...
def thread_lock(lock): """Use an existing thread lock to thread-lock a function This prevents the function from being executed by multiple threads at once Example: import threading lock = threading.Lock() @thread_lock(lock) def my_function(a, b, c): print a, b, c """ def l...
# when training only a subset of variables, only the scope needs to be specified s3dg_logits = 'InceptionV1/Logits' # when warm-starting training using the Estimator API, variable names (including # full scopes) must be specified exactly s3dg_convs = [ 'InceptionV1/Conv2d_1a_7x7/BatchNorm/beta', 'InceptionV1/Conv2...
s3dg_logits = 'InceptionV1/Logits' s3dg_convs = ['InceptionV1/Conv2d_1a_7x7/BatchNorm/beta', 'InceptionV1/Conv2d_1a_7x7/BatchNorm/beta/ExponentialMovingAverage', 'InceptionV1/Conv2d_1a_7x7/BatchNorm/moving_mean', 'InceptionV1/Conv2d_1a_7x7/BatchNorm/moving_mean/ExponentialMovingAverage', 'InceptionV1/Conv2d_1a_7x7/Batc...
pc_pi = 3.14159265358979323846264338327950288 pc_twopi = 6.2831853071795862320E0 pc_h = 6.62606896E-34 # The Planck constant (Js) pc_c = 2.99792458E8 # Speed of light (ms$^{-1}$) pc_kb = 1.3806504E-23 # The Boltzmann constant (JK$^{-1}$) pc_R = 8.314472 ...
pc_pi = 3.141592653589793 pc_twopi = 6.283185307179586 pc_h = 6.62606896e-34 pc_c = 299792458.0 pc_kb = 1.3806504e-23 pc_r = 8.314472 pc_bohr2angstroms = 0.52917720859 pc_bohr2m = 5.2917720859e-11 pc_bohr2cm = 5.2917720859e-09 pc_amu2g = 1.660538782e-24 pc_amu2kg = 1.660538782e-27 pc_au2amu = 0.0005485799097 pc_hartree...
class CoreCompatibilityPreferences(object): # no doc EnableMultiMonitorDisplayClipping=None IsAltKeyRequiredInAccessKeyDefaultScope=False __all__=[]
class Corecompatibilitypreferences(object): enable_multi_monitor_display_clipping = None is_alt_key_required_in_access_key_default_scope = False __all__ = []
{ "targets": [ { "target_name": "swap", "sources": [ "swap.cc" ] } ] }
{'targets': [{'target_name': 'swap', 'sources': ['swap.cc']}]}
auth_params = { 'v1': True, 'v2': True, 'v3': False }
auth_params = {'v1': True, 'v2': True, 'v3': False}
A, B = map(int, input().split()) count, outlet = 0, 1 while(outlet < B): outlet -= 1 outlet += A count += 1 print(count)
(a, b) = map(int, input().split()) (count, outlet) = (0, 1) while outlet < B: outlet -= 1 outlet += A count += 1 print(count)
# cython: language_level=3, boundscheck=False, wraparound=False, control_flow.dot_output=dead2.dot def blah(a, b): for u, v in zip(a, b): break # dead code print(u) print(v) c = a - b for v in range(53): continue # dead code return v v *=...
def blah(a, b): for (u, v) in zip(a, b): break print(u) print(v) c = a - b for v in range(53): continue return v v *= 2
# <auto-generated> # This code was generated by the UnitCodeGenerator tool # # Changes to this file will be lost if the code is regenerated # </auto-generated> def to_square_kilometres(value): return value / 247.105 def to_square_metres(value): return value * 4046.86 def to_square_miles(value): return value / 64...
def to_square_kilometres(value): return value / 247.105 def to_square_metres(value): return value * 4046.86 def to_square_miles(value): return value / 640.0 def to_square_yards(value): return value * 4840.0 def to_square_feet(value): return value * 43560.0 def to_square_inches(value): retur...
def gray(a): return ((a)^(a>>1)) class Solution: def grayCode(self, n: int) -> List[int]: ans=[] for i in range(pow(2,n)): ans.append(gray(i)) return ans
def gray(a): return a ^ a >> 1 class Solution: def gray_code(self, n: int) -> List[int]: ans = [] for i in range(pow(2, n)): ans.append(gray(i)) return ans
''' Undo module. This module defines the class that handles undo and redo operations. ''' class Undo: ''' This class handles all the Undo and Redo functionalities of the program. The idea is the following: * A list is defined that holds operations of type Operation, as defined in the Operation class inside the ...
""" Undo module. This module defines the class that handles undo and redo operations. """ class Undo: """ This class handles all the Undo and Redo functionalities of the program. The idea is the following: * A list is defined that holds operations of type Operation, as defined in the Operation class inside t...
#1) #a)Realice una funcion que dado los numeros pasados por parametro retorne si A=1 y B=1 Res=1, Res=0 en cualquier otro caso. A = input("Ingrese un numero: ") B = input("Ingrese otro numero: ") def andfun(A,B): if A == 1 and B == 1: return 1 else: return 0 print(andfun(A,B)) #b)Realice una funcion que simul...
a = input('Ingrese un numero: ') b = input('Ingrese otro numero: ') def andfun(A, B): if A == 1 and B == 1: return 1 else: return 0 print(andfun(A, B)) c = input('ingrese un numero binario: ') d = input('ingrese otro numero binario: ') def orfun(C, D): if C == 1 or D == 1: return 1...
# Author: Soft9000.com # 2018/03/08: Class Created class GenException(Exception): def __init__(self, message): super().__init__(message) class GenOrderError(Exception): def __init__(self, message): super().__init__(message)
class Genexception(Exception): def __init__(self, message): super().__init__(message) class Genordererror(Exception): def __init__(self, message): super().__init__(message)
class Tile: def describe(self): print("A path runs through dense jungle. To the north, " "you can see the entrance to a cave.") def action(self, player, do): # Nothing to do here yet. print("Sorry, I don't understand")
class Tile: def describe(self): print('A path runs through dense jungle. To the north, you can see the entrance to a cave.') def action(self, player, do): print("Sorry, I don't understand")
def print_unordered_pairs(array_a, array_b): for a in array_a: for b in array_b: if a < b: print('%d, %d' %(a, b)) print_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4]) # The complexity of the print_unordered_pairs function is: O(N^2) # We do a nested loop = length(array_a) *...
def print_unordered_pairs(array_a, array_b): for a in array_a: for b in array_b: if a < b: print('%d, %d' % (a, b)) print_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4])
#string s = "I am a string." print(type(s)) #str #Boolean yes = True print(type(yes)) #bool true no = False print(type(no)) #bool false # List alpha_list = [ "a", "b", "c"] print(type(alpha_list)) # tuple print(type(alpha_list[0])) # string alpha_list.append("d") print(alpha_list) # ...
s = 'I am a string.' print(type(s)) yes = True print(type(yes)) no = False print(type(no)) alpha_list = ['a', 'b', 'c'] print(type(alpha_list)) print(type(alpha_list[0])) alpha_list.append('d') print(alpha_list) alpha_tuple = ('a', 'b', 'c') print(type(alpha_list)) try: alpha_tuple[2] = 'd' except TypeError: pr...
def testfunc(): st='Testing out a function a package' return st
def testfunc(): st = 'Testing out a function a package' return st
def reachToTheEnd(arr, l, h): if l == h: return 0 if arr[l] == 0: return float("inf") min = float("inf") for i in range(l+1, h+1): if i < l + arr[l] + 1: jumps = reachToTheEnd(arr, i, h) if jumps != float("inf") and jumps + 1 < min: ...
def reach_to_the_end(arr, l, h): if l == h: return 0 if arr[l] == 0: return float('inf') min = float('inf') for i in range(l + 1, h + 1): if i < l + arr[l] + 1: jumps = reach_to_the_end(arr, i, h) if jumps != float('inf') and jumps + 1 < min: ...
# ######################### # The world's worst LCM # function. Using recursive, # curried lambda functions # to find the Lowest Common # Multiple of a List of # integers. To be clear, # this is incredibly # unpractical and just # plain heinous. This is # for entertainment # purposes only. Don't do...
l = lambda n: l([n[0] * n[1] / (lambda g: lambda a, b: g(g, a, b))(lambda g, a, b: g(g, b, a % b) if b else a)(n[0], n[1])] + n[2:]) if len(n) > 1 else n[0] print(l(list(range(1, 200))))
all_lines = [] with open('submission.csv', 'r') as f: all_lines = f.readlines() mod_lines = [x.split(',') for x in all_lines] with open('new_sub.csv', 'w') as ff: for line in mod_lines: print(line) mod_one = line[1] if '0' in line[1]: mod_one = '1\n' if '1' in line[...
all_lines = [] with open('submission.csv', 'r') as f: all_lines = f.readlines() mod_lines = [x.split(',') for x in all_lines] with open('new_sub.csv', 'w') as ff: for line in mod_lines: print(line) mod_one = line[1] if '0' in line[1]: mod_one = '1\n' if '1' in line[1]...
#The problem is to count all the possible paths from top left to bottom right of a mXn matrix with the constraints #Withdynamic programming def dy_without_diag(m,n): Grid = [1] * m for i in range(m): Grid[i] = [1] * n for i in range(1,m): for j in range(1,n): if(j!=0 and i!=0): Grid[i][j]=...
def dy_without_diag(m, n): grid = [1] * m for i in range(m): Grid[i] = [1] * n for i in range(1, m): for j in range(1, n): if j != 0 and i != 0: Grid[i][j] = Grid[i][j - 1] + Grid[i - 1][j] return Grid[m - 1][n - 1] print('Without_diagonal', dy_without_diag(3,...
def binary_search(L, X): low = 0 high = len(L)-1 while low <= high: #this fails when we have one element so low and high are equals mid = (low+high)//2 #and then we moved low one step up or high one step down if L[mid] == X: return mid ...
def binary_search(L, X): low = 0 high = len(L) - 1 while low <= high: mid = (low + high) // 2 if L[mid] == X: return mid elif X > L[mid]: low = mid + 1 elif X < L[mid]: high = mid - 1 return -1 l = [1, 4, 7, 9, 10, 20, 25, 34, 90, 10] p...
def find_max(numbers): max = numbers[0] for number in numbers: if number > max: max = number return max
def find_max(numbers): max = numbers[0] for number in numbers: if number > max: max = number return max
'''d={} nums=[1,1,2] for a in nums: d[a]=d.get(a,0)+1 print(len(d.keys()),list(d.keys())) a = {} a.keys() def revstring(string): toret = "" for a in range(len(string)): toret = toret + string[len(string)-1-a] return toret def countKDifference( nums: list[int], k: int) -> int: dic = ...
"""d={} nums=[1,1,2] for a in nums: d[a]=d.get(a,0)+1 print(len(d.keys()),list(d.keys())) a = {} a.keys() def revstring(string): toret = "" for a in range(len(string)): toret = toret + string[len(string)-1-a] return toret def countKDifference( nums: list[int], k: int) -> int: dic = ...
class MarketTicker(): def __init__(self, from_currency, to_currency, exchange, ask, bid): self.to_currency = to_currency self.from_currency = from_currency self.exchange = exchange self.ask = ask self.bid = bid def __str__(self): return "From " + str(self.from_cu...
class Marketticker: def __init__(self, from_currency, to_currency, exchange, ask, bid): self.to_currency = to_currency self.from_currency = from_currency self.exchange = exchange self.ask = ask self.bid = bid def __str__(self): return 'From ' + str(self.from_cur...
class Solution: def solve(self, s): if not s: return 0 left_streaks = [0] for i in range(len(s)): left_streaks.append(left_streaks[-1]+1 if s[i] == '1' else 0) right_streaks = [0] for i in range(len(s)-1,-1,-1): right_streak...
class Solution: def solve(self, s): if not s: return 0 left_streaks = [0] for i in range(len(s)): left_streaks.append(left_streaks[-1] + 1 if s[i] == '1' else 0) right_streaks = [0] for i in range(len(s) - 1, -1, -1): right_streaks.append(...
def greeting(msg): print(msg) greeting("hello from master!")
def greeting(msg): print(msg) greeting('hello from master!')
def dateformat(date_format): if not date_format or not isinstance(date_format, str): raise ValueError('Invalid value for the date_format argument') def func(cls): cls.__dateformat__ = date_format return cls return func def accept_whitespaces(_cls=None): def func(cls): ...
def dateformat(date_format): if not date_format or not isinstance(date_format, str): raise value_error('Invalid value for the date_format argument') def func(cls): cls.__dateformat__ = date_format return cls return func def accept_whitespaces(_cls=None): def func(cls): ...
def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:])) + x[-1] * y[0] -sum(i * j for i, j in zip(x[1:], y)) - x[0] * y[-1]) / 2
def area_by_shoelace(x, y): """Assumes x,y points go around the polygon in one direction""" return abs(sum((i * j for (i, j) in zip(x, y[1:]))) + x[-1] * y[0] - sum((i * j for (i, j) in zip(x[1:], y))) - x[0] * y[-1]) / 2
# Title : TODO # Objective : TODO # Created by: Wenzurk # Created on: 2018/2/2 favorite_number = 2 print(str(favorite_number)+" is my favorite number.")
favorite_number = 2 print(str(favorite_number) + ' is my favorite number.')
class Solution: def subsetsWithDup(self, nums: List[int], sorted: bool = False) -> List[List[int]]: if not nums: return [[]] if len(nums) == 1: return [[], nums] if not sorted: nums.sort() result = self.subsetsWithDup(nums[:-1], sorted=True) result = [i + [nums[-1]] for i in ...
class Solution: def subsets_with_dup(self, nums: List[int], sorted: bool=False) -> List[List[int]]: if not nums: return [[]] if len(nums) == 1: return [[], nums] if not sorted: nums.sort() result = self.subsetsWithDup(nums[:-1], sorted=True) ...
def ternary(cond1, result1, result2): if cond1: return result1 else: return result2
def ternary(cond1, result1, result2): if cond1: return result1 else: return result2
in_chat_with_support = [] @bot.message_handler(commands=['support']) def support(message): userid = message.from_user.id banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid)) if banlist: return if message.from_user.id not in in_chat_with_support: bot.reply_to(message, JOINED_MESSENGER_M...
in_chat_with_support = [] @bot.message_handler(commands=['support']) def support(message): userid = message.from_user.id banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid)) if banlist: return if message.from_user.id not in in_chat_with_support: bot.reply_to(message, J...
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/turtle/holonomic_turtle_bot/src/dynamixel_workbench_controllers/include;/usr/include/eigen3".split(';') if "/home/turtle/holonomic_turtle_bot/src/dynamixel_workbench_controllers/include;/usr/incl...
catkin_package_prefix = '' project_pkg_config_include_dirs = '/home/turtle/holonomic_turtle_bot/src/dynamixel_workbench_controllers/include;/usr/include/eigen3'.split(';') if '/home/turtle/holonomic_turtle_bot/src/dynamixel_workbench_controllers/include;/usr/include/eigen3' != '' else [] project_catkin_depends = 'roscp...
p1 = float(input('Nota de matematica prova 1:')) p2 = float(input('Nota de matematica prova 2:')) m = (p1 + p2)//2 print(f'A media entre a P1 e a P2 e:{m}.')
p1 = float(input('Nota de matematica prova 1:')) p2 = float(input('Nota de matematica prova 2:')) m = (p1 + p2) // 2 print(f'A media entre a P1 e a P2 e:{m}.')
_base_ = [ '../../_base_/models/faster_rcnn_r50_fpn.py', '../../_base_/datasets/mot_challenge.py', '../../_base_/default_runtime.py' ] model = dict( type='QDTrack', detector=dict( backbone=dict( norm_cfg=dict(requires_grad=False), style='caffe', init_cfg=dict(...
_base_ = ['../../_base_/models/faster_rcnn_r50_fpn.py', '../../_base_/datasets/mot_challenge.py', '../../_base_/default_runtime.py'] model = dict(type='QDTrack', detector=dict(backbone=dict(norm_cfg=dict(requires_grad=False), style='caffe', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), rpn_hea...
# uninhm # https://atcoder.jp/contests/abc214/tasks/abc214_c # dp n = int(input()) s = list(map(int, input().split())) t = list(map(int, input().split())) ans = [float('inf')]*n ans[0] = t[0] for _ in range(2): for i in range(n): ans[i] = min(ans[i-1]+s[i-1], t[i]) for i in ans: print(i)
n = int(input()) s = list(map(int, input().split())) t = list(map(int, input().split())) ans = [float('inf')] * n ans[0] = t[0] for _ in range(2): for i in range(n): ans[i] = min(ans[i - 1] + s[i - 1], t[i]) for i in ans: print(i)
sm.spawnMob(8880110, 1073, 16, False, 25200000000000) # 25.2t while sm.hasMobsInField(): sm.waitForMobDeath() sm.warp(350160240)
sm.spawnMob(8880110, 1073, 16, False, 25200000000000) while sm.hasMobsInField(): sm.waitForMobDeath() sm.warp(350160240)
def sum(a): b = a + 1 sol = int(a * b / 2) return sol a = int(raw_input()) before = sum(a) a += 1 after = sum(a) - 1 before += int(after / 10) after = after % 10 print (str(before) + "." + str(after))
def sum(a): b = a + 1 sol = int(a * b / 2) return sol a = int(raw_input()) before = sum(a) a += 1 after = sum(a) - 1 before += int(after / 10) after = after % 10 print(str(before) + '.' + str(after))
def getFreeStream(): global a0 global alt global altd global cpair global fsmach global gama global inptype global lconv1 global lconv2 global ps0 global psout global q0 global rgas global rho0 global...
def get_free_stream(): global a0 global alt global altd global cpair global fsmach global gama global inptype global lconv1 global lconv2 global ps0 global psout global q0 global rgas global rho0 global ts0 global tsout global u0 global u0d rga...
class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: envelopes.sort(key=lambda e:(e[0], -e[1])) N = len(envelopes) best = [0] for _, h in envelopes: index = bisect.bisect_left(best, h) if index == len(best): best.append(...
class Solution: def max_envelopes(self, envelopes: List[List[int]]) -> int: envelopes.sort(key=lambda e: (e[0], -e[1])) n = len(envelopes) best = [0] for (_, h) in envelopes: index = bisect.bisect_left(best, h) if index == len(best): best.appe...
# decorater def ingredients(func): def wrapper(): print("##totato##") func() print("##totato##") # print("</''''''''\>") return wrapper def bread(func): def wrapper(): print("</''''''''\>") func() print("<\......../>") return wrapper # def s...
def ingredients(func): def wrapper(): print('##totato##') func() print('##totato##') return wrapper def bread(func): def wrapper(): print("</''''''''\\>") func() print('<\\......../>') return wrapper @bread @ingredients def sandwich(food='--ham--'): ...
__name__ = 'server' class Server: def __init__(self, host, username, password): self._host = host self._username = username self._password = password @property def host(self): return self._host @property def username(self): return self._username @prop...
__name__ = 'server' class Server: def __init__(self, host, username, password): self._host = host self._username = username self._password = password @property def host(self): return self._host @property def username(self): return self._username @prop...
class Solution: def XXX(self, root: TreeNode) -> int: if not root: return 0 return self.helper(root, 1) def helper(self, root, level): if not root: return level - 1 lev_left = self.helper(root.left, level+1) lev_right = self.helper(r...
class Solution: def xxx(self, root: TreeNode) -> int: if not root: return 0 return self.helper(root, 1) def helper(self, root, level): if not root: return level - 1 lev_left = self.helper(root.left, level + 1) lev_right = self.helper(root.right, ...
def odd_even(): print('Enter a number') num = int(input()) if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) odd_even()
def odd_even(): print('Enter a number') num = int(input()) if num % 2 == 0: print('{0} is Even'.format(num)) else: print('{0} is Odd'.format(num)) odd_even()
class Build(object): list_of_input_variable = [] def __init__(self,*args): self.list_of_input_variable = args def get_input(self): return self.list_of_input_variable def get_number_of_rules(self): number_of_rules = 1 for input_variable in self.list_of_input_variable:...
class Build(object): list_of_input_variable = [] def __init__(self, *args): self.list_of_input_variable = args def get_input(self): return self.list_of_input_variable def get_number_of_rules(self): number_of_rules = 1 for input_variable in self.list_of_input_variable: ...
CLASS_VAR_DEC_TAG_NAME = "classVarDec" VAR_DEC_TAG_NAME = "varDec" TOKENS_TAG_NAME = "tokens" CLASS_TAG_NAME = "class" SUBROUTINE_DEC_TAG_NAME = "subroutineDec" PARAMETER_LIST_TAG_NAME = "parameterList" SUBROUTINE_BODY_TAG_NAME = "subroutineBody" STATEMENTS_TAG_NAME = "statements" LET_TAG_NAME = "letStatement" IF_TAG_N...
class_var_dec_tag_name = 'classVarDec' var_dec_tag_name = 'varDec' tokens_tag_name = 'tokens' class_tag_name = 'class' subroutine_dec_tag_name = 'subroutineDec' parameter_list_tag_name = 'parameterList' subroutine_body_tag_name = 'subroutineBody' statements_tag_name = 'statements' let_tag_name = 'letStatement' if_tag_n...
# program that asks user to enter a number and output if that number is odd or even # helen o'shea # 20210210 while quit !=-1: myNumber = int(input("Enter a number: ")) if myNumber%2==0: parity ="even" print('{} is an {} number'.format(myNumber, parity)) else: parity="odd" print('{} is an {} numb...
while quit != -1: my_number = int(input('Enter a number: ')) if myNumber % 2 == 0: parity = 'even' print('{} is an {} number'.format(myNumber, parity)) else: parity = 'odd' print('{} is an {} number'.format(myNumber, parity)) quit = input('Do you want to quit y or n?') ...
# -*- coding: utf-8 -*- ''' Management of Zabbix user groups. :codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io> ''' def __virtual__(): ''' Only make these states available if Zabbix module is available. ''' return 'zabbix.usergroup_create' in __salt__ def present(name, **kwargs): ''' Create...
""" Management of Zabbix user groups. :codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io> """ def __virtual__(): """ Only make these states available if Zabbix module is available. """ return 'zabbix.usergroup_create' in __salt__ def present(name, **kwargs): """ Creates new user. Args: ...
class Solution: def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: for _ in range(4): if mat == target: return True mat = [list(x) for x in zip(*mat[::-1])] return False
class Solution: def find_rotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: for _ in range(4): if mat == target: return True mat = [list(x) for x in zip(*mat[::-1])] return False
def stretch_stats(url='http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt'): freq = [line.strip().lower().split() for line in urllib.request.urlopen(url) if len(line.strip().split()) == 3] wordfreq = [(word.decode(), int(frq)) for word, pos, frq in freq[1:] ...
def stretch_stats(url='http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt'): freq = [line.strip().lower().split() for line in urllib.request.urlopen(url) if len(line.strip().split()) == 3] wordfreq = [(word.decode(), int(frq)) for (word, pos, frq) in freq[1:] if b'ie' in word or b'ei' in word] cie = su...
db.define_table( 'meaningful_use_2014', Field('choose_file', 'upload', uploadfield='file_data'), Field('file_data', 'blob'), Field('file_description', requires=IS_NOT_EMPTY()), ) db.define_table( "patient_demographics", Field("please_choose", "list:string" # requires=IS_IN_S...
db.define_table('meaningful_use_2014', field('choose_file', 'upload', uploadfield='file_data'), field('file_data', 'blob'), field('file_description', requires=is_not_empty())) db.define_table('patient_demographics', field('please_choose', 'list:string')) services = [('immunization', 'vaccinations/immunizations'), ('pre...
class Dog: __slots__ = ["name", "breed", "weight"] counter = 0 @classmethod def increase_count(cls): cls.counter += 1 # method for count all created dogs @staticmethod def bark(): print("Guf-guf!") def __init__(self, name, breed, weight): self.name = name...
class Dog: __slots__ = ['name', 'breed', 'weight'] counter = 0 @classmethod def increase_count(cls): cls.counter += 1 @staticmethod def bark(): print('Guf-guf!') def __init__(self, name, breed, weight): self.name = name self.breed = breed self.weigh...
class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: c = 0 allowed = set(allowed) for word in words: # word = set(word) for letter in word: if letter not in allowed: break else: ...
class Solution: def count_consistent_strings(self, allowed: str, words: List[str]) -> int: c = 0 allowed = set(allowed) for word in words: for letter in word: if letter not in allowed: break else: c += 1 ret...
#!/usr/bin/env python3 # generator function creates iterator # utility function def isprime(n): if n == 1: return False for x in range(2, n): if n % x == 0: return False else: return True # generator def primes(n = 1): while(True): # True/False, if True: retur...
def isprime(n): if n == 1: return False for x in range(2, n): if n % x == 0: return False else: return True def primes(n=1): while True: if isprime(n): yield n n += 1 for n in primes(): if n > 100: break print(n)
#---------------------------------------------------------------------------------------------------------- # # AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX # # NAME: Create Grade # COLOR: #829eb7 # #---------------------------------------------------------------------------------------------------------- ns = ...
ns = nuke.selectedNodes() for n in ns: n.knob('createGrade').execute()
class Data_Mocks: def get_sample_string_response(self) -> str: return '''{ "SecurityGroups": [ { "Description": "Access from the backery", "GroupName": "my-first-sg", "IpPermissions": [], "OwnerId": "123324134", "GroupId": "sg-2f31...
class Data_Mocks: def get_sample_string_response(self) -> str: return '{\n "SecurityGroups": [\n {\n "Description": "Access from the backery",\n "GroupName": "my-first-sg",\n "IpPermissions": [],\n "OwnerId": "123324134",\n "GroupId": "sg-2f3...
# Config file example # # See the command_help.md file for command number codes you can use. # settings = { "ip": "127.0.0.1", "port": "3333", "timeout": 3 } cmds = { "p": 889, "n": 922, "b": 921, "f": 830, "jf": 900, "jb": 899, "s": 890, "+": 907, "-": 908, "m": 909 }
settings = {'ip': '127.0.0.1', 'port': '3333', 'timeout': 3} cmds = {'p': 889, 'n': 922, 'b': 921, 'f': 830, 'jf': 900, 'jb': 899, 's': 890, '+': 907, '-': 908, 'm': 909}
def func(x, *args): pass func(1, 3)
def func(x, *args): pass func(1, 3)
h = int(input('Horas: ')) m = int(input('Minutos: ')) s = int(input('Segundos: ')) tot = (h * 3600) + (m * 60) + s print(f'Total em segundos: {tot}s')
h = int(input('Horas: ')) m = int(input('Minutos: ')) s = int(input('Segundos: ')) tot = h * 3600 + m * 60 + s print(f'Total em segundos: {tot}s')
def to_str(data): if isinstance(data, str): return data elif isinstance(data, bytes): return data.decode('utf-8') else: raise TypeError('Must supply str or bytes, found: %r' % data)
def to_str(data): if isinstance(data, str): return data elif isinstance(data, bytes): return data.decode('utf-8') else: raise type_error('Must supply str or bytes, found: %r' % data)
state_initial = "if" # if # else # then # for accepted_states = [5, 8, 11, 13] state = 0 def validate_state(state): if state in accepted_states: return True return False if state_initial == "": print("Seu estado foi aceito: " + state_initial) else: for char in state_initial: if state == 0 and char not in ...
state_initial = 'if' accepted_states = [5, 8, 11, 13] state = 0 def validate_state(state): if state in accepted_states: return True return False if state_initial == '': print('Seu estado foi aceito: ' + state_initial) else: for char in state_initial: if state == 0 and char not in ['i', ...
DEPARTMENTS_MAP = { "che": "Chemical", "che-idd": "Chemical IDD", "cer": "Ceramic", "cer-idd": "Ceramic IDD", "civ": "Civil", "civ-idd": "Civil IDD", "cse": "Computer Science", "cse-idd": "Computer Science IDD", "eee": "Electrical", "eee-idd": "Electrical IDD", "ece": "Electr...
departments_map = {'che': 'Chemical', 'che-idd': 'Chemical IDD', 'cer': 'Ceramic', 'cer-idd': 'Ceramic IDD', 'civ': 'Civil', 'civ-idd': 'Civil IDD', 'cse': 'Computer Science', 'cse-idd': 'Computer Science IDD', 'eee': 'Electrical', 'eee-idd': 'Electrical IDD', 'ece': 'Electronics', 'mat': 'Mathematics', 'mat-idd': 'Mat...
#!/usr/bin/python # -*- coding: utf-8 -*- ################################################################################ # Copyright (c) 2017 McAfee Inc. - All Rights Reserved. ################################################################################ __author__ = "Jorge Couchet" extensions = ['dll', 'action'...
__author__ = 'Jorge Couchet' extensions = ['dll', 'action', 'apk', 'app', 'bat', 'bin', 'cmd', 'com', 'command', 'cpl', 'cs', 'exe', 'gadget', 'inf1', 'ins', 'inx', 'ipa', 'isu', 'job', 'jse', 'ksh', 'lnk', 'msc', 'msi', 'msp', 'mst', 'osx', 'out', 'paf', 'pif', 'prg', 'ps1', 'reg', 'rgs', 'run', 'scr', 'sct', 'shb', '...
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-06-13 22:41 PAD = '<pad>' UNK = '<unk>' ROOT = '<root>' CLS = '[CLS]' HANLP_URL = 'https://file.hankcs.com/hanlp/'
pad = '<pad>' unk = '<unk>' root = '<root>' cls = '[CLS]' hanlp_url = 'https://file.hankcs.com/hanlp/'
INFINITY = 1e12 # special markers for identifying a Product PROD_START_MARKER = "[Prod]" PROD_END_MARKER = "[/Prod]"
infinity = 1000000000000.0 prod_start_marker = '[Prod]' prod_end_marker = '[/Prod]'
foods = ['carrots', 'tomatoes', 'cabbage', 'meat', 'pasta'] print ('the first three items in the list are :') for food in foods[:3]: print (food) print ('the three items from the middle of the list are :') for food in foods [1:4]: print (food) print ('the last three items in the list are :') for food in foods[-3:]: ...
foods = ['carrots', 'tomatoes', 'cabbage', 'meat', 'pasta'] print('the first three items in the list are :') for food in foods[:3]: print(food) print('the three items from the middle of the list are :') for food in foods[1:4]: print(food) print('the last three items in the list are :') for food in foods[-3:]: ...
a = 0 b = 7 for i in range(0, int(input())): floor_req = int(input()) if abs(a-floor_req)==abs(b-floor_req): a = floor_req print("A") elif abs(a-floor_req)<abs(b-floor_req): a = floor_req print("A") else: b = floor_req print("B")
a = 0 b = 7 for i in range(0, int(input())): floor_req = int(input()) if abs(a - floor_req) == abs(b - floor_req): a = floor_req print('A') elif abs(a - floor_req) < abs(b - floor_req): a = floor_req print('A') else: b = floor_req print('B')
BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) YELLOW = (255,255,0)
black = (0, 0, 0) white = (255, 255, 255) green = (0, 255, 0) red = (255, 0, 0) blue = (0, 0, 255) yellow = (255, 255, 0)
# Credits: https://github.com/peterbuga/HASS-sonoff-ewelink COOLKIT_APP_ID: str = 'oeVkj2lYFGnJu5XUtWisfW4utiN4u9Mq' COOLKIT_APP_SECRET: str = b'6Nz4n0xA8s8qdxQf2GqurZj2Fs55FUvM'
coolkit_app_id: str = 'oeVkj2lYFGnJu5XUtWisfW4utiN4u9Mq' coolkit_app_secret: str = b'6Nz4n0xA8s8qdxQf2GqurZj2Fs55FUvM'
# Puzzle Input with open('Day14_Test_Prob1.txt') as puzzle_input: operations = puzzle_input.read().split('\n') # Converts string-represented binary number to decimal def bin_to_decimal(bin_num): dec_num = 0 bin_len = len(bin_num) for pos, bit in enumerate(bin_num): # Goes through the bits, fro...
with open('Day14_Test_Prob1.txt') as puzzle_input: operations = puzzle_input.read().split('\n') def bin_to_decimal(bin_num): dec_num = 0 bin_len = len(bin_num) for (pos, bit) in enumerate(bin_num): if bit == '1': dec_num += 2 ** (bin_len - pos - 1) return dec_num def bitwise_ma...
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") def public_dependencies(): maybe( http_archive, name = "rules_python", sha256 = "9fcf91dbcc31fde6d1edb15f117246d912c33c36f44cf681976bd886538deba6", str...
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe') def public_dependencies(): maybe(http_archive, name='rules_python', sha256='9fcf91dbcc31fde6d1edb15f117246d912c33c36f44cf681976bd886538deba6', strip_prefix='rules_python-0.8.0', urls=...
# # PySNMP MIB module Nortel-Magellan-Passport-McsMgrMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-McsMgrMIB # Produced by pysmi-0.3.4 at Wed May 1 14:27:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using...
(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, single_value_constraint, value_range_constraint) ...
headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away", "Papperbok Review: Totally Triffic"] news_ticker = "" # TODO: set ne...
headlines = ['Local Bear Eaten by Man', 'Legislature Announces New Laws', 'Peasant Discovers Violence Inherent in System', 'Cat Rescues Fireman Stuck in Tree', 'Brave Knight Runs Away', 'Papperbok Review: Totally Triffic'] news_ticker = '' for el in headlines: ln_news = len(news_ticker) if ln_news >= 140: ...
class WhitehatErrors(Exception): def __init__(self, message:str=None): if message is None: message = 'An unknown error has occurred within Whitehat.' super().__init__(message) class InvalidFormat(WhitehatErrors): def __init__(self): super().__init__("Invalid Format. ...
class Whitehaterrors(Exception): def __init__(self, message: str=None): if message is None: message = 'An unknown error has occurred within Whitehat.' super().__init__(message) class Invalidformat(WhitehatErrors): def __init__(self): super().__init__("Invalid Format. Suppo...
def get_character_index(s): d = {} # will hold values in the format[fist_index, count] for i in range(len(s)): if d.get(s[i]): d[s[i]][1] += 1 else: d[s[i]] = [i, 1] min_index = len(s) + 1 # will hold the index of the first character with frequency 1 for ...
def get_character_index(s): d = {} for i in range(len(s)): if d.get(s[i]): d[s[i]][1] += 1 else: d[s[i]] = [i, 1] min_index = len(s) + 1 for i in d: if d[i][1] == 1 and min_index > d[i][0]: min_index = d[i][0] return min_index if __name__ =...
def rotateRight( a, k): a = [8,9,10,7,33] length = a.len() reverse( a, 0, len(a) - 1 ) reverse( a, 0, k - 1 ) reverse( a, k, n - 1 ) def reverse( a, start, end ): while(start < end): swap( a, start, end ) start = start+1 end = end-1 def swap( a, pos1, po...
def rotate_right(a, k): a = [8, 9, 10, 7, 33] length = a.len() reverse(a, 0, len(a) - 1) reverse(a, 0, k - 1) reverse(a, k, n - 1) def reverse(a, start, end): while start < end: swap(a, start, end) start = start + 1 end = end - 1 def swap(a, pos1, pos2): temp = a[po...
# GAME SETTINGS WIDTH = 800 HEIGHT = 600 TITLE = 'Alien Invasion' FPS = 60 # BULLET_PROPERTIES BULLET_SPEED = 500 # COLORS WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0) LIGHT_GREEN = (64, 255, 83) RED = (255, 0, 0) YELLOW = (255, 255, 0)
width = 800 height = 600 title = 'Alien Invasion' fps = 60 bullet_speed = 500 white = (255, 255, 255) black = (0, 0, 0) green = (0, 255, 0) light_green = (64, 255, 83) red = (255, 0, 0) yellow = (255, 255, 0)
n = input() total = 0 for i in n: total += int(i) if int(n) % total == 0: print('Yes') else: print('No')
n = input() total = 0 for i in n: total += int(i) if int(n) % total == 0: print('Yes') else: print('No')
class Board(e): def flipcallback(self): self.basicboard.setflip(not self.basicboard.flip) def resetcallback(self): self.basicboard.reset() def setfromfen(self, fen, positioninfo = {}, edithistory = True): restartanalysis = False if self.analyzing.get(): self.sto...
class Board(e): def flipcallback(self): self.basicboard.setflip(not self.basicboard.flip) def resetcallback(self): self.basicboard.reset() def setfromfen(self, fen, positioninfo={}, edithistory=True): restartanalysis = False if self.analyzing.get(): self.stopan...
def convert_sample_to_shot_msc(sample, level=None): prefix = "Dialogue:\n" assert len(sample["dialogue"]) == len(sample["user_memory"]) for turn, meta in zip(sample["dialogue"],sample["user_memory"]): prefix += f"User: {turn[0]}" +"\n" if turn[1] != "": if len(meta)>0: ...
def convert_sample_to_shot_msc(sample, level=None): prefix = 'Dialogue:\n' assert len(sample['dialogue']) == len(sample['user_memory']) for (turn, meta) in zip(sample['dialogue'], sample['user_memory']): prefix += f'User: {turn[0]}' + '\n' if turn[1] != '': if len(meta) > 0: ...
abc = ('A B C D E F G H I J K L M N O P Q R S T U V W X Y Z').split() num = int(input()) for c in range(0, num): if c == 0: print(f'{abc[c] * 1}') else: c += 1 print(f'{abc[c - 1] * c}')
abc = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split() num = int(input()) for c in range(0, num): if c == 0: print(f'{abc[c] * 1}') else: c += 1 print(f'{abc[c - 1] * c}')
class Pizza: def __init__(self, name: str, dough: str, sauce: str, filling: list, cost: float) -> None: self.name = name self.dough = dough self.sauce = sauce self.filling = filling self.cost = cost def __str__(self) -> str: return f"{self.name} from {self.dough}...
class Pizza: def __init__(self, name: str, dough: str, sauce: str, filling: list, cost: float) -> None: self.name = name self.dough = dough self.sauce = sauce self.filling = filling self.cost = cost def __str__(self) -> str: return f'{self.name} from {self.dough...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # --------------------------------------------------------------------------- # ubuntu-sources-tool - variables.py # --------------------------------------------------------------------------- # Author: Videonauth <videonauth@googlemail.com> # License: MIT (see LICENSE fil...
__version__ = '0.0.9' default_constants = dict(DEBUG_MSG=dict(NONE=0, CRITICAL=1, ERROR=2, WARN=3, ALL=4, VAR=5)) default_settings = dict(DEBUG=False, DEBUG_LEVEL=0, LOG=False, LOG_LEVEL=0) default_blueprints = dict(default_conf=list([f'# config/default.conf file written from default_blueprints', f'# version {__version...
if __name__ == '__main__': n, m = [int(c) for c in input().split()] numbers = [list(map(int, input().split())) for _ in range(n)] k = int(input()) for arr in sorted(numbers, key=lambda x: x[k]): print(*arr)
if __name__ == '__main__': (n, m) = [int(c) for c in input().split()] numbers = [list(map(int, input().split())) for _ in range(n)] k = int(input()) for arr in sorted(numbers, key=lambda x: x[k]): print(*arr)
test_no = 1 while True: n = int(input()) if n == 0: break H = list(map(int, input().split())) final_height = sum(H) // n moves = sum(map(lambda x: final_height - x if x < final_height else 0, H)) print("Set #{}".format(test_no)) print("The minimum number of moves is {}.".format(moves)) print()...
test_no = 1 while True: n = int(input()) if n == 0: break h = list(map(int, input().split())) final_height = sum(H) // n moves = sum(map(lambda x: final_height - x if x < final_height else 0, H)) print('Set #{}'.format(test_no)) print('The minimum number of moves is {}.'.format(moves...
def fib(n): a,b = 1,1 for i in range(n): a,b = b,a+b return a t = int(input()) for i in range(t): n = int(input()) print(fib(n))
def fib(n): (a, b) = (1, 1) for i in range(n): (a, b) = (b, a + b) return a t = int(input()) for i in range(t): n = int(input()) print(fib(n))
class CNCCalc: @staticmethod def rpm(dia, sfpm): return int((int(sfpm) * 3.82) / float(dia)) @staticmethod def feedrate(rpm, feed, flutes): return round(float(rpm) * (int(flutes) * float(feed)), 2)
class Cnccalc: @staticmethod def rpm(dia, sfpm): return int(int(sfpm) * 3.82 / float(dia)) @staticmethod def feedrate(rpm, feed, flutes): return round(float(rpm) * (int(flutes) * float(feed)), 2)
class ParamTypes(object): pass for paramType in [ 'aggFunc', 'boolean', 'date', 'float', 'integer', 'interval', 'intOrInterval', 'node', 'nodeOrTag', 'series', 'seriesList', 'seriesLists', 'string', 'tag', ]: setattr(ParamTypes, paramType, paramType) class Param(object): __slots__ ...
class Paramtypes(object): pass for param_type in ['aggFunc', 'boolean', 'date', 'float', 'integer', 'interval', 'intOrInterval', 'node', 'nodeOrTag', 'series', 'seriesList', 'seriesLists', 'string', 'tag']: setattr(ParamTypes, paramType, paramType) class Param(object): __slots__ = ('name', 'type', 'require...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def postorderTraversal(self, root): st = [] data = [] pre = None if root: st...
class Solution(object): def postorder_traversal(self, root): st = [] data = [] pre = None if root: st.append(root) while st: cur = st[len(st) - 1] if cur.left == None and cur.right == None or (pre and (pre == cur.left or pre ==...
# https://www.codewars.com/kata/514a7ac1a33775cbb500001e # Details : This function should return an object, but it's not doing what's intended. What's wrong? def mystery(): results = {'sanity': 'Hello'} return results
def mystery(): results = {'sanity': 'Hello'} return results
class MeldedHand: name = "Melded Hand" points = 6 excluded = ("Single Wait",) def __init__(self, handObj): self.hand = handObj def examine_standard_hand(self): return self.hand.standardhand def examine_nothing_concealed(self): concealed_sets = [] allowed_sets = ["pung", "kong", "chow", "knitted"] ...
class Meldedhand: name = 'Melded Hand' points = 6 excluded = ('Single Wait',) def __init__(self, handObj): self.hand = handObj def examine_standard_hand(self): return self.hand.standardhand def examine_nothing_concealed(self): concealed_sets = [] allowed_sets =...
infile = open("data/coefs/L3_coefs_nodup.csv") outfile = open("data/coefs/L3_coefs_proc_nodup.csv","w") coefs_dict = {} for line in infile: split_line = line.strip().split("\t") mods = "_".join(split_line[0].split("_")[:-2]) mods_feat = "_".join(split_line[1].split("_")[:-1]) score = float(split_line[2...
infile = open('data/coefs/L3_coefs_nodup.csv') outfile = open('data/coefs/L3_coefs_proc_nodup.csv', 'w') coefs_dict = {} for line in infile: split_line = line.strip().split('\t') mods = '_'.join(split_line[0].split('_')[:-2]) mods_feat = '_'.join(split_line[1].split('_')[:-1]) score = float(split_line[2...
individual_prices = { 'A': 50, 'B': 30, 'C': 20, 'D': 15, 'E': 40, 'F': 10, 'G': 20, 'H': 10, 'I': 35, 'J': 60, 'K': 70, 'L': 90, 'M': 15, 'N': 40, 'O': 10, 'P': 50, 'Q': 30, 'R': 50, 'S': 20, 'T': 20, 'U': 40, 'V': 50, 'W': 20...
individual_prices = {'A': 50, 'B': 30, 'C': 20, 'D': 15, 'E': 40, 'F': 10, 'G': 20, 'H': 10, 'I': 35, 'J': 60, 'K': 70, 'L': 90, 'M': 15, 'N': 40, 'O': 10, 'P': 50, 'Q': 30, 'R': 50, 'S': 20, 'T': 20, 'U': 40, 'V': 50, 'W': 20, 'X': 17, 'Y': 20, 'Z': 21} class Offer(object): def __init__(self, required, cost, typ...
# -*- coding: utf-8 -*- __author__ = 'TeamD, Christopher Brandenburg' __email__ = 'cbrandenburg@student.ie.edu' __version__ = '0.9'
__author__ = 'TeamD, Christopher Brandenburg' __email__ = 'cbrandenburg@student.ie.edu' __version__ = '0.9'
# OPTIONS OUTPUT_DICTIONARY_NAME = 'tests/test_out' #AFFIX_FILE_HEADER_NAME = 'input/affixheaders/affix_file_header_latcyr.txt' #PICKLE_FOLDER = 'cache/pickling/' INPUT_DICTIONARIES = [ {'file': 'tests/test_in', 'type': 'AFFDIC'}, ]
output_dictionary_name = 'tests/test_out' input_dictionaries = [{'file': 'tests/test_in', 'type': 'AFFDIC'}]
# http://www.pythonchallenge.com/pc/def/0.html '''It's simply to calculate 2^38 and change the URL''' print(2**38)
"""It's simply to calculate 2^38 and change the URL""" print(2 ** 38)
def square(x): ''' x: int or float. ''' # Your code here return x**2
def square(x): """ x: int or float. """ return x ** 2
# Just a quick script used to delete spaces from train_input_spaced to get train_input # Needs improvements to file paths... I didn'bother coz this file is essentially a one-timer and it has served its purpose f = open('train_input_spaced.dat','rb') f2 = open('train_input.dat','wb') i= 0 for line in f: i+=1 #track...
f = open('train_input_spaced.dat', 'rb') f2 = open('train_input.dat', 'wb') i = 0 for line in f: i += 1 print(i) clean = '' for c in line: if c != ' ': clean += c f2.write(clean)