content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
n = int(input()) a = [] for x in range(n): a.append(int(input())) print(min(a)) print(max(a))
n = int(input()) a = [] for x in range(n): a.append(int(input())) print(min(a)) print(max(a))
def is_2xx(response_code): return 200 <= response_code < 300 def is_3xx(response_code): return 300 <= response_code < 400 def is_4xx(response_code): return 400 <= response_code < 500 def is_5xx(response_code): return response_code >= 500
def is_2xx(response_code): return 200 <= response_code < 300 def is_3xx(response_code): return 300 <= response_code < 400 def is_4xx(response_code): return 400 <= response_code < 500 def is_5xx(response_code): return response_code >= 500
# link:https://leetcode.com/problems/design-browser-history/ class BrowserHistory: def __init__(self, homepage: str): self.forw_memo = [] # forw_memo stores the future url self.back_memo = [] # back_memo stores the previous url self.curr_url = homepage def visit(self, url: str...
class Browserhistory: def __init__(self, homepage: str): self.forw_memo = [] self.back_memo = [] self.curr_url = homepage def visit(self, url: str) -> None: self.back_memo.append(self.curr_url) self.curr_url = url self.forw_memo = [] def back(self, steps: i...
# Python program to for appending a list file1 = open("myfile.txt","w") L = [] value=input("how many you want in a list") a=value.split() print(a) for i in a: L.append(i) print(L) file1.close() # Append-adds at last file1 = open("myfile.txt","a")#append mode for i in L: file1.write(i) file1.close() file1 =...
file1 = open('myfile.txt', 'w') l = [] value = input('how many you want in a list') a = value.split() print(a) for i in a: L.append(i) print(L) file1.close() file1 = open('myfile.txt', 'a') for i in L: file1.write(i) file1.close() file1 = open('myfile.txt', 'r') print('Output of Readlines after appending') prin...
class Solution(object): def numIslands(self, grid): self.dx = [-1, 1, 0, 0] self.dy = [0, 0, -1, 1] if not grid: return 0 self.x_max, self.y_max, self.grid = len(grid), len(grid[0]), grid self.visited = set() return sum([self.floodfill_dfs(i, j) for i in range(self.x...
class Solution(object): def num_islands(self, grid): self.dx = [-1, 1, 0, 0] self.dy = [0, 0, -1, 1] if not grid: return 0 (self.x_max, self.y_max, self.grid) = (len(grid), len(grid[0]), grid) self.visited = set() return sum([self.floodfill_dfs(i, j) for ...
def author_name(): return "Ganesh" def author_education(): return "Purusing Engineering Pre-final Year" def author_socialmedia(): return "https://www.linkedin.com/in/ganeshuthiravasagam/" def author_github(): return "https://github.com/Ganeshuthiravasagam/"
def author_name(): return 'Ganesh' def author_education(): return 'Purusing Engineering Pre-final Year' def author_socialmedia(): return 'https://www.linkedin.com/in/ganeshuthiravasagam/' def author_github(): return 'https://github.com/Ganeshuthiravasagam/'
# start main program DIGITS = list(range(1, 10)) # create emtpy puzzle grid = [[0 for i in range(9)] for j in range(9)] # hard coded puzzle from North Haven Courier grid[0][0] = 1; grid[0][3] = 6; grid[0][5] = 5; grid[0][6] = 4; grid[0][8] = 3; grid[1][0] = 6; grid[1][2] = 7; grid[1][4] = 2; grid[1][7] = 1; g...
digits = list(range(1, 10)) grid = [[0 for i in range(9)] for j in range(9)] grid[0][0] = 1 grid[0][3] = 6 grid[0][5] = 5 grid[0][6] = 4 grid[0][8] = 3 grid[1][0] = 6 grid[1][2] = 7 grid[1][4] = 2 grid[1][7] = 1 grid[2][1] = 4 grid[2][4] = 7 grid[2][6] = 2 grid[4][4] = 5 grid[4][5] = 3 grid[4][7] = 4 grid[5][2] = 4 gri...
#example 1 dummy_list = ["one","two","three","four","five","six"] separator = ' ' result_string = separator.join(dummy_list) print(result_string) #example 2 dummy_list = ["one","two","three","four","five","six"] separator = ',' result_string = separator.join(dummy_list) print(result_string)
dummy_list = ['one', 'two', 'three', 'four', 'five', 'six'] separator = ' ' result_string = separator.join(dummy_list) print(result_string) dummy_list = ['one', 'two', 'three', 'four', 'five', 'six'] separator = ',' result_string = separator.join(dummy_list) print(result_string)
class CameraInfo : ''' Camera Information. Attributes ---------- model: Camera model. firmware: Firmware version. uid: Camera identification. resolution: Camera resolution port: Serial port ''' def __init__(self, _model, _firm...
class Camerainfo: """ Camera Information. Attributes ---------- model: Camera model. firmware: Firmware version. uid: Camera identification. resolution: Camera resolution port: Serial port """ def __init__(self, _model, _firmw...
def ComputeR10_1(scores,labels,count = 10): total = 0 correct = 0 for i in range(len(labels)): if labels[i] == 1: total = total+1 sublist = scores[i:i+count] if max(sublist) == scores[i]: correct = correct + 1 print(float(correct)/ total ) def...
def compute_r10_1(scores, labels, count=10): total = 0 correct = 0 for i in range(len(labels)): if labels[i] == 1: total = total + 1 sublist = scores[i:i + count] if max(sublist) == scores[i]: correct = correct + 1 print(float(correct) / total)...
class CallAfterCommitMiddleware(object): def process_response(self, request, response): try: callbacks = request._post_commit_callbacks except AttributeError: callbacks = [] for fn, args, kwargs in callbacks: fn(*args, **kwargs) return response
class Callaftercommitmiddleware(object): def process_response(self, request, response): try: callbacks = request._post_commit_callbacks except AttributeError: callbacks = [] for (fn, args, kwargs) in callbacks: fn(*args, **kwargs) return response
# execute with python ./part1.py def trees_met(map: list, right: int, down: int): trees = 0 idx_of_column = 0 idx_of_row = 0 length_of_row = len(map[0])-1 # so that we do not count the newline character!!! while idx_of_row < len(map)-1: idx_of_row = idx_of_row + down row = map[idx_o...
def trees_met(map: list, right: int, down: int): trees = 0 idx_of_column = 0 idx_of_row = 0 length_of_row = len(map[0]) - 1 while idx_of_row < len(map) - 1: idx_of_row = idx_of_row + down row = map[idx_of_row] idx_of_column = idx_of_column + right if idx_of_column > l...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Jon Hawkesworth (@jhawkesworth) <figs@unity.demon.co.uk> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # this is a windows documentation stub. actual code lives in the .ps1 # file of the same name ANSIBLE...
ansible_metadata = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} documentation = '\n---\nmodule: win_msg\nversion_added: "2.3"\nshort_description: Sends a message to logged in users on Windows hosts\ndescription:\n - Wraps the msg.exe command in order to send messages to Windows hos...
def greeting(): text= "Hello World" print(text) if __name__== '__main__': greeting()
def greeting(): text = 'Hello World' print(text) if __name__ == '__main__': greeting()
# # PySNMP MIB module SNMP-NOTIFICATION-MIB (http://pysnmp.sf.net) # ASN.1 source file:///usr/share/snmp/mibs/SNMP-NOTIFICATION-MIB.txt # Produced by pysmi-0.0.5 at Sat Sep 19 23:00:18 2015 # On host grommit.local platform Darwin version 14.4.0 by user ilya # Using Python version 2.7.6 (default, Sep 9 2014, 15:04:36) ...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ...
n = int(input()) w = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n)] syussya = [0] * (n*2) for s, _ in w: syussya[s] += 1 for i in range(1, n*2): syussya[i] += syussya[i-1] for s, t in w: print(syussya[t] - syussya[s])
n = int(input()) w = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] syussya = [0] * (n * 2) for (s, _) in w: syussya[s] += 1 for i in range(1, n * 2): syussya[i] += syussya[i - 1] for (s, t) in w: print(syussya[t] - syussya[s])
USERS = {'editor':'editor', 'viewer':'viewer'} GROUPS = {'editor':['group:editors'], 'viewer':['group:viewers']} def groupfinder(userid, request): if userid in USERS: return GROUPS.get(userid,[])
users = {'editor': 'editor', 'viewer': 'viewer'} groups = {'editor': ['group:editors'], 'viewer': ['group:viewers']} def groupfinder(userid, request): if userid in USERS: return GROUPS.get(userid, [])
# Autogenerated by devscripts/update-version.py __version__ = '2021.12.01' RELEASE_GIT_HEAD = '91f071af6'
__version__ = '2021.12.01' release_git_head = '91f071af6'
# ------------------------------------------------------------------------------ # Access to the CodeHawk Binary Analyzer Analysis Results # Author: Henny Sipma # ------------------------------------------------------------------------------ # The MIT License (MIT) # # Copyright (c) 2016-2020 Kestrel Technology LLC # #...
class Stringxrefs(object): def __init__(self, stringsxrefs, xnode): self.stringsxrefs = stringsxrefs self.xnode = xnode self.strval = self.stringsxrefs.bdictionary.read_xml_string(self.xnode) self.addr = self.xnode.get('a') self.xrefs = [] self._initialize() def...
#encoding:utf-8 subreddit = 'Windows10' t_channel = '@r_Windows10' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'Windows10' t_channel = '@r_Windows10' def send_post(submission, r2t): return r2t.send_simple(submission)
s, f, l = input('String='), input('First Letter='), input('Second Letter=') for i in range(1): f_in, l_in = s.rindex(f), s.index(l) if f_in == -1 or l_in == -1 or f_in > l_in: print(False) else: print(True)
(s, f, l) = (input('String='), input('First Letter='), input('Second Letter=')) for i in range(1): (f_in, l_in) = (s.rindex(f), s.index(l)) if f_in == -1 or l_in == -1 or f_in > l_in: print(False) else: print(True)
class Solution: def romanToInt(self, s: str) -> int: return self.get_roman(self.roman_numerals(), s) @staticmethod def roman_numerals(): numerals = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M'...
class Solution: def roman_to_int(self, s: str) -> int: return self.get_roman(self.roman_numerals(), s) @staticmethod def roman_numerals(): numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} return numerals @staticmethod def get_roman(numerals, s):...
# https://www.hackerrank.com/challenges/py-set-mutations/problem s = [set(map(int, input().split())) for _ in range(2)][1] # 16 # len(s) # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52 methods1 = { "update": s.update, "difference_update": s.difference_update, "intersection_update": s.intersection_update, ...
s = [set(map(int, input().split())) for _ in range(2)][1] methods1 = {'update': s.update, 'difference_update': s.difference_update, 'intersection_update': s.intersection_update, 'symmetric_difference_update': s.symmetric_difference_update} def methods2(m, s, sub_s): if m == 'update': s |= sub_s elif m ...
#!/usr/local/bin/python3.7 #!/usr/bin/env python3 #!/usr/bin/python3 for i1 in range(32, 127): c1 = chr(i1) print(("%d %s" % (i1, c1)))
for i1 in range(32, 127): c1 = chr(i1) print('%d %s' % (i1, c1))
# terrascript/resource/grafana.py __all__ = []
__all__ = []
## Number Zoo Patrol ## 6 kyu ## https://www.codewars.com//kata/5276c18121e20900c0000235 def find_missing_number(numbers): numbers = set(numbers) if len(numbers) == 0: return 1 for i in range(1,max(numbers)+2): if i not in numbers: return i
def find_missing_number(numbers): numbers = set(numbers) if len(numbers) == 0: return 1 for i in range(1, max(numbers) + 2): if i not in numbers: return i
# datasetPreprocess.py # Preprocessing should should have a fit and a transform step def convert_numpy(df): return df.to_numpy() def drop_columns(df, ids): return df.drop(ids, axis = 1) def recode(df): df["Bound"] = 2*df["Bound"] - 1 return df def squeeze(array): return array.squeeze()
def convert_numpy(df): return df.to_numpy() def drop_columns(df, ids): return df.drop(ids, axis=1) def recode(df): df['Bound'] = 2 * df['Bound'] - 1 return df def squeeze(array): return array.squeeze()
# bergWeight.by # A program that asks user for the weight of a single Berg Bar and the total number of # bars made that month as inputs. # Outputs the total weight of pounds and ounces of all Berg Bar for the month # Name: Ben Goldstone # Date 9/8/2020 weightOfSingleBar = float(input("What was the weight of a single Be...
weight_of_single_bar = float(input('What was the weight of a single Berg Bar? ')) total_number_of_bars = int(input('How many bars were produced? ')) total_weight = weightOfSingleBar * totalNumberOfBars lbs = int(totalWeight // 16) oz = totalWeight % 16 oz_to_grams = 28.34952 bar_in_grams = weightOfSingleBar * OZ_TO_GRA...
account_error = {"status": "error", "message": "username or password error!"}, 400 teacher_not_found = {"status": "error", "message": "teacher not found!"}, 400 topic_not_found = {"status": "error", "message": "topic not found!"}, 400 file_not_found = {"status": "error", "message": "file not found!"}, 400 upload_error ...
account_error = ({'status': 'error', 'message': 'username or password error!'}, 400) teacher_not_found = ({'status': 'error', 'message': 'teacher not found!'}, 400) topic_not_found = ({'status': 'error', 'message': 'topic not found!'}, 400) file_not_found = ({'status': 'error', 'message': 'file not found!'}, 400) uploa...
class Solution: # @return a string def countAndSay(self, n): pre = "1" for i in range(n-1): pre = self.f(pre) return pre def f(self, s): ans = "" pre = s[0] cur = 1 for c in s[1:]: if c == pre: cur = cur + 1...
class Solution: def count_and_say(self, n): pre = '1' for i in range(n - 1): pre = self.f(pre) return pre def f(self, s): ans = '' pre = s[0] cur = 1 for c in s[1:]: if c == pre: cur = cur + 1 else: ...
class Solution: def minWindow(self, s: str, t: str) -> str: if t == "": return "" count,window = {},{} res = [-1,-1] ;reslen = float("inf") for c in t : count[c] = 1 + count.get(c,0) have,need = 0, len(count) l = 0 ...
class Solution: def min_window(self, s: str, t: str) -> str: if t == '': return '' (count, window) = ({}, {}) res = [-1, -1] reslen = float('inf') for c in t: count[c] = 1 + count.get(c, 0) (have, need) = (0, len(count)) l = 0 ...
def find_product(lst): b = 1 ans = [] for i, v in enumerate(lst): tmp = 1 for j in lst[i+1:]: tmp *= j ans.append(tmp * b) b *= v print(ans) return ans assert find_product([1,2,3,4]) == [24,12,8,6] assert find_product([4,2,1,5, 0]) == [0,0,0,0,40]
def find_product(lst): b = 1 ans = [] for (i, v) in enumerate(lst): tmp = 1 for j in lst[i + 1:]: tmp *= j ans.append(tmp * b) b *= v print(ans) return ans assert find_product([1, 2, 3, 4]) == [24, 12, 8, 6] assert find_product([4, 2, 1, 5, 0]) == [0, 0, 0...
CONFIG = dict({ 'demo_battery': [ { 'protocol': 'UDP', 'setup': 'single', 'mode': 'simple', 'size': '1MB', 'test_count': 1 } ], 'full_battery': [ { 'protocol': 'UDP', 'setup': 'single', 'mode': 'simple', 'size': '1MB', 'test_count': 3 }, { 'protocol': 'UDP', 'setup': 'si...
config = dict({'demo_battery': [{'protocol': 'UDP', 'setup': 'single', 'mode': 'simple', 'size': '1MB', 'test_count': 1}], 'full_battery': [{'protocol': 'UDP', 'setup': 'single', 'mode': 'simple', 'size': '1MB', 'test_count': 3}, {'protocol': 'UDP', 'setup': 'single', 'mode': 'simple', 'size': '10MB', 'test_count': 3},...
expected_output = { 'key_chain': { 'ISIS-HELLO-CORE': { 'keys': { '1': { 'accept_lifetime': '00:01:00 january 01 2013 infinite', 'key_string': 'password 020F175218', 'cryptographic_algorithm': 'HMAC-MD5'}}, ...
expected_output = {'key_chain': {'ISIS-HELLO-CORE': {'keys': {'1': {'accept_lifetime': '00:01:00 january 01 2013 infinite', 'key_string': 'password 020F175218', 'cryptographic_algorithm': 'HMAC-MD5'}}, 'accept_tolerance': 'infinite'}}}
x, y, w, h = map(int, input().split()) answer = min(x, y, w-x, h-y) print(answer)
(x, y, w, h) = map(int, input().split()) answer = min(x, y, w - x, h - y) print(answer)
def part1(pairs): depth = 0 h_pos = 0 for cmd, val in pairs: val = int(val) if cmd == "forward": h_pos += val elif cmd == "up": depth -= val elif cmd == "down": depth += val else: raise Exception return h_pos * dept...
def part1(pairs): depth = 0 h_pos = 0 for (cmd, val) in pairs: val = int(val) if cmd == 'forward': h_pos += val elif cmd == 'up': depth -= val elif cmd == 'down': depth += val else: raise Exception return h_pos * dep...
userName = input('Ingresar usuario ') password = int(input('Ingresa pass: ')) if (userName == 'pablo') and (password == 123456): print('Bienvenido') else: print('Acceso denegado')
user_name = input('Ingresar usuario ') password = int(input('Ingresa pass: ')) if userName == 'pablo' and password == 123456: print('Bienvenido') else: print('Acceso denegado')
# # PySNMP MIB module CISCO-MOBILE-IP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-MOBILE-IP-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:07:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) ...
# https://www.codewars.com/kata/string-cleaning/ def string_clean(s): output = "" for symbol in s: if not(symbol.isdigit()): output += symbol return output
def string_clean(s): output = '' for symbol in s: if not symbol.isdigit(): output += symbol return output
#! /usr/bin/python class PySopn: # Initialize instance def __init__(self, iface, port): self.interface = interface self.port = port self.socket = PySopn_eth(iface, port) # Set configuration def configSet(self, config): pass # Open def open(self): self...
class Pysopn: def __init__(self, iface, port): self.interface = interface self.port = port self.socket = py_sopn_eth(iface, port) def config_set(self, config): pass def open(self): self.flgopen = True
class Controller: user = '' mdp = '' url = '' port = 0 timeout = 0 def __init__(self, user, mdp, url, port, timeout): self.user = user self.mdp = mdp self.url = url self.port = int(port) self.timeout = int(timeout)
class Controller: user = '' mdp = '' url = '' port = 0 timeout = 0 def __init__(self, user, mdp, url, port, timeout): self.user = user self.mdp = mdp self.url = url self.port = int(port) self.timeout = int(timeout)
categories_db = \ { 'armors': { 'items': [ 'cuirass', 'banded-mail', 'scale-mail', 'ring-mail', 'chainmail', 'half-plate', 'moon...
categories_db = {'armors': {'items': ['cuirass', 'banded-mail', 'scale-mail', 'ring-mail', 'chainmail', 'half-plate', 'moonplate', 'steel-cuirass', 'full-plate', 'longmail', 'noble-plate', 'silvered-scales', 'arcane-guard', 'runic-mail', 'chaos-armor', 'shining-armor', 'valkyrie-armor', 'white-fullplate', 'eldritch-mai...
# 3-3 Problem1, Problem2, Problem3 sum = 0 for i in range(1, 101): sum += i print('{}'.format(sum)) A = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100] mean = 0.0 for point in A: mean += point mean /= len(A) print('{}'.format(mean)) numbers = [1, 2, 3, 4, 5] result = [n * 2 for n in numbers if ...
sum = 0 for i in range(1, 101): sum += i print('{}'.format(sum)) a = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100] mean = 0.0 for point in A: mean += point mean /= len(A) print('{}'.format(mean)) numbers = [1, 2, 3, 4, 5] result = [n * 2 for n in numbers if n % 2 == 1] print(result)
class Solution: def addStrings(self, num1: str, num2: str) -> str: n1 = 0; n2 = 0; o = 0 for c in num1[::-1]: n1 += int(c)*10**o o += 1 o = 0 for c in num2[::-1]: n2 += int(c)*10**o o += 1 return str(n1+n2)
class Solution: def add_strings(self, num1: str, num2: str) -> str: n1 = 0 n2 = 0 o = 0 for c in num1[::-1]: n1 += int(c) * 10 ** o o += 1 o = 0 for c in num2[::-1]: n2 += int(c) * 10 ** o o += 1 return str(n1 +...
#class method class Employee: raise_amount = 1.04 num_of_emps = 0 def __init__ (self, first, last , pay): self.first = first self.last = last self.email = first + "." + last + "@company.com" self.pay = pay Employee.num_of_emps += 1 def full_n...
class Employee: raise_amount = 1.04 num_of_emps = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.email = first + '.' + last + '@company.com' self.pay = pay Employee.num_of_emps += 1 def full_name(self): return '{} {}'.fo...
# test loading constants in viper functions @micropython.viper def f(): return b'bytes' print(f()) @micropython.viper def f(): @micropython.viper def g() -> int: return 123 return g print(f()())
@micropython.viper def f(): return b'bytes' print(f()) @micropython.viper def f(): @micropython.viper def g() -> int: return 123 return g print(f()())
x = ['apple', 'banana', 'mango', 'orange', 'peach', 'grapes'] def createNewList(l): newList = [] i = 1 while i < 6: newList.append(l[i]) i = i + 1 if i % 2 == 1: i = i + 1 print(newList) createNewList(x)
x = ['apple', 'banana', 'mango', 'orange', 'peach', 'grapes'] def create_new_list(l): new_list = [] i = 1 while i < 6: newList.append(l[i]) i = i + 1 if i % 2 == 1: i = i + 1 print(newList) create_new_list(x)
def find(needle, haystack): for i in range(len(haystack)-len(needle)+1): flag=True for j,char in enumerate(needle): if char=="_": continue elif char!=haystack[i+j]: flag=False break if flag: return i retu...
def find(needle, haystack): for i in range(len(haystack) - len(needle) + 1): flag = True for (j, char) in enumerate(needle): if char == '_': continue elif char != haystack[i + j]: flag = False break if flag: ...
__title__ = 'compas_fab' __description__ = 'Robotic fabrication package for the COMPAS Framework' __url__ = 'https://github.com/gramaziokohler/compas_fab' __version__ = '0.5.0' __author__ = 'Gramazio Kohler Research' __author_email__ = 'gramaziokohler@arch.ethz.ch' __license__ = 'MIT license' __copyright__ = 'Copyright...
__title__ = 'compas_fab' __description__ = 'Robotic fabrication package for the COMPAS Framework' __url__ = 'https://github.com/gramaziokohler/compas_fab' __version__ = '0.5.0' __author__ = 'Gramazio Kohler Research' __author_email__ = 'gramaziokohler@arch.ethz.ch' __license__ = 'MIT license' __copyright__ = 'Copyright...
def garterKnit(k,beg,end,length,c,side='l', knitsettings=[4,400,400], xfersettings=[2,0,300]): if side == 'l': start=1 else: start=2 length=length+1 for b in range(start,length+1): if b%2==1: k.stitchNumber(xfersettings[0]) k.rollerAdvance(xfersetti...
def garter_knit(k, beg, end, length, c, side='l', knitsettings=[4, 400, 400], xfersettings=[2, 0, 300]): if side == 'l': start = 1 else: start = 2 length = length + 1 for b in range(start, length + 1): if b % 2 == 1: k.stitchNumber(xfersettings[0]) k.r...
def resolve(): ''' code here ''' N, M, Q = [int(item) for item in input().split()] a_list = [[int(item) for item in input().split()] for _ in range(Q)] res = 0 for item in comb: temp_res = 0 print(item) for j in a_list: a = j[0]-1 b = ...
def resolve(): """ code here """ (n, m, q) = [int(item) for item in input().split()] a_list = [[int(item) for item in input().split()] for _ in range(Q)] res = 0 for item in comb: temp_res = 0 print(item) for j in a_list: a = j[0] - 1 b = j[1] ...
## @file GenXmlFile.py # # This file contained the logical of generate XML files. # # Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent # ''' GenXmlFile '''
""" GenXmlFile """
# # PySNMP MIB module RBTWS-TRAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBTWS-TRAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:53:51 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_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ...
class MwClientError(RuntimeError): pass class MediaWikiVersionError(MwClientError): pass class APIDisabledError(MwClientError): pass class MaximumRetriesExceeded(MwClientError): pass class APIError(MwClientError): def __init__(self, code, info, kwargs): self.code = code self...
class Mwclienterror(RuntimeError): pass class Mediawikiversionerror(MwClientError): pass class Apidisablederror(MwClientError): pass class Maximumretriesexceeded(MwClientError): pass class Apierror(MwClientError): def __init__(self, code, info, kwargs): self.code = code self.inf...
def plot_table(data): fig = plt.figure() ax = fig.add_subplot(111) col_labels = list(range(0,10)) row_labels = [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '] # Draw table value_table = plt.table(cellText=data, colWidths=[0.05] * 10, rowLabels...
def plot_table(data): fig = plt.figure() ax = fig.add_subplot(111) col_labels = list(range(0, 10)) row_labels = [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '] value_table = plt.table(cellText=data, colWidths=[0.05] * 10, rowLabels=row_labels, colLabels=col_labels, loc='center...
class Settings: def __init__(self): self.screen_width = 800 self.screen_height = 600 self.black = (0, 0, 0) self.white = (255, 255, 255) self.red = (255, 0, 0) self.green = (0, 255, 0) self.blue = (0, 0, 255) self.FPS = 90
class Settings: def __init__(self): self.screen_width = 800 self.screen_height = 600 self.black = (0, 0, 0) self.white = (255, 255, 255) self.red = (255, 0, 0) self.green = (0, 255, 0) self.blue = (0, 0, 255) self.FPS = 90
N = 2 for i in range(1,N): for j in range(1,N): for k in range(1,N): for l in range(1,N): if i**3+j**3==k**3+l**3: print(i,j,k,l)
n = 2 for i in range(1, N): for j in range(1, N): for k in range(1, N): for l in range(1, N): if i ** 3 + j ** 3 == k ** 3 + l ** 3: print(i, j, k, l)
def rainWaterTrapping(arr: list) -> int: n = len(arr) maxL = [1] * n maxR = [1] * n maxL[0] = arr[0] for i in range(1, n): maxL[i] = max(maxL[i - 1], arr[i]) maxR[n - 1] = arr[n - 1] for i in range(n - 2, -1, -1): maxR[i] = max(maxR[i + 1], arr[i]) total_water = 0 ...
def rain_water_trapping(arr: list) -> int: n = len(arr) max_l = [1] * n max_r = [1] * n maxL[0] = arr[0] for i in range(1, n): maxL[i] = max(maxL[i - 1], arr[i]) maxR[n - 1] = arr[n - 1] for i in range(n - 2, -1, -1): maxR[i] = max(maxR[i + 1], arr[i]) total_water = 0 ...
n=int(input()) x=hex(n)[-1] if x.isalpha(): x=ord(x)-87 print(bin(int(x))[-1])
n = int(input()) x = hex(n)[-1] if x.isalpha(): x = ord(x) - 87 print(bin(int(x))[-1])
BLACK = [0x00, 0x00, 0x00] # Floor WHITE = [0xFF, 0xFF, 0xFF] # Wall GOLD = [0xFF, 0xD7, 0x00] # Gold BLUE = [0x00, 0x00, 0xFF] # Player GRAY = [0x55, 0x55, 0x55] # Box GREEN = [0x00, 0xAA, 0x00] # Key PURPLE = [0xC4, 0x00, 0xC4] # Door RED = [0xFF, 0x00, 0x00] # Teleport 1 BROWN = [0xA0, 0x50, 0x00] # Teleport 2
black = [0, 0, 0] white = [255, 255, 255] gold = [255, 215, 0] blue = [0, 0, 255] gray = [85, 85, 85] green = [0, 170, 0] purple = [196, 0, 196] red = [255, 0, 0] brown = [160, 80, 0]
count = 0 sum = 0 print('Before', count, sum) for value in [9, 41, 12, 3, 74, 15]: count = count + 1 sum = sum + value print(count, sum, value) print('After', count, sum, sum / count)
count = 0 sum = 0 print('Before', count, sum) for value in [9, 41, 12, 3, 74, 15]: count = count + 1 sum = sum + value print(count, sum, value) print('After', count, sum, sum / count)
def pattern_thirty_seven(): '''Pattern thirty_seven 1 2 3 4 5 2 5 3 5 4 5 5 ''' num = '12345' for i in range(1, 6): if i == 1: print(' '.join(num)) elif i in range(2, 5): space = -2 * i + 9 # using -2*n + 9 for ge...
def pattern_thirty_seven(): """Pattern thirty_seven 1 2 3 4 5 2 5 3 5 4 5 5 """ num = '12345' for i in range(1, 6): if i == 1: print(' '.join(num)) elif i in range(2, 5): space = -2 * i + 9 output = num[i ...
def listening_algorithm(to,from_): counts = [] to = to.split(' ') for i in range(len(from_)): count = 0 var = from_[i].split(' ') n = min(len(to),len(var)) for j in range(n): if var[j] in to[j]: count += 1 counts.append(count) ...
def listening_algorithm(to, from_): counts = [] to = to.split(' ') for i in range(len(from_)): count = 0 var = from_[i].split(' ') n = min(len(to), len(var)) for j in range(n): if var[j] in to[j]: count += 1 counts.append(count) maxm_ =...
''' 06 - Combining groupby() and resample() A very powerful method in Pandas is .groupby(). Whereas .resample() groups rows by some time or date information, .groupby() groups rows based on the values in one or more columns. For example, rides.groupby('Member type').size() would tell us how many rides there were...
""" 06 - Combining groupby() and resample() A very powerful method in Pandas is .groupby(). Whereas .resample() groups rows by some time or date information, .groupby() groups rows based on the values in one or more columns. For example, rides.groupby('Member type').size() would tell us how many rides there were...
# model settings weight_root = '/home/datasets/mix_data/iMIX/data/models/detectron.vmb_weights/' model = dict( type='M4C', hidden_dim=768, dropout_prob=0.1, ocr_in_dim=3002, encoder=[ dict( type='TextBertBase', text_bert_init_from_bert_base=True, hidden_size=768, params=dict(num_...
weight_root = '/home/datasets/mix_data/iMIX/data/models/detectron.vmb_weights/' model = dict(type='M4C', hidden_dim=768, dropout_prob=0.1, ocr_in_dim=3002, encoder=[dict(type='TextBertBase', text_bert_init_from_bert_base=True, hidden_size=768, params=dict(num_hidden_layers=3)), dict(type='ImageFeatureEncoder', encoder_...
bot_token = "" # Bot token stored as string bot_prefix = "" # bot prefix stored as string log_level = "INFO" # log level stored as string jellyfin_url = "" # jellyfin base url stored as string jellyfin_api_key = "" # jellyfin API key stored as string plex_url = "" # plex base url, stored as string plex_api_key = "" #...
bot_token = '' bot_prefix = '' log_level = 'INFO' jellyfin_url = '' jellyfin_api_key = '' plex_url = '' plex_api_key = '' plex_access_role = 0 guild_id = 0 plex_admin_role = 0
def run_diagnostic_program(program): instruction_lengths = [0, 4, 4, 2, 2, 3, 3, 4, 4] i = 0 while i < len(program): opcode = program[i] % 100 modes = [(program[i] // 10**j) % 10 for j in range(2, 5)] if opcode == 99: break instruction_length = instruction_lengths...
def run_diagnostic_program(program): instruction_lengths = [0, 4, 4, 2, 2, 3, 3, 4, 4] i = 0 while i < len(program): opcode = program[i] % 100 modes = [program[i] // 10 ** j % 10 for j in range(2, 5)] if opcode == 99: break instruction_length = instruction_lengths...
# In python lambda stands for an anonymous function. # A lambda function can only perform one lines worth of operations on a given input. greeting = lambda name: 'Hello ' + name print(greeting('Viewers')) # You can also use lambda with map(...) and filter(...) functions names = ['Sherry', 'Jeniffer', 'Ron', 'Sam', '...
greeting = lambda name: 'Hello ' + name print(greeting('Viewers')) names = ['Sherry', 'Jeniffer', 'Ron', 'Sam', 'Messi'] s_manes = list(filter(lambda name: name.lower().startswith('s'), names)) print(s_manes) greetings = list(map(lambda name: 'Hey ' + name, s_manes)) print(greetings)
{ "targets": [ { "target_name": "MagickCLI", "sources": ["src/magick-cli.cc"], 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")" ], 'dependencies': [ "<!(node -p \...
{'targets': [{'target_name': 'MagickCLI', 'sources': ['src/magick-cli.cc'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'dependencies': ['<!(node -p "require(\'node-addon-api\').gyp")'], 'conditions': [['OS=="linux" or OS=="s...
# -*- coding: utf-8 -*- ############################################## # Export CloudWatch metric data to csv file # Configuration file ############################################## METRICS = { 'CPUUtilization': ['AWS/EC2', 'AWS/RDS'], 'CPUCreditUsage': ['AWS/EC2', 'AWS/RDS'], 'CPUCreditBalance': ['AWS/EC2', 'AWS/...
metrics = {'CPUUtilization': ['AWS/EC2', 'AWS/RDS'], 'CPUCreditUsage': ['AWS/EC2', 'AWS/RDS'], 'CPUCreditBalance': ['AWS/EC2', 'AWS/RDS'], 'DiskReadOps': ['AWS/EC2'], 'DiskWriteOps': ['AWS/EC2'], 'DiskReadBytes': ['AWS/EC2'], 'DiskWriteBytes': ['AWS/EC2'], 'NetworkIn': ['AWS/EC2'], 'NetworkOut': ['AWS/EC2'], 'NetworkPa...
NORTH, EAST, SOUTH, WEST = range(4) class Compass(object): compass = [NORTH, EAST, SOUTH, WEST] def __init__(self, bearing=NORTH): self.bearing = bearing def left(self): self.bearing = self.compass[self.bearing - 1] def right(self): self.bearing = self.compass[(self.bearing ...
(north, east, south, west) = range(4) class Compass(object): compass = [NORTH, EAST, SOUTH, WEST] def __init__(self, bearing=NORTH): self.bearing = bearing def left(self): self.bearing = self.compass[self.bearing - 1] def right(self): self.bearing = self.compass[(self.bearing...
class SavingsAccount: '''Defines a savings account''' #static variables RATE = 0.02 MIN_BALANCE = 25 def __init__(self, name, pin, balance = 0.0): self.name = name self.pin = pin self.balance = balance def __str__(self): result = "Name: " + self.name + "\n...
class Savingsaccount: """Defines a savings account""" rate = 0.02 min_balance = 25 def __init__(self, name, pin, balance=0.0): self.name = name self.pin = pin self.balance = balance def __str__(self): result = 'Name: ' + self.name + '\n' result += 'PIN: ' + ...
MICROSERVICES = { # Map locations to their microservices "LOCATION_MICROSERVICES": [ { "module": "intelligence.welcome.location_welcome_microservice", "class": "LocationWelcomeMicroservice" } ] }
microservices = {'LOCATION_MICROSERVICES': [{'module': 'intelligence.welcome.location_welcome_microservice', 'class': 'LocationWelcomeMicroservice'}]}
ADDRESS_STR = '' PRIVATE_KEY_STR = '' GAS = 210000 GAS_PRICE = 5000000000 SECONDS_LEFT = 25 SELL_AFTER_WIN = False
address_str = '' private_key_str = '' gas = 210000 gas_price = 5000000000 seconds_left = 25 sell_after_win = False
track_width = 0.6603288840524426 track_original = [(3.9968843292236325, -2.398085115814209), (4.108486819458006, -2.398085115814209), (4.220117408752442, -2.398085115814209), (4.331728619384766, -2.3980848251342772), (4.443350294494627, -2.398085115814209), (4.554988441467286, -2.398...
track_width = 0.6603288840524426 track_original = [(3.9968843292236325, -2.398085115814209), (4.108486819458006, -2.398085115814209), (4.220117408752442, -2.398085115814209), (4.331728619384766, -2.3980848251342772), (4.443350294494627, -2.398085115814209), (4.554988441467286, -2.398085115814209), (4.666571746826172, -...
class DealProposal(object): ''' Holds details about a deal proposed by one player to another. ''' def __init__( self, propose_to_player=None, properties_offered=None, properties_wanted=None, maximum_cash_offered=0, minimum_cash_wan...
class Dealproposal(object): """ Holds details about a deal proposed by one player to another. """ def __init__(self, propose_to_player=None, properties_offered=None, properties_wanted=None, maximum_cash_offered=0, minimum_cash_wanted=0): """ The 'constructor'. properties_offere...
email = input() while True: line = input() if line == 'Complete': break args = line.split() command = args[0] if command == 'Make': result = '' if args[1] == 'Upper': for ch in email: if ch.isalpha(): ch = ch.upp...
email = input() while True: line = input() if line == 'Complete': break args = line.split() command = args[0] if command == 'Make': result = '' if args[1] == 'Upper': for ch in email: if ch.isalpha(): ch = ch.upper() ...
# B_R_R # M_S_A_W # Accept a string # Encode the received string into unicodes # And decipher the unicodes back to its original form # Convention of assigning characters with unicodes # A - Z ---> 65-90 # a - z ---> 97-122 # ord("A") ---> 65 # chr(65) ---> A # Enter a string to encode in uppercase giv...
given_str = input('What is your word in mind(in uppercase please): ').upper() secret_str = '' norm_str = '' for char in givenStr: secret_str += str(ord(char)) print('The encrypted string is --->', secretStr) for i in range(0, len(secretStr) - 1, 2): char_code = secretStr[i] + secretStr[i + 1] norm_str += ch...
# Backtracking is a general algorithm for finding all (or some) solutions to some computational problems, notably # constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate # ("backtracks") as soon as it determines that the candidate cannot possibly be complete...
def backtracking(self, data, candidate): if self.reject(data, candidate): return if self.accept(data, candidate): return self.output(data, candidate) for cur_candidate in self.all_extension(data, candidate): if not self.should_to_be_pruned(cur_candidate): self.backtrackin...
f = open('input.txt').readlines() f = [line.strip().split(')') for line in f] nodes = {} for line in f: nodes[line[1]] = set() nodes['COM'] = set() for line in f: nodes[line[0]].add(line[1]) def predecessors(n): global nodes if n == 'COM': return set([n]) for p in nodes: if n ...
f = open('input.txt').readlines() f = [line.strip().split(')') for line in f] nodes = {} for line in f: nodes[line[1]] = set() nodes['COM'] = set() for line in f: nodes[line[0]].add(line[1]) def predecessors(n): global nodes if n == 'COM': return set([n]) for p in nodes: if n in nod...
#Creating a single link list static (Example-1) class Node: def __init__(self): self.data=None self.nxt=None def assign_data(self,val): self.data=val def assign_add(self,addr): self.nxt=addr class ListPrint: def printLinklist(self,tmp): while(tm...
class Node: def __init__(self): self.data = None self.nxt = None def assign_data(self, val): self.data = val def assign_add(self, addr): self.nxt = addr class Listprint: def print_linklist(self, tmp): while tmp: print(tmp.data, end=' ') ...
# a *very* minimal conversion from a bitstream only fpga to fpga binary format # that can be loaded by the qorc-sdk bootloader(v2.1 or above) # 8 word header: # bin version = 0.1 = 0x00000001 # bitstream size = 75960 = 0x000128B8 # bitstream crc = 0x0 (not used) # meminit size = 0x0 (not used) # meminit crc = 0x0 (n...
header = [1, 75960, 0, 0, 0, 0, 0, 0] fpga_binary_bytearray = bytearray() for each_word in header: fpga_binary_bytearray.extend(int(each_word).to_bytes(4, 'little')) with open('usb2serial.bit', 'rb') as fpga_bitstream: fpga_binary_bytearray.extend(fpga_bitstream.read()) with open('usb2serial_fpga.bin', 'wb') as...
class WrapperBase(object): def __init__(self, instance_to_wrap): self.wrapped = instance_to_wrap def __getattr__(self, item): assert item not in dir(self) return self.wrapped.__getattribute__(item)
class Wrapperbase(object): def __init__(self, instance_to_wrap): self.wrapped = instance_to_wrap def __getattr__(self, item): assert item not in dir(self) return self.wrapped.__getattribute__(item)
def busca(inicio, fim, elemento, A): if (fim >= inicio): terco1 = inicio + (fim - inicio) // 3 terco2 = fim - (fim - inicio) // 3 if (A[terco1] == elemento): return terco1 if (A[terco2] == elemento): return terco2 if (elemento < A[terco1]): ...
def busca(inicio, fim, elemento, A): if fim >= inicio: terco1 = inicio + (fim - inicio) // 3 terco2 = fim - (fim - inicio) // 3 if A[terco1] == elemento: return terco1 if A[terco2] == elemento: return terco2 if elemento < A[terco1]: return ...
for _ in range(int(input())): n = int(input()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] s = "" for i in range(n): b[i] -= a[i] for i in range(1,n): s += str(abs(b[i] - b[i - 1])) print("TAK") if (s == s[::-1]) else print("NIE")
for _ in range(int(input())): n = int(input()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] s = '' for i in range(n): b[i] -= a[i] for i in range(1, n): s += str(abs(b[i] - b[i - 1])) print('TAK') if s == s[::-1] else print('NIE')
#!/usr/bin/python3 class Complex: def __init__(self, realpart, imagpart): self.realpart = realpart self.imagpart = imagpart x = complex(3.0, -4.5) print(x.real, x.imag) class Test: def prt(self): print(self) print(self.__class__) t = Test() t.prt()
class Complex: def __init__(self, realpart, imagpart): self.realpart = realpart self.imagpart = imagpart x = complex(3.0, -4.5) print(x.real, x.imag) class Test: def prt(self): print(self) print(self.__class__) t = test() t.prt()
__version__ = 0.1 __all__ = [ "secure", "mft", "logfile", "usnjrnl", ]
__version__ = 0.1 __all__ = ['secure', 'mft', 'logfile', 'usnjrnl']
def transform_type(val): if val == 'payment': return 3 elif val == 'transfer': return 4 elif val == 'cash_out': return 1 elif val == 'cash_in': return 0 elif val == 'debit': return 2 else: return 0 def transform_nameDest(val): dest = val[0] if dest == 'M': return 1 elif dest == '...
def transform_type(val): if val == 'payment': return 3 elif val == 'transfer': return 4 elif val == 'cash_out': return 1 elif val == 'cash_in': return 0 elif val == 'debit': return 2 else: return 0 def transform_name_dest(val): dest = val[0] ...
locs, labels = xticks() xticks(locs, ("-10%", "-6.7%", "-3.3%", "0", "3.3%", "6.7%", "10%")) xlabel("Percentage change") ylabel("Number of Stocks") title("Simulated Market Performance")
(locs, labels) = xticks() xticks(locs, ('-10%', '-6.7%', '-3.3%', '0', '3.3%', '6.7%', '10%')) xlabel('Percentage change') ylabel('Number of Stocks') title('Simulated Market Performance')
{ 'targets': [ { 'target_name': 'yajl', 'type': 'static_library', 'sources': [ 'yajl/src/yajl.c', 'yajl/src/yajl_lex.c', 'yajl/src/yajl_parser.c', 'yajl/src/yajl_buf.c', 'yajl/src/yajl_encode.c', 'yajl/src/yajl_gen.c', 'yajl/src/yajl_alloc.c'...
{'targets': [{'target_name': 'yajl', 'type': 'static_library', 'sources': ['yajl/src/yajl.c', 'yajl/src/yajl_lex.c', 'yajl/src/yajl_parser.c', 'yajl/src/yajl_buf.c', 'yajl/src/yajl_encode.c', 'yajl/src/yajl_gen.c', 'yajl/src/yajl_alloc.c', 'yajl/src/yajl_tree.c', 'yajl/src/yajl_version.c'], 'cflags': ['-Wall', '-fvisib...
def letUsCalculate(): print("Where n is the number of ELEMENTS in the SET, and R is the samples taken in the function\n") print("///////////////////////////////\n") print("///////////////////////////////\n") print("///////////////////////////////\n") print("///////////////////////////////\n") pr...
def let_us_calculate(): print('Where n is the number of ELEMENTS in the SET, and R is the samples taken in the function\n') print('///////////////////////////////\n') print('///////////////////////////////\n') print('///////////////////////////////\n') print('///////////////////////////////\n') ...
n=int(input('Numero:\n')) i=1 while(i*i<=n): i=i+1 print('La parte entera de la raiz cuadrada es: '+str(i-1))
n = int(input('Numero:\n')) i = 1 while i * i <= n: i = i + 1 print('La parte entera de la raiz cuadrada es: ' + str(i - 1))
dados = [] lista = [] maior = menor = 0 while True: lista.append(str(input('Digite um nome: '))) lista.append(float(input('Digite seu peso: '))) while True: escol = str(input('Quer continuar?[S/N] ')).upper().split()[0] if escol in 'SN': break dados.append(lista[:]) lista...
dados = [] lista = [] maior = menor = 0 while True: lista.append(str(input('Digite um nome: '))) lista.append(float(input('Digite seu peso: '))) while True: escol = str(input('Quer continuar?[S/N] ')).upper().split()[0] if escol in 'SN': break dados.append(lista[:]) lista...
class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self, i, x): while i <= self.size: self.tree[i] += x ...
class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self, i, x): while i <= self.size: self.tree[i] += x ...
def print_rules(bit): rules = [] # Bit Toggle rules.append(( "// REG ^= (1 << %d)" % bit, "replace restart {", " ld a, %1", " xor a, #%s" % format((1 << bit) & 0xff, '#04x'), " ld %1, a", "} by {", " bcpl %%1, #%d ; peephole replaced xor b...
def print_rules(bit): rules = [] rules.append(('// REG ^= (1 << %d)' % bit, 'replace restart {', ' ld a, %1', ' xor a, #%s' % format(1 << bit & 255, '#04x'), ' ld %1, a', '} by {', ' bcpl %%1, #%d ; peephole replaced xor by bcpl.' % bit, "} if notUsed('a')")) rules.append(('// REG |= (1 << %d)' ...
class RedirectException(Exception): def __init__(self, redirect_to: str): super().__init__() self.redirect_to = redirect_to
class Redirectexception(Exception): def __init__(self, redirect_to: str): super().__init__() self.redirect_to = redirect_to
AMAZON_COM: str = "https://www.amazon.com/" DBA_DK: str = "https://www.dba.dk/" EXAMPLE_COM: str = "http://example.com/" GOOGLE_COM: str = "https://www.google.com/" JYLLANDSPOSTEN_DK: str = "https://jyllands-posten.dk/" IANA_ORG: str = "https://www.iana.org/domains/reserved" W3SCHOOLS_COM: str = "https://www.w3sc...
amazon_com: str = 'https://www.amazon.com/' dba_dk: str = 'https://www.dba.dk/' example_com: str = 'http://example.com/' google_com: str = 'https://www.google.com/' jyllandsposten_dk: str = 'https://jyllands-posten.dk/' iana_org: str = 'https://www.iana.org/domains/reserved' w3_schools_com: str = 'https://www.w3schools...
def read_file_to_string(filename): with open(filename, 'r') as fin: return fin.read() def write_string_to_file(filename, content): with open(filename, 'w') as fout: fout.write(content)
def read_file_to_string(filename): with open(filename, 'r') as fin: return fin.read() def write_string_to_file(filename, content): with open(filename, 'w') as fout: fout.write(content)
# Coding up the SVM Quiz clf.fit(features_train, labels_train) pred = clf.predict(features_test)
clf.fit(features_train, labels_train) pred = clf.predict(features_test)
# https://www.hackerrank.com/challenges/grading/problem def gradingStudents(grades): rounded = [] for g in grades: if (g < 38) or ((g % 5) < 3) : rounded.append(g) else: rounded.append(g + (5 - (g % 5))) return rounded
def grading_students(grades): rounded = [] for g in grades: if g < 38 or g % 5 < 3: rounded.append(g) else: rounded.append(g + (5 - g % 5)) return rounded