content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# A new variable named "player_1_score" is created to hold player 1's score. # It is assigned an initial value of 0 since the game is just starting and # player 1 hasn't scored any points yet. player_1_score = 0 # A new variable named "player_2_score" is created to hold player 2's score. # It is assigned an initial val...
player_1_score = 0 player_2_score = 0 loop_until_user_chooses_to_exit_after_a_round = True while LOOP_UNTIL_USER_CHOOSES_TO_EXIT_AFTER_A_ROUND: player_1_shape = input('[PLAYER 1]: Choose "rock", "paper", or "scissors": ') player_2_shape = input('[PLAYER 2]: Choose "rock", "paper", or "scissors": ') rock_sha...
class User: ''' class that generates new instance of user ''' user_list = [] def __init__(self, login_name, password): ''' this method ddefines properties for our user object ''' self.login_name = login_name self.password = password def save_user(self): ...
class User: """ class that generates new instance of user """ user_list = [] def __init__(self, login_name, password): """ this method ddefines properties for our user object """ self.login_name = login_name self.password = password def save_user(self): ...
def writeLines(file, lines): f = open(file, "w") data ="\n".join(lines) f.write(data) f.close()
def write_lines(file, lines): f = open(file, 'w') data = '\n'.join(lines) f.write(data) f.close()
__version = '0.2.2' def get_version(): return __version
__version = '0.2.2' def get_version(): return __version
class GRUNet(ModelBase): def __init__(self, batch_size=100, input_size=2, # input dimension hidden_size=100, num_classes=1): super(GRUNet, self).__init__() self.add_param(name='Wx', shape=(input_size, 2*hidden_size))\ ....
class Grunet(ModelBase): def __init__(self, batch_size=100, input_size=2, hidden_size=100, num_classes=1): super(GRUNet, self).__init__() self.add_param(name='Wx', shape=(input_size, 2 * hidden_size)).add_param(name='Wh', shape=(hidden_size, 2 * hidden_size)).add_param(name='b', shape=(2 * hidden_s...
n = 0 hosts = [] guests = [] preference_matrix = [] r1 = [] r2 = [] def get_n(data): global n n = int(data[0][:-1]) print(n) if (n % 2) != 0: raise Exception("error: text file has not even number n of people on the first line!") def get_hosts(data): global hosts hosts.extend( [x for...
n = 0 hosts = [] guests = [] preference_matrix = [] r1 = [] r2 = [] def get_n(data): global n n = int(data[0][:-1]) print(n) if n % 2 != 0: raise exception('error: text file has not even number n of people on the first line!') def get_hosts(data): global hosts hosts.extend([x for x in ...
# default separator (whitespace) print("a b".split()) print(" a b ".split(None)) print(" a b ".split(None, 1)) print(" a b ".split(None, 2)) print(" a b c ".split(None, 1)) print(" a b c ".split(None, 0)) print(" a b c ".split(None, -1)) # empty separator should fail try: "ab...
print('a b'.split()) print(' a b '.split(None)) print(' a b '.split(None, 1)) print(' a b '.split(None, 2)) print(' a b c '.split(None, 1)) print(' a b c '.split(None, 0)) print(' a b c '.split(None, -1)) try: 'abc'.split('') except ValueError: print('ValueError') print('a...
# # PySNMP MIB module CISCO-FLEX-LINKS-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-FLEX-LINKS-CAPABILITY # Produced by pysmi-0.3.4 at Wed May 1 11:58:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python versio...
(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, constraints_intersection, single_value_constraint) ...
def word_mixer(word_list): word_list.sort() new_words = [] while len(word_list) > 5: new_words.append(word_list.pop(4)) new_words.append(word_list.pop(0)) new_words.append(word_list.pop()) return new_words user_input = input("Enter a saying or poem: ") words_list = user_input.sp...
def word_mixer(word_list): word_list.sort() new_words = [] while len(word_list) > 5: new_words.append(word_list.pop(4)) new_words.append(word_list.pop(0)) new_words.append(word_list.pop()) return new_words user_input = input('Enter a saying or poem: ') words_list = user_input.spl...
seq_length = 26 embedding_dim = 300 data_img = 'data/data_img.h5' data_prepo = 'data/data_prepro.h5' data_prepo_meta = 'data/data_prepro.json' embedding_matrix_filename = 'data/ckpts/embeddings_%s.h5'%embedding_dim glove_path = 'data/glove.6B.300d.txt' train...
seq_length = 26 embedding_dim = 300 data_img = 'data/data_img.h5' data_prepo = 'data/data_prepro.h5' data_prepo_meta = 'data/data_prepro.json' embedding_matrix_filename = 'data/ckpts/embeddings_%s.h5' % embedding_dim glove_path = 'data/glove.6B.300d.txt' train_questions_path = 'data/MultipleChoice_mscoco_train2014_ques...
# The Dictionary sandwich = {'size:': 'small', 'smell': 'dank', 'price': 'cheap'} # Create dictionary print(sandwich['smell']) # Prints dank print('My sandwich is very ' + sandwich['price'] + '.') # In essence, a dictionary is an unordered list list1 = ['ed' , 'edd' , 'eddy'] list2 = ['fred' , 'fredd...
sandwich = {'size:': 'small', 'smell': 'dank', 'price': 'cheap'} print(sandwich['smell']) print('My sandwich is very ' + sandwich['price'] + '.') list1 = ['ed', 'edd', 'eddy'] list2 = ['fred', 'fredd', 'freddy'] print(str(list1 == list2)) dict1 = {'size:': 'small', 'smell': 'dank', 'price': 'cheap'} dict2 = {'smell': '...
def find_first_binary_search(lst,num): i = 0 j = len(lst) - 1 first = -1 while(i<=j): middle = i + (j-i)//2 if lst[middle] >= num: j = middle - 1 else: i = middle + 1 if lst[middle] == num: first = middle return first def find_last...
def find_first_binary_search(lst, num): i = 0 j = len(lst) - 1 first = -1 while i <= j: middle = i + (j - i) // 2 if lst[middle] >= num: j = middle - 1 else: i = middle + 1 if lst[middle] == num: first = middle return first def fin...
# Input: nums = [2,7,11,15], target = 9 # Output: [0,1] # Output: Because nums[0] + nums[1] == 9, we return [0, 1]. class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: temp = {} for i, num in enumerate(nums): x = target - num if x not in temp: ...
class Solution: def two_sum(self, nums: List[int], target: int) -> List[int]: temp = {} for (i, num) in enumerate(nums): x = target - num if x not in temp: temp[num] = i else: return [temp[x], i]
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n") word = input("Enter a word: ") print(word[::-1])
print('Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n') word = input('Enter a word: ') print(word[::-1])
a = [] b = 0 c = 0 n = int(input()) m = int(input()) for i in range(n): a.append(int(input())) a.sort() while b < m: b += a.pop() c += 1 print(c)
a = [] b = 0 c = 0 n = int(input()) m = int(input()) for i in range(n): a.append(int(input())) a.sort() while b < m: b += a.pop() c += 1 print(c)
np.random.seed(1234) fig, ax = plt.subplots(1) x = 30*np.random.randn(10000) mu = x.mean() median = np.median(x) sigma = x.std() textstr = '$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(mu, median, sigma) ax.hist(x, 50) # these are matplotlib.patch.Patch properties props = dict(boxstyle='round', facecolor='wheat...
np.random.seed(1234) (fig, ax) = plt.subplots(1) x = 30 * np.random.randn(10000) mu = x.mean() median = np.median(x) sigma = x.std() textstr = '$\\mu=%.2f$\n$\\mathrm{median}=%.2f$\n$\\sigma=%.2f$' % (mu, median, sigma) ax.hist(x, 50) props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) ax.text(0.05, 0.95, text...
# All the possible states for a cell. alive = 'a' dead = '.' # These states are intermediate. They happen during the turn. dying = 'd' being_born = 'b'
alive = 'a' dead = '.' dying = 'd' being_born = 'b'
try: print((10).to_bytes(1, "big")) except Exception as e: print(type(e)) try: print(int.from_bytes(b"\0", "big")) except Exception as e: print(type(e))
try: print(10 .to_bytes(1, 'big')) except Exception as e: print(type(e)) try: print(int.from_bytes(b'\x00', 'big')) except Exception as e: print(type(e))
''' https://leetcode.com/problems/two-sum/ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. E...
""" https://leetcode.com/problems/two-sum/ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. E...
class Solution: def toLowerCase(self, s: str) -> str: # Map uppercase alphabet to lowecase alphabet hash_map = dict(zip(string.ascii_uppercase, string.ascii_lowercase)) return ''.join(hash_map[c] if c in hash_map else c for c in s) # Hard-coding ascii values...
class Solution: def to_lower_case(self, s: str) -> str: hash_map = dict(zip(string.ascii_uppercase, string.ascii_lowercase)) return ''.join((hash_map[c] if c in hash_map else c for c in s))
nTerms = int(input("How many terms? ")) n1, n2 = 0, 1 count = 0 if nTerms <= 0: print("Please enter a positive integer") elif nTerms == 1: print("Fibonacci sequence up-to",nTerms,":") print(n1) else: print("Fibonacci sequence:") while count < nTerms: print(n1) nth = n...
n_terms = int(input('How many terms? ')) (n1, n2) = (0, 1) count = 0 if nTerms <= 0: print('Please enter a positive integer') elif nTerms == 1: print('Fibonacci sequence up-to', nTerms, ':') print(n1) else: print('Fibonacci sequence:') while count < nTerms: print(n1) nth = n1 + n2 ...
#!/usr/bin/python3 # create empty list t1 = list() # debug only # skip user input for the filename #fhandle = open('romeo.txt','r') # handle user input for the filename fname = input("Read file: ") try: fhandle = open(fname, 'r') except: print('File cannot be opened', fname) exit() # for each line in f...
t1 = list() fname = input('Read file: ') try: fhandle = open(fname, 'r') except: print('File cannot be opened', fname) exit() for line in fhandle: words = line.split() words.sort() for word in words: if word in t1: continue t1.append(word) t1.sort() print(t1)
class Colorize: def __init__(self, text: str, foreground_color: str = 'default', background_color: str = 'default', center: int = 0) -> None: self.foreground_color: str = foreground_color self.background_color: str = background_color self.center: int = center self.text: str = text.c...
class Colorize: def __init__(self, text: str, foreground_color: str='default', background_color: str='default', center: int=0) -> None: self.foreground_color: str = foreground_color self.background_color: str = background_color self.center: int = center self.text: str = text.center(...
#!/usr/bin/env python # -*- coding: utf-8 -*- spinMultiplicity = 1 energy = { 'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('p16_f12.out'), } frequencies = GaussianLog('p16freq.log') rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[3,1], top=[1,2,12], symmetry=1, fit='best'), HinderedRotor(scanLog=ScanL...
spin_multiplicity = 1 energy = {'CCSD(T)-F12/cc-pVTZ-F12': molpro_log('p16_f12.out')} frequencies = gaussian_log('p16freq.log') rotors = [hindered_rotor(scanLog=scan_log('scan_0.log'), pivots=[3, 1], top=[1, 2, 12], symmetry=1, fit='best'), hindered_rotor(scanLog=scan_log('scan_1.log'), pivots=[3, 9], top=[9, 10, 11, 1...
TEMPLATE_ROOT = "./templates" MODEL_TEMPLATE = "code-templates/model.json" MODEL_GENERATION_LOCATION = TEMPLATE_ROOT + "/json-model/" LAYER_TYPE_DENSE = "dense" LAYER_TYPES = "layer_types" MODEL_GENERATION_TYPE = ".json" MODEL_NAME = "model_name" DENSE_UNITS = "units" DENSE_ACTIVATION_FUNCTION = "activation" DENSE_ID =...
template_root = './templates' model_template = 'code-templates/model.json' model_generation_location = TEMPLATE_ROOT + '/json-model/' layer_type_dense = 'dense' layer_types = 'layer_types' model_generation_type = '.json' model_name = 'model_name' dense_units = 'units' dense_activation_function = 'activation' dense_id =...
# ----------------------------------------------------------------------------- # @brief: # Define some signals used during parallel # ----------------------------------------------------------------------------- # it makes the main trpo agent push its weights into the tunnel START_SIGNAL = 1 # it ends the tr...
start_signal = 1 end_signal = -1 end_rollout_signal = -2 agent_collect_filter_info = 10 agent_synchronize_filter = 20 agent_set_policy_weights = 30
# # PySNMP MIB module BAY-STACK-EAPOL-EXTENSION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-EAPOL-EXTENSION-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:18:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ve...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) ...
class Lexer: def __init__(self, data): self.data = data self.tokens = [] self.keywords = [ 'print' ] def tokenizer(self): for loc in self.data: tmp = [] tid = '' for l in loc: if l == '"' and tid == '': ...
class Lexer: def __init__(self, data): self.data = data self.tokens = [] self.keywords = ['print'] def tokenizer(self): for loc in self.data: tmp = [] tid = '' for l in loc: if l == '"' and tid == '': tid = 'char' tmp ...
def create_board(width, height): ''' Creates a new game board based on input parameters. Args: int: The width of the board int: The height of the board Returns: list: Game board ''' pass def put_player_on_board(board, player): ''' Modifies the game board by placing the pl...
def create_board(width, height): """ Creates a new game board based on input parameters. Args: int: The width of the board int: The height of the board Returns: list: Game board """ pass def put_player_on_board(board, player): """ Modifies the game board by placing the pla...
trigger_content={ "XML String": '<Event><ApiVersion>v2</ApiVersion><Id>92eb2e26-0f24-48aa-1111-de9dac3fb903</Id><DeviceName>Random-Integer-Device</DeviceName>' '<ProfileName>Random-Integer-Device</ProfileName><SourceName>Int32</SourceName><Origin>1540855006469</Origin>' '<Reading...
trigger_content = {'XML String': '<Event><ApiVersion>v2</ApiVersion><Id>92eb2e26-0f24-48aa-1111-de9dac3fb903</Id><DeviceName>Random-Integer-Device</DeviceName><ProfileName>Random-Integer-Device</ProfileName><SourceName>Int32</SourceName><Origin>1540855006469</Origin><Readings><Id>82eb2e26-0f24-48aa-ae4c-de9dac3fb920</I...
num_tests = int(input()) total_allowed = 0 max_dim = [56, 45, 25, 7] for t in range(num_tests): dim = list(map(float, input().split())) # Check dimension if any([x[0] > x[1] for x in zip(dim, max_dim)]): if sum(dim[0:3]) > 125: print("0") continue if dim[3] > 7: print("0") continue ...
num_tests = int(input()) total_allowed = 0 max_dim = [56, 45, 25, 7] for t in range(num_tests): dim = list(map(float, input().split())) if any([x[0] > x[1] for x in zip(dim, max_dim)]): if sum(dim[0:3]) > 125: print('0') continue if dim[3] > 7: print('0') cont...
# # PySNMP MIB module Nortel-Magellan-Passport-DisdnNI2MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-DisdnNI2MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:17:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # U...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_union, value_range_constraint, value_size_constraint, constraints_intersection) ...
def forall(p, domain): for x in domain: if not p(x): return False return True def exists(p, domain): for x in domain: if p(x): return True return False
def forall(p, domain): for x in domain: if not p(x): return False return True def exists(p, domain): for x in domain: if p(x): return True return False
triangle = [] with open('p067_triangle.txt') as f: for line in f: triangle.append([int(n) for n in line.split()]) for row in range(1, len(triangle)): triangle[row - 1].append(0) for col in range(0, len(triangle[row])): triangle[row][col] += max(triangle[row - 1][col], triangle[row - 1][col ...
triangle = [] with open('p067_triangle.txt') as f: for line in f: triangle.append([int(n) for n in line.split()]) for row in range(1, len(triangle)): triangle[row - 1].append(0) for col in range(0, len(triangle[row])): triangle[row][col] += max(triangle[row - 1][col], triangle[row - 1][col -...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"MoralTopology": "00_core.ipynb", "on_click_upload": "00_core.ipynb", "on_submit": "00_core.ipynb", "btn_upload": "00_core.ipynb", "btn_submit": "00_core.ipynb", "...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'MoralTopology': '00_core.ipynb', 'on_click_upload': '00_core.ipynb', 'on_submit': '00_core.ipynb', 'btn_upload': '00_core.ipynb', 'btn_submit': '00_core.ipynb', 'out_pl': '00_core.ipynb', 'data_name': '00_core.ipynb', 'data_label': '00_core.ipynb',...
def su(ar): return sum(ar) ar = list(map(int, input().rstrip().split())) print(su(ar))
def su(ar): return sum(ar) ar = list(map(int, input().rstrip().split())) print(su(ar))
# process word list from https://github.com/hackerb9/gwordlist words = [] for _ in range(9): words.append([]) with open('/home/saul/Downloads/1gramsbyfreq.txt') as fin: for line in fin: text = line.split() if len(text) != 2: continue if not text[0].isalpha(): con...
words = [] for _ in range(9): words.append([]) with open('/home/saul/Downloads/1gramsbyfreq.txt') as fin: for line in fin: text = line.split() if len(text) != 2: continue if not text[0].isalpha(): continue if not text[0].isascii(): continue ...
myint = 7 print(myint) # the below way is another way to do the above print(7) # This will print 7.
myint = 7 print(myint) print(7)
## ## # File auto-generated against equivalent DynamicSerialize Java class class LockTableRequest(object): def __init__(self): self.parmId = None self.dbId = None def getParmId(self): return self.parmId def setParmId(self, parmId): self.parmId = parmId def getDbId(s...
class Locktablerequest(object): def __init__(self): self.parmId = None self.dbId = None def get_parm_id(self): return self.parmId def set_parm_id(self, parmId): self.parmId = parmId def get_db_id(self): return self.dbId def set_db_id(self, dbId): ...
# # PySNMP MIB module RADLAN-Physicaldescription-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-Physicaldescription-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:47:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint) ...
expected_output = { "GigabitEthernet0/0/1": { "service_policy": { "input": { "policy_name": { "TEST": { "class_map": { "class-default": { "match_evaluation": "match-any", ...
expected_output = {'GigabitEthernet0/0/1': {'service_policy': {'input': {'policy_name': {'TEST': {'class_map': {'class-default': {'match_evaluation': 'match-any', 'packets': 0, 'bytes': 0, 'rate': {'interval': 300, 'offered_rate_bps': 0, 'drop_rate_bps': 0}, 'match': ['any']}}}}}}}}
# we use the same function from 1_network_graphs_students def extract_subgraph(G, node): new_G = nx.Graph() for neighbor in G.neighbors(node): new_G.add_edge(node, neighbor) return new_G # then plot akt1_G = extract_subgraph(G, 'AKT1') nx.draw(akt1_G, with_labels=True) plt.show() # alternatively...
def extract_subgraph(G, node): new_g = nx.Graph() for neighbor in G.neighbors(node): new_G.add_edge(node, neighbor) return new_G akt1_g = extract_subgraph(G, 'AKT1') nx.draw(akt1_G, with_labels=True) plt.show() nx.draw(G.subgraph(akt1_G.nodes), with_labels=True)
def load(h): return ({'abbr': 1, 'code': 1, 'title': 'Channel'}, {'abbr': 2, 'code': 2, 'title': 'Pressure level'}, {'abbr': 3, 'code': 3, 'title': 'Pressure layer'}, {'abbr': 4, 'code': 4, 'title': 'Surface'})
def load(h): return ({'abbr': 1, 'code': 1, 'title': 'Channel'}, {'abbr': 2, 'code': 2, 'title': 'Pressure level'}, {'abbr': 3, 'code': 3, 'title': 'Pressure layer'}, {'abbr': 4, 'code': 4, 'title': 'Surface'})
# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights # reserved. Use of this source code is governed by a BSD-style license that # can be found in the LICENSE file. { 'variables': { 'pkg-config': 'pkg-config', 'chromium_code': 1, 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/cef', #...
{'variables': {'pkg-config': 'pkg-config', 'chromium_code': 1, 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/cef', 'revision': '<!(cat CEF_VERSION)>', 'version_mac_dylib': '<!(python ../chrome/tools/build/version.py -f VERSION -f ../chrome/VERSION -t "@CEF_MAJOR@<(revision).@BUILD_HI@.@BUILD_LO@" -e "BUILD_HI=int(BUILD)/...
# button definitions for Logitech ATTACK3 FORWARD_AXIS = 1 TURN_AXIS = 0 ADJUST_AXIS = 2 BUTTON_FIRE = 0 BUTTON_SERVO = 1 BUTTON_SERVO_CENTER = 2 BUTTON_SERVO_LEFT = 3 BUTTON_SERVO_RIGHT = 4 BUTTON_STRAFE = 5 BUTTON_STAND = 10 BUTTON_RELAX = 9
forward_axis = 1 turn_axis = 0 adjust_axis = 2 button_fire = 0 button_servo = 1 button_servo_center = 2 button_servo_left = 3 button_servo_right = 4 button_strafe = 5 button_stand = 10 button_relax = 9
############################################################################ # Copyright 2015 Valerio Morsella # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may no...
test_app_url = 'http://testapp.galenframework.com' class Basepage(object): def __init__(self, driver): self.driver = driver def load(self): pass def for_screen_size(self, width, height): self.driver.set_window_size(width, height) return self class Welcomepage(BasePage): ...
_base_ = [ '../_base_/models/dcgan/dcgan_64x64.py', '../_base_/datasets/unconditional_imgs_64x64.py', '../_base_/default_runtime.py' ] # define dataset # you must set `samples_per_gpu` and `imgs_root` data = dict( samples_per_gpu=128, train=dict(imgs_root='data/lsun/bedroom_train')) # adjust running c...
_base_ = ['../_base_/models/dcgan/dcgan_64x64.py', '../_base_/datasets/unconditional_imgs_64x64.py', '../_base_/default_runtime.py'] data = dict(samples_per_gpu=128, train=dict(imgs_root='data/lsun/bedroom_train')) lr_config = None checkpoint_config = dict(interval=100000, by_epoch=False) custom_hooks = [dict(type='Vis...
FLAGS = { b'\U0001f1e6\U0001f1e9' : 'ca', b'\U0001f1e6\U0001f1ea' : 'ar', b'\U0001f1e6\U0001f1eb' : 'fa', b'\U0001f1e6\U0001f1ec' : 'en', b'\U0001f1e6\U0001f1ee' : None, # anguilla b'\U0001f1e6\U0001f1f1' : 'sq', b'\U0001f1e6\U0001f1f2' : 'hy', b'\U0001f1e6\U0001f1f4' : 'pt', b'\U00...
flags = {b'\\U0001f1e6\\U0001f1e9': 'ca', b'\\U0001f1e6\\U0001f1ea': 'ar', b'\\U0001f1e6\\U0001f1eb': 'fa', b'\\U0001f1e6\\U0001f1ec': 'en', b'\\U0001f1e6\\U0001f1ee': None, b'\\U0001f1e6\\U0001f1f1': 'sq', b'\\U0001f1e6\\U0001f1f2': 'hy', b'\\U0001f1e6\\U0001f1f4': 'pt', b'\\U0001f1e6\\U0001f1f6': None, b'\\U0001f1e6\...
def main(): # input N, M = map(int, input().split()) ABs = [list(map(int, input().split())) for _ in range(N)] # compute ABs.sort(key=lambda x: x[0]) money = 0 for a, b in ABs: if b < M: money += a*b M -= b else: money += a*M break # output print(money) if __name__ ...
def main(): (n, m) = map(int, input().split()) a_bs = [list(map(int, input().split())) for _ in range(N)] ABs.sort(key=lambda x: x[0]) money = 0 for (a, b) in ABs: if b < M: money += a * b m -= b else: money += a * M break print(mon...
# Copyright (c) waltz 2020. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program i...
washington_population = 7614893 countypopulation = {'King County': 2252782, 'Pierce County': 904980, 'Snohomish County': 822083, 'Spokane County': 522798, 'Clark County': 488231, 'Thurston County': 290536, 'Kitsap County': 271473, 'Yakima County': 250873, 'Whatcom County': 229247, 'Benton County': 204390, 'Skagit Count...
#!/bin/env python3 ip=input("Server Address: ") pt=input("Server port: ") gw=input("Gateway address: ") mk=input("Network Mask: ") ss=input("WiFi SSID: ") pw=input("WiFi password: ") cfg=open("server/zxnftp.cfg", "w") cfg.write("ATE0\n") cfg.write("AT+CWMODE=1\n") cfg.write("AT+CIPSTA=\""+ip+"\",\""+gw+"\",\""+mk+"\"\n...
ip = input('Server Address: ') pt = input('Server port: ') gw = input('Gateway address: ') mk = input('Network Mask: ') ss = input('WiFi SSID: ') pw = input('WiFi password: ') cfg = open('server/zxnftp.cfg', 'w') cfg.write('ATE0\n') cfg.write('AT+CWMODE=1\n') cfg.write('AT+CIPSTA="' + ip + '","' + gw + '","' + mk + '"\...
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: l=len(connections) if l<n-2: return -1 if l>n-1: return 0 groups=[connections[1]] for i in range(1,l): m,n=connections[i] flag=0 f...
class Solution: def make_connected(self, n: int, connections: List[List[int]]) -> int: l = len(connections) if l < n - 2: return -1 if l > n - 1: return 0 groups = [connections[1]] for i in range(1, l): (m, n) = connections[i] ...
needed_money = float(input()) money_in_hand = float(input()) spending_days = 0 days = 0 while True: action = input() current_sum = float(input()) days += 1 if action == "spend": money_in_hand -= current_sum if money_in_hand < 0: money_in_hand = 0 spending_days += 1 ...
needed_money = float(input()) money_in_hand = float(input()) spending_days = 0 days = 0 while True: action = input() current_sum = float(input()) days += 1 if action == 'spend': money_in_hand -= current_sum if money_in_hand < 0: money_in_hand = 0 spending_days += 1 ...
XTPVersionType = "char" XTP_LOG_LEVEL = "enum" XTP_PROTOCOL_TYPE = "enum" XTP_EXCHANGE_TYPE = "enum" XTP_MARKET_TYPE = "enum" XTP_PRICE_TYPE = "enum" XTP_SIDE_TYPE = "uint8_t" XTP_POSITION_EFFECT_TYPE = "uint8_t" XTP_ORDER_ACTION_STATUS_TYPE = "enum" XTP_ORDER_STATUS_TYPE = "enum" XTP_ORDER_SUBMIT_STATUS_TYPE = "enum" ...
xtp_version_type = 'char' xtp_log_level = 'enum' xtp_protocol_type = 'enum' xtp_exchange_type = 'enum' xtp_market_type = 'enum' xtp_price_type = 'enum' xtp_side_type = 'uint8_t' xtp_position_effect_type = 'uint8_t' xtp_order_action_status_type = 'enum' xtp_order_status_type = 'enum' xtp_order_submit_status_type = 'enum...
a = int(input()) b = int(input()) c = int(input()) if (a > b, a > c): print(a) elif (a == b, a > c): print(a, ) if (b > a, b > c): print(b) elif (b > a, b == c): print(b, c) if (c > a, c > b): print(c) elif (c == a, c > b): print(a, c) if (a == b, b == c): print(a, b, c)
a = int(input()) b = int(input()) c = int(input()) if (a > b, a > c): print(a) elif (a == b, a > c): print(a) if (b > a, b > c): print(b) elif (b > a, b == c): print(b, c) if (c > a, c > b): print(c) elif (c == a, c > b): print(a, c) if (a == b, b == c): print(a, b, c)
class Solution: # tmp is used to prevent same value of slow def twoSum(self, numbers, target): tmp = numbers[0] + 1 for slow in range(len(numbers)): if numbers[slow] == tmp: continue tmp = slow for fast in range(slow+1, len(numbers)): ...
class Solution: def two_sum(self, numbers, target): tmp = numbers[0] + 1 for slow in range(len(numbers)): if numbers[slow] == tmp: continue tmp = slow for fast in range(slow + 1, len(numbers)): if numbers[slow] + numbers[fast] == t...
# "urlconfs" are really just modules. And they _have_ to be # modules... This sucks badly urlpatterns = []
urlpatterns = []
''' PROBLEM STATEMENT: Given a matrix with m rows and n columns. Print its transpose. Transpose of a matrix is obtained by changing the rows to columns and columns to rows i.e., by changing mat[i][j] to mat[j][i]. ''' # A function to print the transpose of the given matrix def Transpose(mat, m, n): # Cr...
""" PROBLEM STATEMENT: Given a matrix with m rows and n columns. Print its transpose. Transpose of a matrix is obtained by changing the rows to columns and columns to rows i.e., by changing mat[i][j] to mat[j][i]. """ def transpose(mat, m, n): trans = [[0 for y in range(m)] for x in range(n)] for x in range(n)...
class CompositeOutputStream: def __init__(self, streams=()): self.streams = list(streams) def add_stream(self, stream): self.streams.append(stream) def close(self): for stream in self.streams: stream.close() def rotate(self): for stream in self.streams: ...
class Compositeoutputstream: def __init__(self, streams=()): self.streams = list(streams) def add_stream(self, stream): self.streams.append(stream) def close(self): for stream in self.streams: stream.close() def rotate(self): for stream in self.streams: ...
value = 1 if value <= 1 or not (some .chained .call()): print("Failure") else: print("Success")
value = 1 if value <= 1 or not some.chained.call(): print('Failure') else: print('Success')
class CommentManager(): pass # @staticmethod # def generate_comment(cls, item_list)
class Commentmanager: pass
class PlatformOutput(object): # 'show version output showVersionOutput = { 'chassis_detail': 'ASR 9006 4 Line Card Slot Chassis with V2 AC PEM', 'config_register': '0x1922', 'image': 'disk0:asr9k-os-mbi-6.1.4.10I/0x100305/mbiasr9k-rsp3.vm', 'main_mem': 'cisco ASR9K Series (Inte...
class Platformoutput(object): show_version_output = {'chassis_detail': 'ASR 9006 4 Line Card Slot Chassis with V2 AC PEM', 'config_register': '0x1922', 'image': 'disk0:asr9k-os-mbi-6.1.4.10I/0x100305/mbiasr9k-rsp3.vm', 'main_mem': 'cisco ASR9K Series (Intel 686 F6M14S4) processor with 6291456K bytes of memory.', 'o...
def compute_network(matrix,seed=0,min_dcos=0.7,max_neighbors=3,max_nodes=1000): G=nx.Graph() visited = [] visited.append(seed) total = matrix.shape[0] temp = {} while(True): seed = visited.pop() temp[seed]=1 neighbors = {} for i in range(0,total): if seed==i: continue ...
def compute_network(matrix, seed=0, min_dcos=0.7, max_neighbors=3, max_nodes=1000): g = nx.Graph() visited = [] visited.append(seed) total = matrix.shape[0] temp = {} while True: seed = visited.pop() temp[seed] = 1 neighbors = {} for i in range(0, total): ...
class Account: def __init__(self, name): self.name= name self.balance = 0 self.borowed_to = {} def add_money(self,value): self.balance += value def print_balance(self): print(f'{self.name} has {self.balance} pounds') def give(self, person, poun...
class Account: def __init__(self, name): self.name = name self.balance = 0 self.borowed_to = {} def add_money(self, value): self.balance += value def print_balance(self): print(f'{self.name} has {self.balance} pounds') def give(self, person, pounds): i...
LINEAR = [8, 50, 500, 1000, 1000, 1000, 500, 75] CONV_OUT_CHANNEL = [4, 4, 8] CONV_KERNEL_SIZE = [50, 32, 5] CONV_STRIDE = [2, 2, 1] REG_SCALE = 5e-8 BATCH_SIZE = 128 EVAL_STEP = 1000 TRAIN_STEP = 10 LEARN_RATE = 1e-4 DECAY_STEP = 25000 DECAY_RATE = 0.5 X_RANGE = [i for i in range(2, 10 )] Y_RANGE = [i for i in range(1...
linear = [8, 50, 500, 1000, 1000, 1000, 500, 75] conv_out_channel = [4, 4, 8] conv_kernel_size = [50, 32, 5] conv_stride = [2, 2, 1] reg_scale = 5e-08 batch_size = 128 eval_step = 1000 train_step = 10 learn_rate = 0.0001 decay_step = 25000 decay_rate = 0.5 x_range = [i for i in range(2, 10)] y_range = [i for i in range...
def get_occ(pair, insertion, step): if pair not in insertion: return {} result = {insertion[pair] : 1} if step == 1: return result return result | get_occ(pair[0] + insertion[pair], insertion, step - 1) | get_occ(insertion[pair] + pair[1], insertion, step - 1) polymer = "" ...
def get_occ(pair, insertion, step): if pair not in insertion: return {} result = {insertion[pair]: 1} if step == 1: return result return result | get_occ(pair[0] + insertion[pair], insertion, step - 1) | get_occ(insertion[pair] + pair[1], insertion, step - 1) polymer = '' insertion = {} ...
# Find the maximum length subarray with GCD=1 # Difficulty -> Easy # Asked in Zoho # Approach: # If a array has any two element GCD as 1 then the whole array has GCD=1 # using this logic, we will return the length of array as maximum subarray if it has # any two elements with gcd 1 # Utility function to find gcd o...
def gcd(a, b): if b: return gcd(b, a % b) else: return a def gcd_1(arr1): res = arr1[0] for i in range(1, len(arr1)): res = gcd(res, arr1[i]) print(len(arr1) if res == 1 else -1) arr1 = [2, 2, 4] arr2 = [7, 2] print(gcd_1(arr1)) print(gcd_1(arr2))
students = [] for _ in range(int(input())): students.append([input(), float(input())]) lowest = min([student[1] for student in students]) students = [student for student in students if student[1] != lowest] second_lowest = min([student[1] for student in students]) names = [student[0] for student in students if stud...
students = [] for _ in range(int(input())): students.append([input(), float(input())]) lowest = min([student[1] for student in students]) students = [student for student in students if student[1] != lowest] second_lowest = min([student[1] for student in students]) names = [student[0] for student in students if stud...
class IntentionalError(Exception): pass raise IntentionalError()
class Intentionalerror(Exception): pass raise intentional_error()
load( "//rules/common:private/utils.bzl", _collect = "collect", _collect_optionally = "collect_optionally", ) ScalaConfiguration = provider( doc = "Scala compile-time and runtime configuration", fields = { "version": "The Scala full version.", "compiler_classpath": "The compiler cla...
load('//rules/common:private/utils.bzl', _collect='collect', _collect_optionally='collect_optionally') scala_configuration = provider(doc='Scala compile-time and runtime configuration', fields={'version': 'The Scala full version.', 'compiler_classpath': 'The compiler classpath.', 'runtime_classpath': 'The runtime class...
class PersistentObject(object): def __init__(self, **kwargs): fields = super().__getattribute__('fields') d = {} for k in fields: if not k in kwargs: continue d[k] = kwargs[k] super().__setattr__('values', d) def __getattr__(self, name)...
class Persistentobject(object): def __init__(self, **kwargs): fields = super().__getattribute__('fields') d = {} for k in fields: if not k in kwargs: continue d[k] = kwargs[k] super().__setattr__('values', d) def __getattr__(self, name): ...
a = [1, 2, 6, 7, 9, 10, 20, 30] def search_linear(a, x): for y in a: if x == y: return True return False def search_linear_index(a, x): for i in range(len(a)): if a[i] == x: return i return -1 def search_binary(a, x): n = len(a) if...
a = [1, 2, 6, 7, 9, 10, 20, 30] def search_linear(a, x): for y in a: if x == y: return True return False def search_linear_index(a, x): for i in range(len(a)): if a[i] == x: return i return -1 def search_binary(a, x): n = len(a) if n == 0: retur...
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def get_alpha_encoding(num): num_chars = 1 min_range, max_range = 1, 26 while num > max_range: num_chars += 1 min_range = max_range max_range += len(alphabet) ** num_chars chars = list() for _ in range(num_chars): interval = ...
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def get_alpha_encoding(num): num_chars = 1 (min_range, max_range) = (1, 26) while num > max_range: num_chars += 1 min_range = max_range max_range += len(alphabet) ** num_chars chars = list() for _ in range(num_chars): interval ...
# coding: utf-8 n = int(input()) def islucky(a): a = str(a) for ch in a: if ch!='4' and ch!='7': return False return True for i in range(1,n+1): if islucky(i) and n%i==0: print('YES') break else: print('NO')
n = int(input()) def islucky(a): a = str(a) for ch in a: if ch != '4' and ch != '7': return False return True for i in range(1, n + 1): if islucky(i) and n % i == 0: print('YES') break else: print('NO')
# beginning for loop https://repl.it/@thakopian/day-5-for-loops-end#main.py fruits = ['apple', 'peach', 'pear'] for x in fruits: print(x) print(x + ' Pie')
fruits = ['apple', 'peach', 'pear'] for x in fruits: print(x) print(x + ' Pie')
# Complete the plusMinus function below. def plusMinus(arr): contpositive, contnegative, contzero = 0, 0, 0 for i in arr: if i > 0: contpositive += 1 elif i < 0: contnegative += 1 else: contzero += 1 print('{0:.6f}'.format(contpositive/len(arr)))...
def plus_minus(arr): (contpositive, contnegative, contzero) = (0, 0, 0) for i in arr: if i > 0: contpositive += 1 elif i < 0: contnegative += 1 else: contzero += 1 print('{0:.6f}'.format(contpositive / len(arr))) print('{0:.6f}'.format(contnega...
# -*- coding: utf-8 -*- ''' File name: code\sum_of_digits_experience_13\sol_377.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #377 :: Sum of digits, experience 13 # # For more information see: # https://projecteuler.net/problem=377 # P...
""" File name: code\\sum_of_digits_experience_13\\sol_377.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x """ '\nThere are 16 positive integers that do not have a zero in their digits and that have a digital sum equal to 5, namely: \n5, 14, 23, 32, 41, 113, 122, 131, 212, 221, 311...
class CLIArgumentsConst: NUM_OF_PROCESSORS = 'num_processors' PRECISION = 'precision' RESULT_FILE = 'save_to_file' QUIET_OUTPUT = 'quiet_output' GRANULARITY = 'granularity' class DefaultArgumentsValuesConst: PROCESSORS = 1 PRECISION = 3000 OUTPUT_FILE_NAME = 'eulerNumCalculation' GR...
class Cliargumentsconst: num_of_processors = 'num_processors' precision = 'precision' result_file = 'save_to_file' quiet_output = 'quiet_output' granularity = 'granularity' class Defaultargumentsvaluesconst: processors = 1 precision = 3000 output_file_name = 'eulerNumCalculation' gr...
#!/usr/bin/python3 oddEven=50 if oddEven%2==1: print(str(oddEven)+" is odd!") elif oddEven%2==0: print(str(oddEven)+" is even!") else: print("This shouldn't run!")
odd_even = 50 if oddEven % 2 == 1: print(str(oddEven) + ' is odd!') elif oddEven % 2 == 0: print(str(oddEven) + ' is even!') else: print("This shouldn't run!")
def my_function() -> None: # TODO # ^ who knows why this is here? pass def my_function_noqa() -> str: return "bad TODO can be ignored with" # noqa: T400 # This comment has both TODO and XXX
def my_function() -> None: pass def my_function_noqa() -> str: return 'bad TODO can be ignored with'
class TeamsSelection: def simulate(self, preference1, preference2): i, j, c, n = 0, 0, 0, len(preference1) s, r = set(i for i in xrange(1, n + 1)), ["1"] * n while c < n: if c % 2 == 0: while preference1[i] not in s: i += 1 r[pr...
class Teamsselection: def simulate(self, preference1, preference2): (i, j, c, n) = (0, 0, 0, len(preference1)) (s, r) = (set((i for i in xrange(1, n + 1))), ['1'] * n) while c < n: if c % 2 == 0: while preference1[i] not in s: i += 1 ...
# CTCI 3.2: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time. class StackNode: def __init__(self) -> None: self.element:int = None self.min:int = None class Stack: def __init...
class Stacknode: def __init__(self) -> None: self.element: int = None self.min: int = None class Stack: def __init__(self) -> None: self.array = [] def push(self, e: int) -> None: n = stack_node() n.element = e if self.isEmpty() or self.min() >= e: ...
# flake8: noqa elections_resp = { 'kind': 'civicinfo#electionsQueryResponse', 'elections': [{ 'id': '2000', 'name': 'VIP Test Election', 'electionDay': '2021-06-06', 'ocdDivisionId': 'ocd-division/country:us' }, { 'id': '4803', 'name': 'Los Angeles County Elec...
elections_resp = {'kind': 'civicinfo#electionsQueryResponse', 'elections': [{'id': '2000', 'name': 'VIP Test Election', 'electionDay': '2021-06-06', 'ocdDivisionId': 'ocd-division/country:us'}, {'id': '4803', 'name': 'Los Angeles County Election', 'electionDay': '2019-05-14', 'ocdDivisionId': 'ocd-division/country:us/s...
class dont(dict): __slots__ = '__missing__', 'contains', 'getitem' def __init__(self, func, *args): if args: func = partial(func, *args) self.__missing__ = lambda k: s(k, func(k)) setdefault = s = dict.setdefault .__get__(self) self.getitem = ...
class Dont(dict): __slots__ = ('__missing__', 'contains', 'getitem') def __init__(self, func, *args): if args: func = partial(func, *args) self.__missing__ = lambda k: s(k, func(k)) setdefault = s = dict.setdefault.__get__(self) self.getitem = dict.__getitem__.__get_...
class UserAlreadyExists(Exception): pass class UserNotFound(Exception): pass class UserNotValid(Exception): pass
class Useralreadyexists(Exception): pass class Usernotfound(Exception): pass class Usernotvalid(Exception): pass
# ------------------------------------------------------------------ # Warp Sequencer # (C) 2020 Michael DeHaan <michael@michaeldehaan.net> & contributors # Apache2 Licensed # ------------------------------------------------------------------ # allows an application to hook certain events in the code without # subclas...
class Defaultcallback(object): __slots__ = () def on_init(self): pass def on_scene_start(self, scene): print('> starting scene: %s (%s)' % (scene.name, scene.obj_id)) def on_clip_start(self, clip): print('> starting clip: %s (%s)' % (clip.name, clip.obj_id)) def on_clip_s...
# # @lc app=leetcode id=6 lang=python3 # @lc code=start class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s temp = [''] * numRows r = 0 step = 1 for c in s: temp[r] += c if r == 0: step ...
class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s temp = [''] * numRows r = 0 step = 1 for c in s: temp[r] += c if r == 0: step = 1 elif r == numRows - 1: ...
# LITTLE SHINO AND COINS k = int(input()) s = str(input()) counti = 0 for i in range(0,len(s)-k+1,1): counta = 0 ch="" for j in range(i,len(s),1): a = s[j] if counta == k and len(ch)==k: counti = counti + 1 if ch.count(a)>=1 and counta==k: counti...
k = int(input()) s = str(input()) counti = 0 for i in range(0, len(s) - k + 1, 1): counta = 0 ch = '' for j in range(i, len(s), 1): a = s[j] if counta == k and len(ch) == k: counti = counti + 1 if ch.count(a) >= 1 and counta == k: counti = counti + 1 ...
# -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # Copyright (c) 2017, Battelle Memorial Institute # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistri...
class Vertex: def __init__(self, marginal_price, prod_cost, power, continuity=True, power_uncertainty=0.0): self.cost = prod_cost self.marginalPrice = marginal_price self.power = power self.powerUncertainty = power_uncertainty self.continuity = continuity
#!/usr/bin/env python class GeneratorLossArgs: def __init__(self, generated_images, inputs, targets=None, reconstructed_images=None, identity_images=None): self._generated_images = generated_images self._inputs = inputs self._targets = targets self._reconstructed_images = reconstructed_images se...
class Generatorlossargs: def __init__(self, generated_images, inputs, targets=None, reconstructed_images=None, identity_images=None): self._generated_images = generated_images self._inputs = inputs self._targets = targets self._reconstructed_images = reconstructed_images sel...
def solution(answers): answer = [] score = [0, 0, 0] a = [1,2,3,4,5] b = [2,1,2,3,2,4,2,5] c = [3,3,1,1,2,2,4,4,5,5] for i in range(len(answers)): if a[i%len(a)] == answers[i]: score[0] += 1 if b[i%len(b)] == answers[i]: score[1] += 1 if c[...
def solution(answers): answer = [] score = [0, 0, 0] a = [1, 2, 3, 4, 5] b = [2, 1, 2, 3, 2, 4, 2, 5] c = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] for i in range(len(answers)): if a[i % len(a)] == answers[i]: score[0] += 1 if b[i % len(b)] == answers[i]: score[1] +=...
class Solution: def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: for i,j in enumerate(A):# i ->index j -> element # reverse list # then toggle each element A[i] = [ y^1 for y in j[::-1]] return A
class Solution: def flip_and_invert_image(self, A: List[List[int]]) -> List[List[int]]: for (i, j) in enumerate(A): A[i] = [y ^ 1 for y in j[::-1]] return A
a = 7141 b = 54773 m = 259200 def kongr(n): if n > 0: return (a * kongr(n - 1) + b) % m else: return (a * 0 + b) % m def neumann(bin): b1 = "0" * (32 - len(bin[2:])) + bin[2:] b2 = [] for i in range(0, 32, 2): if b1[i:i + 2] == "01": b2.append("0") el...
a = 7141 b = 54773 m = 259200 def kongr(n): if n > 0: return (a * kongr(n - 1) + b) % m else: return (a * 0 + b) % m def neumann(bin): b1 = '0' * (32 - len(bin[2:])) + bin[2:] b2 = [] for i in range(0, 32, 2): if b1[i:i + 2] == '01': b2.append('0') elif ...
table_names = ["players", "tournament_type", "matches", "participating_teams", "heroes", "base_stats", "abilities", "player_characters", "match_description", "match_performance", ...
table_names = ['players', 'tournament_type', 'matches', 'participating_teams', 'heroes', 'base_stats', 'abilities', 'player_characters', 'match_description', 'match_performance', 'teams', 'teams_teams', 'roles', 'teams_player'] attrs = [[('steam_name', 1), ('steam_id', 1), ('name', 1), ('country_of_origin', 1), ('date_...
file = open('result.txt','w') file.write('Hello World!\n') file.write('This is our new text file.\n') file.write('We can create a new line. ') file.write('Cool, isnt it?!') file.close()
file = open('result.txt', 'w') file.write('Hello World!\n') file.write('This is our new text file.\n') file.write('We can create a new line. ') file.write('Cool, isnt it?!') file.close()
# A Python program to demonstrate use of # generator object with next() # A generator function def simpleGeneratorFun(): yield 1 yield 2 yield 3 # x is a generator object x = simpleGeneratorFun() # Iterating over the generator object using next print(x.next()) # In Python 3, __next__() print(x.next()) print(x.nex...
def simple_generator_fun(): yield 1 yield 2 yield 3 x = simple_generator_fun() print(x.next()) print(x.next()) print(x.next())
#!/usr/bin/python # -*- coding: utf-8 # # Copyright (C) 2018 Monument-Software GmbH # # 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 # # Unle...
with open('../libopenrv/keysymdef.h') as f: lines = f.readlines() with open('../libopenrv/key_xkeygen.h', 'wb') as f: f.write('typedef struct SXKeyDefT\n{\n\tconst char* mName;\n\tint mXCode; // xkey code\n\tint mUCode; // unicode value\n} SXKeyDef;\n') f.write('const SXKeyDef xkey_defs[] = \n{\n') firs...
''' .. _snippets-pythonapi-versioning: Python API: Versioning Data =========================== This is the tested source code for the snippets used in :ref:`pythonapi-versioning`. The config file we're using in this example can be downloaded :download:`here <../../examples/snippets/resources/datafs_mongo.yml>`. SetU...
""" .. _snippets-pythonapi-versioning: Python API: Versioning Data =========================== This is the tested source code for the snippets used in :ref:`pythonapi-versioning`. The config file we're using in this example can be downloaded :download:`here <../../examples/snippets/resources/datafs_mongo.yml>`. SetU...
class Matrix: def __init__(self, r, c, d): self.row = r self.column = c self.data = d def __str__(self): return "Matrix({0}, {1}, {2})".format(self.row, self.column, self.data) def __add__(self, other): temp = Matrix(self.row, self.column,[]) i...
class Matrix: def __init__(self, r, c, d): self.row = r self.column = c self.data = d def __str__(self): return 'Matrix({0}, {1}, {2})'.format(self.row, self.column, self.data) def __add__(self, other): temp = matrix(self.row, self.column, []) if self.row =...
def get_coordinate_columns_from_file(infile): coordinate_columns = {} header_split = infile[0].rstrip().split("\t") for column_index in range(0, len(header_split)): if header_split[column_index].upper() == "CHROMOSOME": coordinate_columns["CHROMOSOME"] = column_index elif head...
def get_coordinate_columns_from_file(infile): coordinate_columns = {} header_split = infile[0].rstrip().split('\t') for column_index in range(0, len(header_split)): if header_split[column_index].upper() == 'CHROMOSOME': coordinate_columns['CHROMOSOME'] = column_index elif header_...