content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def outer ():
def inner():
print(x )
x = 12
inner()
outer() | def outer():
def inner():
print(x)
x = 12
inner()
outer() |
print ("--------------------------------------------------")
cad1 = "separar"
print (cad1)
nuevo_string1 = ",".join(cad1)
print (nuevo_string1)
print ("--------------------------------------------------")
cad2 = "mi archivo de texto.txt"
print (cad2)
nuevo_string2 = cad2.split()
nuevo_string2 = "_".join(nuevo_... | print('--------------------------------------------------')
cad1 = 'separar'
print(cad1)
nuevo_string1 = ','.join(cad1)
print(nuevo_string1)
print('--------------------------------------------------')
cad2 = 'mi archivo de texto.txt'
print(cad2)
nuevo_string2 = cad2.split()
nuevo_string2 = '_'.join(nuevo_string2)
print... |
def is_even(n):
if n % 2 == 0:
return True
def is_positive(n):
if n >= 0:
return True
def get_result(collection):
result = [str(x) for x in collection]
return ", ".join(result)
numbers = [int(x) for x in input().split(", ")]
positive_nums = []
negative_nums = []
even_nums = []
odd_nu... | def is_even(n):
if n % 2 == 0:
return True
def is_positive(n):
if n >= 0:
return True
def get_result(collection):
result = [str(x) for x in collection]
return ', '.join(result)
numbers = [int(x) for x in input().split(', ')]
positive_nums = []
negative_nums = []
even_nums = []
odd_nums... |
def multi_print(number = 3, word = "Hallo"):
for i in range(0, number):
print(str(i) + " " + word)
multi_print(1, "Hallo")
print("--")
multi_print()
print("--")
multi_print(2)
print("--")
multi_print(word = "Welt")
print("--")
multi_print(word = "Welt", number = 5)
print("--")
| def multi_print(number=3, word='Hallo'):
for i in range(0, number):
print(str(i) + ' ' + word)
multi_print(1, 'Hallo')
print('--')
multi_print()
print('--')
multi_print(2)
print('--')
multi_print(word='Welt')
print('--')
multi_print(word='Welt', number=5)
print('--') |
"""
The structure of a blockchain, Which is accessed like JSON or a dict.
"""
block = {
"index": 1,
"timestamp": 1506057125.900785,
"transactions": [
{
"sender": "8527147fe1f5426f9dd545de4b27ee00",
"recipient": "a77f5cdfa2934df3954a5c7c7da5df1f",
"amount": 5,
... | """
The structure of a blockchain, Which is accessed like JSON or a dict.
"""
block = {'index': 1, 'timestamp': 1506057125.900785, 'transactions': [{'sender': '8527147fe1f5426f9dd545de4b27ee00', 'recipient': 'a77f5cdfa2934df3954a5c7c7da5df1f', 'amount': 5}], 'proof': 324984774000, 'previous_hash': '2cf24dba5fb0a30e26e8... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
_blank_symbol_ctc = '_'
_pad_symbol = '#'
_characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ\' '
# Export all symbols:
symbols = [_blank_symbol_ctc] + list(_characters) + [_pad_symbol]
# Mappings from symbol to numeric ID and vice versa
# (remember - ID zero ... | _blank_symbol_ctc = '_'
_pad_symbol = '#'
_characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ' "
symbols = [_blank_symbol_ctc] + list(_characters) + [_pad_symbol]
_symbol_to_id = {s: i for (i, s) in enumerate(symbols)}
_id_to_symbol = {i: s for (i, s) in enumerate(symbols)}
def text_to_sequence(text):
""" converts text to s... |
PEER_DID_NUMALGO_0 = "did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V"
DID_DOC_NUMALGO_O_BASE58 = """
{
"id": "did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V",
"authentication": [
{
"id": "did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv2... | peer_did_numalgo_0 = 'did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V'
did_doc_numalgo_o_base58 = '\n {\n "id": "did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkGv22od935YF4s8M7V",\n "authentication": [\n {\n "id": "did:peer:0z6MkqRYqQiSgvZQdnBytw86Qbs2ZWUkG... |
class Solution:
def longestSubsequence(self, arr: List[int], diff: int) -> int:
dp = {}
for num in arr:
if num - diff in dp:
cnt = dp.pop(num - diff)
dp[num] = max(dp.get(num, 0), cnt + 1)
else:
dp[num] = max(dp.get(num, 0), 1)
... | class Solution:
def longest_subsequence(self, arr: List[int], diff: int) -> int:
dp = {}
for num in arr:
if num - diff in dp:
cnt = dp.pop(num - diff)
dp[num] = max(dp.get(num, 0), cnt + 1)
else:
dp[num] = max(dp.get(num, 0), 1... |
numbers = [1, 45, 31, 12, 60]
for number in numbers:
if number % 8 == 0:
print ("THe numbers are unacccepetble")
break
else:
print ("The Numbers are good") | numbers = [1, 45, 31, 12, 60]
for number in numbers:
if number % 8 == 0:
print('THe numbers are unacccepetble')
break
else:
print('The Numbers are good') |
'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
class... | """
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
"""
class... |
class rational:
def __init__(self, x, y):
gcd = self.__gcd(x, y)
self.d = x // gcd # denominator
self.n = y // gcd # numerator
def __gcd(self, x, y):
while y > 0:
x, y = y, x % y
return x
def __add__(self, other):
return rational(
... | class Rational:
def __init__(self, x, y):
gcd = self.__gcd(x, y)
self.d = x // gcd
self.n = y // gcd
def __gcd(self, x, y):
while y > 0:
(x, y) = (y, x % y)
return x
def __add__(self, other):
return rational(self.n * other.d + self.d * other.n, ... |
#module for data updating
def update_data_set(text_file_name:str, data:{'Time':int, "Mood":int, "Age":int}, class_res:int):
'''Given a text file name and data, it will open the text file
and update the file with new data in format "int,int,int" '''
file = open(text_file_name, "a")
elements_for_dat... | def update_data_set(text_file_name: str, data: {'Time': int, 'Mood': int, 'Age': int}, class_res: int):
"""Given a text file name and data, it will open the text file
and update the file with new data in format "int,int,int" """
file = open(text_file_name, 'a')
elements_for_data_input = ['\n', data... |
# https://www.codementor.io/moyosore/a-dive-into-python-closures-and-decorators-part-1-9mpr98pgr
def add_all_arguments(*args):
result = 0
for i in args:
result += i
return result
print(add_all_arguments(1, 5, 7, 9, 10)) # 32
print(add_all_arguments(1, 9)) # 10
print(add_all_arguments(1, 2, 3, ... | def add_all_arguments(*args):
result = 0
for i in args:
result += i
return result
print(add_all_arguments(1, 5, 7, 9, 10))
print(add_all_arguments(1, 9))
print(add_all_arguments(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
print(add_all_arguments(1))
print(add_all_arguments())
def print_arguments(**kwargs):
... |
# Do DFS on input. Maintin a set of keys_collected. Do not push a room if it's there in the keys_collected set.
class Solution(object):
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
S = [rooms[0]]
keys_collected = set([... | class Solution(object):
def can_visit_all_rooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
s = [rooms[0]]
keys_collected = set([0])
while S:
node = S.pop()
for k in node:
if k not in keys_collected:... |
"""Constants"""
DOMAIN = "grocy"
DOMAIN_DATA = "{}_data".format(DOMAIN)
DOMAIN_EVENT = "grocy_updated"
DOMAIN_SERVICE = "{}"
# Integration local data
DATA_GROCY = "grocy"
DATA_DATA = "data"
DATA_ENTITIES = "entities"
DATA_STORE_CONF = "store_conf"
# Domain events
EVENT_ADDED_TO_LIST='added_to_list'
EVENT_SUBTRACT_F... | """Constants"""
domain = 'grocy'
domain_data = '{}_data'.format(DOMAIN)
domain_event = 'grocy_updated'
domain_service = '{}'
data_grocy = 'grocy'
data_data = 'data'
data_entities = 'entities'
data_store_conf = 'store_conf'
event_added_to_list = 'added_to_list'
event_subtract_from_list = 'subtract_from_list'
event_produ... |
number_for_fibonacci = int(input("Enter Fibonacci number: "))
first_num = 0
second_num = 1
while second_num <= number_for_fibonacci:
print(second_num)
first_num, second_num = second_num, first_num + second_num
print("Fibonacci number") | number_for_fibonacci = int(input('Enter Fibonacci number: '))
first_num = 0
second_num = 1
while second_num <= number_for_fibonacci:
print(second_num)
(first_num, second_num) = (second_num, first_num + second_num)
print('Fibonacci number') |
def collected_materials(key_materials_dict:dict, junk_materials_dict:dict, material:str, quantity:int):
if material=="shards" or material=="fragments" or material=="motes":
key_materials_dict[material]+=quantity
else:
if material not in junk_materials.keys():
junk_materials[material]... | def collected_materials(key_materials_dict: dict, junk_materials_dict: dict, material: str, quantity: int):
if material == 'shards' or material == 'fragments' or material == 'motes':
key_materials_dict[material] += quantity
elif material not in junk_materials.keys():
junk_materials[material] = q... |
t_host = "localhost"
t_port = "5432"
t_dbname = "insert_db_name"
t_user = "insert_user"
t_pw = "insert_pw"
photo_request_data = {
"CAD6E": {
"id": 218,
"coords_x": -5.9357153,
"coords_y": 54.5974748,
"land_hash": "1530850C9A6F5FF56B66AC16301584EC"
},
"TES... | t_host = 'localhost'
t_port = '5432'
t_dbname = 'insert_db_name'
t_user = 'insert_user'
t_pw = 'insert_pw'
photo_request_data = {'CAD6E': {'id': 218, 'coords_x': -5.9357153, 'coords_y': 54.5974748, 'land_hash': '1530850C9A6F5FF56B66AC16301584EC'}, 'TEST1': {'id': 1, 'coords_x': 11.111111, 'coords_y': 22.222222, 'land_h... |
def pad_in(string: str, space: int) -> str:
"""
>>> pad_in('abc', 0)
'abc'
>>> pad_in('abc', 2)
' abc'
"""
return "".join([" "] * space) + string
def without_ends(string: str) -> str:
"""
>>> without_ends('abc')
'b'
"""
return string[1:-1]
def without_first(string: ... | def pad_in(string: str, space: int) -> str:
"""
>>> pad_in('abc', 0)
'abc'
>>> pad_in('abc', 2)
' abc'
"""
return ''.join([' '] * space) + string
def without_ends(string: str) -> str:
"""
>>> without_ends('abc')
'b'
"""
return string[1:-1]
def without_first(string: st... |
def algorithm(K1,K2, B, weight_vec, datapoints, true_labels, lambda_lasso, penalty_func_name='norm1', calculate_score=False):
'''
Outer loop is gradient ascent algorithm, the variable 'new_weight_vec' here is the dual variable we are interested in
Inner loop is still our Nlasso algorithm
:para... | def algorithm(K1, K2, B, weight_vec, datapoints, true_labels, lambda_lasso, penalty_func_name='norm1', calculate_score=False):
"""
Outer loop is gradient ascent algorithm, the variable 'new_weight_vec' here is the dual variable we are interested in
Inner loop is still our Nlasso algorithm
:par... |
#!/usr/bin/env python2
class RDHSSet:
def __init__(self, path):
with open(path, 'r') as f:
self.regions = [ tuple(line.strip().split()[:4]) for line in f ]
self.indexmap = { x: i for i, x in enumerate(self.regions) }
self.accessionIndexMap = { x[-1]: i for i, x in enumerate(sel... | class Rdhsset:
def __init__(self, path):
with open(path, 'r') as f:
self.regions = [tuple(line.strip().split()[:4]) for line in f]
self.indexmap = {x: i for (i, x) in enumerate(self.regions)}
self.accessionIndexMap = {x[-1]: i for (i, x) in enumerate(self.regions)}
def __le... |
def getLeapYear(year):
while True:
if year%400==0:
return year
elif year%4==0 and year%100!=0:
return year
else:
year +=1
if __name__=='__main__':
leap_year_list = []
cur_year = int(input("Enter any year :"))
leap_year = getLeapYear(cur_year)
for i in range(15):
leap_year_list.append(leap_year)... | def get_leap_year(year):
while True:
if year % 400 == 0:
return year
elif year % 4 == 0 and year % 100 != 0:
return year
else:
year += 1
if __name__ == '__main__':
leap_year_list = []
cur_year = int(input('Enter any year :'))
leap_year = get_le... |
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print(f"{number} FizzBuzz")
elif number % 3 == 0:
print(f"{number} Fizz")
elif number % 5 == 0:
print(f"{number} Buzz")
else:
print(number)
| for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print(f'{number} FizzBuzz')
elif number % 3 == 0:
print(f'{number} Fizz')
elif number % 5 == 0:
print(f'{number} Buzz')
else:
print(number) |
{{notice}}
workers = 4
errorlog = "{{proj_root}}/run/log/gunicorn.error"
accesslog = "{{proj_root}}/run/log/gunicorn.access"
loglevel = "debug"
bind = ["127.0.0.1:9001"]
| {{notice}}
workers = 4
errorlog = '{{proj_root}}/run/log/gunicorn.error'
accesslog = '{{proj_root}}/run/log/gunicorn.access'
loglevel = 'debug'
bind = ['127.0.0.1:9001'] |
class Relevance(object):
'''Incooperation with result file and qrels file
Attributes:
qid, int, query id
judgement_docid_list: list of list, judged docids in TREC qrels
supervised_docid_list: list, top docids from unsupervised models, e.g. BM25, QL.
'''
def __init__(self, qid, judged_docid_... | class Relevance(object):
"""Incooperation with result file and qrels file
Attributes:
qid, int, query id
judgement_docid_list: list of list, judged docids in TREC qrels
supervised_docid_list: list, top docids from unsupervised models, e.g. BM25, QL.
"""
def __init__(self, qid, judged_do... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: Bocheng.Zhang
@license: Apache Licence
@contact: bocheng0000@gmail.com
@file: config.py
@time: 2019/11/6 10:35
"""
# [environment]
ela_url = "coreservices-mainchain-privnet.elastos.org"
did_url = "coreservices-didsidechain-privnet.elastos.org"
# faucet account
fa... | """
@author: Bocheng.Zhang
@license: Apache Licence
@contact: bocheng0000@gmail.com
@file: config.py
@time: 2019/11/6 10:35
"""
ela_url = 'coreservices-mainchain-privnet.elastos.org'
did_url = 'coreservices-didsidechain-privnet.elastos.org'
faucet = {'address': 'EVpUKLScc3BmTyJ9xnd6aGSv3o8eAtFKNw', 'publickey': '03597... |
def our_range(*args):
start = 0
end = 10
step = 1
if len(args) == 1:
end = args[0]
elif 2 <= len(args) <= 3:
start = args[0]
end = args[1]
if len(args) == 3:
step = args[2]
elif len(args) > 3:
raise SyntaxError
i = start
while i < end... | def our_range(*args):
start = 0
end = 10
step = 1
if len(args) == 1:
end = args[0]
elif 2 <= len(args) <= 3:
start = args[0]
end = args[1]
if len(args) == 3:
step = args[2]
elif len(args) > 3:
raise SyntaxError
i = start
while i < end:
... |
def part1(input_data):
numbers, boards = parse_input(input_data)
for number in numbers:
# Put number on all boards
for board in boards:
for row in board:
for i in range(len(row)):
if number == row[i]:
row[i] = "x"
... | def part1(input_data):
(numbers, boards) = parse_input(input_data)
for number in numbers:
for board in boards:
for row in board:
for i in range(len(row)):
if number == row[i]:
row[i] = 'x'
for board in boards:
fo... |
load("@bazel_skylib//lib:paths.bzl", "paths")
load(
"//caffe2/test:defs.bzl",
"define_tests",
)
def define_pipeline_tests():
test_files = native.glob(["**/test_*.py"])
TESTS = {}
for test_file in test_files:
test_file_name = paths.basename(test_file)
test_name = test_file_name.rep... | load('@bazel_skylib//lib:paths.bzl', 'paths')
load('//caffe2/test:defs.bzl', 'define_tests')
def define_pipeline_tests():
test_files = native.glob(['**/test_*.py'])
tests = {}
for test_file in test_files:
test_file_name = paths.basename(test_file)
test_name = test_file_name.replace('test_',... |
# definitions.py
IbConfig = {
'telepotChatId': '572145851',
'googleServiceKeyFile' : 'GoogleCloudServiceKey.json',
'telepotToken' : '679545486:AAEbCBdedlJ1lxFXpN1a-J-6LfgFQ4cAp04',
'startMessage' : 'Hallo, ich bin unsere dolmetschende Eule. Stelle mich bitte auf deine Handflaeche und ich sage dir, was d... | ib_config = {'telepotChatId': '572145851', 'googleServiceKeyFile': 'GoogleCloudServiceKey.json', 'telepotToken': '679545486:AAEbCBdedlJ1lxFXpN1a-J-6LfgFQ4cAp04', 'startMessage': 'Hallo, ich bin unsere dolmetschende Eule. Stelle mich bitte auf deine Handflaeche und ich sage dir, was dein tauber Gegenueber schreibt. Wenn... |
class Graph:
def __init__(self,nodes,edges):
self.graph=[]
for i in range(nodes+1):
self.graph.append([])
self.visited=[False]*(len(self.graph))
def addEdge(self,v1,v2):
self.graph[v1].append(v2)
def dfs(self,source):
self.visited[source]=True
print(source)
for i in self.graph[source]:
if not s... | class Graph:
def __init__(self, nodes, edges):
self.graph = []
for i in range(nodes + 1):
self.graph.append([])
self.visited = [False] * len(self.graph)
def add_edge(self, v1, v2):
self.graph[v1].append(v2)
def dfs(self, source):
self.visited[source] = ... |
inp = list(map(float, input().split()))
inp.sort(reverse=True)
a, b, c = inp
if a >= b + c:
print('NAO FORMA TRIANGULO')
else:
if a ** 2 == b ** 2 + c ** 2:
print('TRIANGULO RETANGULO')
elif a ** 2 > b ** 2 + c ** 2:
print('TRIANGULO OBTUSANGULO')
else:
print('TRIANGULO ACUTAN... | inp = list(map(float, input().split()))
inp.sort(reverse=True)
(a, b, c) = inp
if a >= b + c:
print('NAO FORMA TRIANGULO')
else:
if a ** 2 == b ** 2 + c ** 2:
print('TRIANGULO RETANGULO')
elif a ** 2 > b ** 2 + c ** 2:
print('TRIANGULO OBTUSANGULO')
else:
print('TRIANGULO ACUTANG... |
__all__ = ['CONFIG', 'get']
CONFIG = {
'model_save_dir': "./output/MicroExpression",
'num_classes': 7,
'total_images': 17245,
'epochs': 20,
'batch_size': 32,
'image_shape': [3, 224, 224],
'LEARNING_RATE': {
'params': {
'lr': 0.00375
}
},
'OPT... | __all__ = ['CONFIG', 'get']
config = {'model_save_dir': './output/MicroExpression', 'num_classes': 7, 'total_images': 17245, 'epochs': 20, 'batch_size': 32, 'image_shape': [3, 224, 224], 'LEARNING_RATE': {'params': {'lr': 0.00375}}, 'OPTIMIZER': {'params': {'momentum': 0.9}, 'regularizer': {'function': 'L2', 'factor': ... |
n=str(input("Enter the string"))
le=len(n)
dig=0
alp=0
for i in range(le):
if n[i].isdigit():
dig=dig+1
elif n[i].isalpha():
alp=alp+1
else:
continue
print("Letters count is : %d"%alp)
print("Digits count is : %d"%dig)
| n = str(input('Enter the string'))
le = len(n)
dig = 0
alp = 0
for i in range(le):
if n[i].isdigit():
dig = dig + 1
elif n[i].isalpha():
alp = alp + 1
else:
continue
print('Letters count is : %d' % alp)
print('Digits count is : %d' % dig) |
# Author: Will Killian
# https://www.github.com/willkill07
#
# Copyright 2021
# All Rights Reserved
class Lab:
_all = dict()
lab_id = 200
def min_id():
"""
Returns the maximum number for the lab IDs (always 200)
"""
return 200
def max_id():
"""
... | class Lab:
_all = dict()
lab_id = 200
def min_id():
"""
Returns the maximum number for the lab IDs (always 200)
"""
return 200
def max_id():
"""
Returns the maximum number for the lab IDs
"""
return Lab.lab_id - 1
def get(id):
... |
# -*- coding: utf-8 -*-
class GeocoderException(Exception):
"""Base class for all the reverse geocoder module exceptions."""
class InitializationError(GeocoderException):
"""Catching this error will catch all initialization-related errors."""
class CsvReadError(InitializationError):
"""Could not open ... | class Geocoderexception(Exception):
"""Base class for all the reverse geocoder module exceptions."""
class Initializationerror(GeocoderException):
"""Catching this error will catch all initialization-related errors."""
class Csvreaderror(InitializationError):
"""Could not open the locations csv file."""
... |
#Given a decimal number n, your task is to convert it
#to its binary equivalent using a recursive function.
#The binary number output must be of length 8 bits.
def binary(n):
if n == 0:
return 0
else:
return (n % 2 + 10*binary(int(n // 2)))
def convert_8_bit(n):
s = str(n)
while len(s... | def binary(n):
if n == 0:
return 0
else:
return n % 2 + 10 * binary(int(n // 2))
def convert_8_bit(n):
s = str(n)
while len(s) < 8:
s = '0' + s
return s
def dec_to_binary(n):
return convert_8_bit(binary(n))
def main():
t = int(input())
n = []
for _ in range... |
'''
Author: Shuailin Chen
Created Date: 2021-09-14
Last Modified: 2021-12-29
content:
'''
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005)
optimizer_config = dict()
# learning policy
lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False)
# runtime settings
runner ... | """
Author: Shuailin Chen
Created Date: 2021-09-14
Last Modified: 2021-12-29
content:
"""
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005)
optimizer_config = dict()
lr_config = dict(policy='poly', power=0.9, min_lr=0.0001, by_epoch=False)
runner = dict(type='MyIterBasedRunner', max_iters=10000... |
keys = {
"accept": 30,
"add": 107,
"apps": 93,
"attn": 246,
"back": 8,
"browser_back": 166,
"browser_forward": 167,
"cancel": 3,
"capital": 20,
"clear": 12,
"control": 17,
"convert": 28,
"crsel": 247,
"decimal": 110,
"delete": 46,
"divide":... | keys = {'accept': 30, 'add': 107, 'apps': 93, 'attn': 246, 'back': 8, 'browser_back': 166, 'browser_forward': 167, 'cancel': 3, 'capital': 20, 'clear': 12, 'control': 17, 'convert': 28, 'crsel': 247, 'decimal': 110, 'delete': 46, 'divide': 111, 'down': 40, 'end': 35, 'ereof': 249, 'escape': 27, 'execute': 43, 'exsel': ... |
N = int(input())
A = list(map(int, input().split()))
A.sort()
left, right = 0, 2*N-1
moist = A.count(0) // 2
while left < right and A[left] < 0 and A[right] > 0:
if abs(A[left]) == A[right]:
moist += 1
left += 1
right -= 1
elif abs(A[left]) > A[right]:
left += 1
else:
... | n = int(input())
a = list(map(int, input().split()))
A.sort()
(left, right) = (0, 2 * N - 1)
moist = A.count(0) // 2
while left < right and A[left] < 0 and (A[right] > 0):
if abs(A[left]) == A[right]:
moist += 1
left += 1
right -= 1
elif abs(A[left]) > A[right]:
left += 1
els... |
def printSlope(equation):
xIndex = equation.find('x')
if xIndex == -1:
print(0)
elif xIndex == 2:
print(1)
else:
slopeString = equation[2:xIndex]
if slopeString == "-":
print(-1)
else:
print(slopeString)
printSlope("y=2x+5") #prints 2
prin... | def print_slope(equation):
x_index = equation.find('x')
if xIndex == -1:
print(0)
elif xIndex == 2:
print(1)
else:
slope_string = equation[2:xIndex]
if slopeString == '-':
print(-1)
else:
print(slopeString)
print_slope('y=2x+5')
print_slope... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
__title__ = 'replace'
__author__ = 'JieYuan'
__mtime__ = '2019-05-06'
"""
def replace(s, dic):
return s.translate(str.maketrans(dic))
if __name__ == '__main__':
print(replace('abcd', {'a': '8', 'd': '88'}))
| """
__title__ = 'replace'
__author__ = 'JieYuan'
__mtime__ = '2019-05-06'
"""
def replace(s, dic):
return s.translate(str.maketrans(dic))
if __name__ == '__main__':
print(replace('abcd', {'a': '8', 'd': '88'})) |
def profile_most_probable_kmer(text, k, profile):
highest_prob = -1
most_probable_kmer = ""
for i in range(len(text) - k + 1):
kmer = text[i : i+k]
prob = 1
for index, nucleotide in enumerate(kmer):
prob *= profile[nucleotide][index]
if prob > highest_prob:
... | def profile_most_probable_kmer(text, k, profile):
highest_prob = -1
most_probable_kmer = ''
for i in range(len(text) - k + 1):
kmer = text[i:i + k]
prob = 1
for (index, nucleotide) in enumerate(kmer):
prob *= profile[nucleotide][index]
if prob > highest_prob:
... |
ROW_COUNT = 128
COLUMN_COUNT = 8
def solve(input):
return max(map(lambda i: BoardingPass(i).seat_id, input))
class BoardingPass:
def __init__(self, data, row_count=ROW_COUNT, column_count=COLUMN_COUNT):
self.row = self._search(
data = data[:7],
low_char='F',
high_char='B',
i=0,
... | row_count = 128
column_count = 8
def solve(input):
return max(map(lambda i: boarding_pass(i).seat_id, input))
class Boardingpass:
def __init__(self, data, row_count=ROW_COUNT, column_count=COLUMN_COUNT):
self.row = self._search(data=data[:7], low_char='F', high_char='B', i=0, min_value=0, max_value=r... |
f = open('day3.txt', 'r')
data = f.readlines()
oneCount = 0
threeCount = 0
fiveCount = 0
sevenCount = 0
evenCount = 0
pos1 = 0
pos3 = 0
pos5 = 0
pos7 = 0
posEven = 0
even = True
for line in data:
line = line.replace("\n", '')
if line[pos1 % len(line)] == '#':
oneCount += 1
if line[pos3 % len(line)... | f = open('day3.txt', 'r')
data = f.readlines()
one_count = 0
three_count = 0
five_count = 0
seven_count = 0
even_count = 0
pos1 = 0
pos3 = 0
pos5 = 0
pos7 = 0
pos_even = 0
even = True
for line in data:
line = line.replace('\n', '')
if line[pos1 % len(line)] == '#':
one_count += 1
if line[pos3 % len(... |
def porrada(seq, passo):
atual = 0
while len(seq) > 1:
atual += passo - 1
while atual > len(seq) - 1:
atual -= len(seq)
seq.pop(atual)
return seq[0] + 1
quantidade_de_casos = int(input())
for c in range(quantidade_de_casos):
entrada = input().split()
n = list(ra... | def porrada(seq, passo):
atual = 0
while len(seq) > 1:
atual += passo - 1
while atual > len(seq) - 1:
atual -= len(seq)
seq.pop(atual)
return seq[0] + 1
quantidade_de_casos = int(input())
for c in range(quantidade_de_casos):
entrada = input().split()
n = list(rang... |
n = int(input())
arr = list(map(int, input().split(' ')))
arr.sort(reverse=True)
res = 0
for i in range(n):
res += arr[i]*2**i
print(res)
| n = int(input())
arr = list(map(int, input().split(' ')))
arr.sort(reverse=True)
res = 0
for i in range(n):
res += arr[i] * 2 ** i
print(res) |
class Solution:
def minInsertions(self, s: str) -> int:
right = count = 0
for c in s:
if c == '(':
if right & 1:
right -= 1
count += 1
right += 2
else:
right -= 1
if right ... | class Solution:
def min_insertions(self, s: str) -> int:
right = count = 0
for c in s:
if c == '(':
if right & 1:
right -= 1
count += 1
right += 2
else:
right -= 1
if righ... |
# Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# re... | class Solution(object):
def two_sum(self, nums, target):
"""
O(m)
O(m)
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
return [dic[nums[i]], i]
... |
S = input()
N = len(S)
A = [0]*(N+1)
B = [0]*(N+1)
for i in range(N):
if S[i] == '<':
A[i+1] = A[i]+1
else:
A[i+1] = 0
for i in range(N):
if S[N-i-1] == '>':
B[N-i-1] = B[N-i]+1
else:
B[N-i-1] = 0
ans = 0
for i in range(N+1):
ans += max(A[i], B[i])
print(ans)
| s = input()
n = len(S)
a = [0] * (N + 1)
b = [0] * (N + 1)
for i in range(N):
if S[i] == '<':
A[i + 1] = A[i] + 1
else:
A[i + 1] = 0
for i in range(N):
if S[N - i - 1] == '>':
B[N - i - 1] = B[N - i] + 1
else:
B[N - i - 1] = 0
ans = 0
for i in range(N + 1):
ans += max... |
'''
Write a program that takes an integer argument and
retums all the primes between 1 and that integer.
For example, if the input is 18, you should return
[2, 3, 5, 7, 11, 13, 17].
'''
def generate_primes(n): # Time: O(n log log n) | Space: O(n)
primes = []
# is_prime[p] represents if p is prime or not.
... | """
Write a program that takes an integer argument and
retums all the primes between 1 and that integer.
For example, if the input is 18, you should return
[2, 3, 5, 7, 11, 13, 17].
"""
def generate_primes(n):
primes = []
is_prime = [False, False] + [True] * (n - 1)
for p in range(2, n + 1):
if is_... |
"""
gdcdatamodel.migrations.update_case_cache
--------------------
Functionality to fix stale case caches in _related_cases edge tables.
"""
def update_related_cases(driver, node_id):
"""Removes and re-adds the edge between the given node and it's parent
to cascade the new relationship to _related_cases thr... | """
gdcdatamodel.migrations.update_case_cache
--------------------
Functionality to fix stale case caches in _related_cases edge tables.
"""
def update_related_cases(driver, node_id):
"""Removes and re-adds the edge between the given node and it's parent
to cascade the new relationship to _related_cases thro... |
n = int(input())
l = []
for i in range(0, n):
l.append(int(input()))
for orig_num in l:
count = 0
num = orig_num
while num != 0:
digit = num % 10
if digit == 0:
pass
elif orig_num % digit == 0:
count += 1
num = int(num / 10)
print (count) | n = int(input())
l = []
for i in range(0, n):
l.append(int(input()))
for orig_num in l:
count = 0
num = orig_num
while num != 0:
digit = num % 10
if digit == 0:
pass
elif orig_num % digit == 0:
count += 1
num = int(num / 10)
print(count) |
class Qseq(str):
def __init__(self, seq):
self.qkey = None
self.parent = None
self.parental_id = None
self.parental_class = None
self.name = None
self.item = None
def __getitem__(self, item):
value = s... | class Qseq(str):
def __init__(self, seq):
self.qkey = None
self.parent = None
self.parental_id = None
self.parental_class = None
self.name = None
self.item = None
def __getitem__(self, item):
value = super().__getitem__(item)
if self.parental_cla... |
rios = {
'nilo' : 'egito',
'rio grande' : 'brasil',
'rio parana' : 'brasil'
}
for key,value in rios.items():
print(' O rio ' + key.title() + ' corre pelo ' + value.title())
for key in rios.keys():
print(key.title())
for value in rios.values():
print(value.title())
| rios = {'nilo': 'egito', 'rio grande': 'brasil', 'rio parana': 'brasil'}
for (key, value) in rios.items():
print(' O rio ' + key.title() + ' corre pelo ' + value.title())
for key in rios.keys():
print(key.title())
for value in rios.values():
print(value.title()) |
def hello(name):
"""Generate a friendly greeting.
Greeting is an important part of culture. This function takes a name and
generates a friendly greeting for it.
Parameters
----------
name : str
A name.
Returns
-------
str
A greeting.
"""
return 'Hello {na... | def hello(name):
"""Generate a friendly greeting.
Greeting is an important part of culture. This function takes a name and
generates a friendly greeting for it.
Parameters
----------
name : str
A name.
Returns
-------
str
A greeting.
"""
return 'Hello {nam... |
vowels2 = set('aeiiiouuu')
word = input('Provide a word to search for vowels:').lower()
found = vowels2.intersection(set(word))
for v in found:
print(v) | vowels2 = set('aeiiiouuu')
word = input('Provide a word to search for vowels:').lower()
found = vowels2.intersection(set(word))
for v in found:
print(v) |
#!/usr/bin/env python2.7
"""
Read the file agents.raw and output agents.txt, a readable file
"""
if __name__=="__main__":
with open("agents.raw","r") as f:
with open("agents.txt","w") as out:
for line in f:
if(line[0] in '+|'):
out.write(line)
| """
Read the file agents.raw and output agents.txt, a readable file
"""
if __name__ == '__main__':
with open('agents.raw', 'r') as f:
with open('agents.txt', 'w') as out:
for line in f:
if line[0] in '+|':
out.write(line) |
# -*- coding: utf-8 -*-
"""mul.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fvc_bX8oobfbr_O2r1pCpgOd2CTckXe9
"""
def mul(num1, num2):
print('Result is: ', num1 * num2) | """mul.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fvc_bX8oobfbr_O2r1pCpgOd2CTckXe9
"""
def mul(num1, num2):
print('Result is: ', num1 * num2) |
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
table = {}
mapped = set()
words = str.split()
if len(words) != len(pattern):
return False
for i, word in enumerate(words):
if word in table:
if table[wor... | class Solution:
def word_pattern(self, pattern: str, str: str) -> bool:
table = {}
mapped = set()
words = str.split()
if len(words) != len(pattern):
return False
for (i, word) in enumerate(words):
if word in table:
if table[word] != pa... |
HOST = 'localhost'
PORT = 61613
VERSION = '1.2'
BROKER = 'activemq'
LOGIN, PASSCODE, VIRTUALHOST = {
'activemq': ('', '', ''),
'apollo': ('admin', 'password', 'mybroker'),
'rabbitmq': ('guest', 'guest', '/')
}[BROKER]
| host = 'localhost'
port = 61613
version = '1.2'
broker = 'activemq'
(login, passcode, virtualhost) = {'activemq': ('', '', ''), 'apollo': ('admin', 'password', 'mybroker'), 'rabbitmq': ('guest', 'guest', '/')}[BROKER] |
# python3.7
"""Configuration for testing StyleGAN on FF-HQ (1024) dataset.
All settings are particularly used for one replica (GPU), such as `batch_size`
and `num_workers`.
"""
runner_type = 'StyleGANRunner'
gan_type = 'stylegan'
resolution = 1024
batch_size = 16
data = dict(
num_workers=4,
# val=dict(root_d... | """Configuration for testing StyleGAN on FF-HQ (1024) dataset.
All settings are particularly used for one replica (GPU), such as `batch_size`
and `num_workers`.
"""
runner_type = 'StyleGANRunner'
gan_type = 'stylegan'
resolution = 1024
batch_size = 16
data = dict(num_workers=4, val=dict(root_dir='data/ffhq.zip', data_... |
def Num2581():
M = int(input())
N = int(input())
minPrimeNum = 0
sumPrimeNum = 0
primeNums = []
for dividend in range(M, N+1):
if dividend == 1:
continue
primeNums.append(dividend)
sumPrimeNum += dividend
for divisor in range(2, dividend):
... | def num2581():
m = int(input())
n = int(input())
min_prime_num = 0
sum_prime_num = 0
prime_nums = []
for dividend in range(M, N + 1):
if dividend == 1:
continue
primeNums.append(dividend)
sum_prime_num += dividend
for divisor in range(2, dividend):
... |
#takes a list of options as input which will be printed as a numerical list
#Also optionally takes messages as input to be printed after the options but before input request
#Ultimately the users choice is returned
def selector(options,*messages):
rego = 'y'
while rego.lower() == "y":
n=1
for x... | def selector(options, *messages):
rego = 'y'
while rego.lower() == 'y':
n = 1
for x in options:
print(str(n) + '. ' + str(x))
n = n + 1
n = 1
print('')
for arg in messages:
print(arg)
choice = input(' :> ')
if choice == ... |
"""A module to keep track of a relinearization key."""
class BFVRelinKey:
"""An instance of a relinearization key.
The relinearization key consists of a list of values, as specified
in Version 1 of the BFV paper, generated in key_generator.py.
Attributes:
base (int): Base used in relineariza... | """A module to keep track of a relinearization key."""
class Bfvrelinkey:
"""An instance of a relinearization key.
The relinearization key consists of a list of values, as specified
in Version 1 of the BFV paper, generated in key_generator.py.
Attributes:
base (int): Base used in relinearizat... |
class Wrapping(object):
def __init__(self, klass, wrapped_klass, dependency_functions):
self._klass = klass
self._wrapped_klass = wrapped_klass
self._dependency_functions = dependency_functions
def wrap(self):
for dependency_method in self._dependency_functions:
se... | class Wrapping(object):
def __init__(self, klass, wrapped_klass, dependency_functions):
self._klass = klass
self._wrapped_klass = wrapped_klass
self._dependency_functions = dependency_functions
def wrap(self):
for dependency_method in self._dependency_functions:
sel... |
"""
templates for urls
"""
URL = """router.register(r'%(path)s', %(model)sViewSet)
"""
VIEWSET_IMPORT = """from %(app)s.views import %(model)sViewSet
"""
URL_PATTERNS = """urlpatterns = [
path("", include(router.urls)),
]"""
SETUP = """from rest_framework import routers
from django.urls import include, path
r... | """
templates for urls
"""
url = "router.register(r'%(path)s', %(model)sViewSet)\n\n"
viewset_import = 'from %(app)s.views import %(model)sViewSet\n'
url_patterns = 'urlpatterns = [\n path("", include(router.urls)),\n]'
setup = 'from rest_framework import routers\nfrom django.urls import include, path\n\nrouter = ro... |
def roman_number(num):
if num > 3999:
print("enter number less than 3999")
return
#take 2 list symbol and value symbol having roman of each integer in list value
value = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
symbol = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
ro... | def roman_number(num):
if num > 3999:
print('enter number less than 3999')
return
value = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
symbol = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
roman = ''
i = 0
while num > 0:
div = num // v... |
AN_ESCAPED_NEWLINE = "\n"
AN_ESCAPED_TAB = "\t"
A_COMMA = ","
A_QUOTE = "'"
A_TAB = "\t"
DOUBLE_QUOTES = "\""
NEWLINE = "\n"
| an_escaped_newline = '\n'
an_escaped_tab = '\t'
a_comma = ','
a_quote = "'"
a_tab = '\t'
double_quotes = '"'
newline = '\n' |
#!/usr/bin/env python3
#
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | class Scholarshipbuilder:
@staticmethod
def set_name(scholarship, name):
scholarship['scholarshipName'] = name
@staticmethod
def set_id(scholarship, id):
scholarship['id'] = str(int(id))
@staticmethod
def set_schools_list(scholarship, schoolsList):
scholarship['schools... |
class MyClass:
def __init__(self, name):
self.__name = name
def Show(self):
print(self.__name)
c1 = MyClass('c1')
c2 = MyClass('c2')
c3 = MyClass('c3')
c4 = MyClass('c4')
a = {x.Show() for x in {c1, c2, c3, c4} if x not in {c1, c2}}
| class Myclass:
def __init__(self, name):
self.__name = name
def show(self):
print(self.__name)
c1 = my_class('c1')
c2 = my_class('c2')
c3 = my_class('c3')
c4 = my_class('c4')
a = {x.Show() for x in {c1, c2, c3, c4} if x not in {c1, c2}} |
@metadata_reactor
def install_git(metadata):
return {
'apt': {
'packages': {
'git': {
'installed': True,
},
}
},
}
| @metadata_reactor
def install_git(metadata):
return {'apt': {'packages': {'git': {'installed': True}}}} |
if __name__ == '__main__':
n,m = map(int,input().split())
l = map(int,input().split())
a = set(map(int,input().split()))
b = set(map(int,input().split()))
happy = 0
for i in l:
if i in a:
happy += 1
elif i in b:
happy -= 1
print(happy)
# print(sum([(i in a) - (i in b) for i in l])) | if __name__ == '__main__':
(n, m) = map(int, input().split())
l = map(int, input().split())
a = set(map(int, input().split()))
b = set(map(int, input().split()))
happy = 0
for i in l:
if i in a:
happy += 1
elif i in b:
happy -= 1
print(happy) |
#!/usr/bin/env python
"""Python-LCS Algorithm, Author: Matt Nichols
Copied from https://github.com/man1/Python-LCS/blob/master/lcs.py
Modified for running LCS inside P4SC merging algorithm
"""
### solve the longest common subsequence problem
# get the matrix of LCS lengths at each sub-step of the recursive pro... | """Python-LCS Algorithm, Author: Matt Nichols
Copied from https://github.com/man1/Python-LCS/blob/master/lcs.py
Modified for running LCS inside P4SC merging algorithm
"""
def lcs_mat(list1, list2):
m = len(list1)
n = len(list2)
mat = [[0] * (n + 1) for row in range(m + 1)]
for row in range(1, m +... |
# // This is a generated file, modify: generate/templates/binding.gyp.
{
"targets": [{
"target_name": "nodegit",
"dependencies": [
"<(module_root_dir)/vendor/libgit2.gyp:libgit2"
],
"sources": [
"src/nodegit.cc",
"src/wrapper.cc",
"src/functions/copy.cc",
"src/attr.cc"... | {'targets': [{'target_name': 'nodegit', 'dependencies': ['<(module_root_dir)/vendor/libgit2.gyp:libgit2'], 'sources': ['src/nodegit.cc', 'src/wrapper.cc', 'src/functions/copy.cc', 'src/attr.cc', 'src/blame.cc', 'src/blame_hunk.cc', 'src/blame_options.cc', 'src/blob.cc', 'src/branch.cc', 'src/branch_iterator.cc', 'src/b... |
# Text for QML styles
chl_style = """
<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
<qgis version="2.4.0-Chugiak" minimumScale="0" maximumScale="1e+08" hasScaleBasedVisibilityFlag="0">
<pipe>
<rasterrenderer opacity="1" alphaBand="0" classificationMax="1.44451" classificationMinMaxOrigin="Cumulative... | chl_style = '\n<!DOCTYPE qgis PUBLIC \'http://mrcc.com/qgis.dtd\' \'SYSTEM\'>\n<qgis version="2.4.0-Chugiak" minimumScale="0" maximumScale="1e+08" hasScaleBasedVisibilityFlag="0">\n <pipe>\n <rasterrenderer opacity="1" alphaBand="0" classificationMax="1.44451" classificationMinMaxOrigin="CumulativeCutFullExtentEsti... |
a = 10
b = 20
c = 300000
| a = 10
b = 20
c = 300000 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if not root:
... | class Solution:
def average_of_levels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if not root:
return []
result = []
level = [root]
while level:
new_level = []
total = 0
for node in lev... |
class Solution:
def addBinary(self, a: str, b: str) -> str:
x=int(a,2)
y=int(b,2)
return bin(x+y)[2:]
| class Solution:
def add_binary(self, a: str, b: str) -> str:
x = int(a, 2)
y = int(b, 2)
return bin(x + y)[2:] |
for i in range(int(input())):
n = int(input())
s = input()
a,b = [-1 for j in range(26)],[1e5 for j in range(26)]
for j in range(n):
if(a[ord(s[j])-97]==-1):
a[ord(s[j])-97] = j
else:
if(j-a[ord(s[j])-97]<b[ord(s[j])-97]):
b[ord(s[j])-97] = j-a[ord... | for i in range(int(input())):
n = int(input())
s = input()
(a, b) = ([-1 for j in range(26)], [100000.0 for j in range(26)])
for j in range(n):
if a[ord(s[j]) - 97] == -1:
a[ord(s[j]) - 97] = j
else:
if j - a[ord(s[j]) - 97] < b[ord(s[j]) - 97]:
b[... |
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
edits = [[x for x in range(len(word1) + 1)] for y in range(len(word2) + 1)]
for i in range(1, len(word2) + 1):
edits[i][0] = edits[i - 1][0] + 1
for i in range(1, len(word2) + 1):
for j in range(1, ... | class Solution:
def min_distance(self, word1: str, word2: str) -> int:
edits = [[x for x in range(len(word1) + 1)] for y in range(len(word2) + 1)]
for i in range(1, len(word2) + 1):
edits[i][0] = edits[i - 1][0] + 1
for i in range(1, len(word2) + 1):
for j in range(1... |
ENHANCED_PEER_MOBILIZATION = 'enhanced_peer_mobilization'
CHAMP_CAMEROON = 'champ_client_forms'
TARGET_XMLNS = 'http://openrosa.org/formdesigner/A79467FD-4CDE-47B6-8218-4394699A5C95'
PREVENTION_XMLNS = 'http://openrosa.org/formdesigner/DF2FBEEA-31DE-4537-9913-07D57591502C'
POST_TEST_XMLNS = 'http://openrosa.org/formd... | enhanced_peer_mobilization = 'enhanced_peer_mobilization'
champ_cameroon = 'champ_client_forms'
target_xmlns = 'http://openrosa.org/formdesigner/A79467FD-4CDE-47B6-8218-4394699A5C95'
prevention_xmlns = 'http://openrosa.org/formdesigner/DF2FBEEA-31DE-4537-9913-07D57591502C'
post_test_xmlns = 'http://openrosa.org/formdes... |
def attack(state, attacking_moves_sequence):
new_state = state.__deepcopy__()
ATTACKING_TERRITORY_INDEX = 0
ENEMY_TERRITORY_INDEX = 1
for attacking_move in attacking_moves_sequence:
print("in attack attacking move",attacking_move)
print("new state map in attack", len(new_state.map))
... | def attack(state, attacking_moves_sequence):
new_state = state.__deepcopy__()
attacking_territory_index = 0
enemy_territory_index = 1
for attacking_move in attacking_moves_sequence:
print('in attack attacking move', attacking_move)
print('new state map in attack', len(new_state.map))
... |
# You may need this if you really want to use a recursive solution!
# It raises the cap on how many recursions can happen. Use this at your own risk!
# sys.setrecursionlimit(100000)
def read_lines(filename):
try:
f = open(filename,"r")
lines = f.readlines()
f.close()
filter... | def read_lines(filename):
try:
f = open(filename, 'r')
lines = f.readlines()
f.close()
filtered_contents = []
for line in lines:
line = line.rstrip('\n')
filtered_contents.append(list(line))
return filtered_contents
except FileNotFoundError... |
class MultiFilterCNNModel(object):
def __init__(self, max_sequences, word_index, embed_dim, embedding_matrix, filter_sizes,
num_filters, dropout, learning_rate, beta_1, beta_2, epsilon, n_classes):
sequence_input = Input(shape=(max_sequences,), dtype='int32')
embedding_layer = Emb... | class Multifiltercnnmodel(object):
def __init__(self, max_sequences, word_index, embed_dim, embedding_matrix, filter_sizes, num_filters, dropout, learning_rate, beta_1, beta_2, epsilon, n_classes):
sequence_input = input(shape=(max_sequences,), dtype='int32')
embedding_layer = embedding(len(word_in... |
#!usr/bin/python
# -*- coding: utf-8 -*-
class Database(object):
"""Database class holding information about node/label relationships, mappings from nodes to images and from images to status."""
def __init__(self, root_name="core"):
"""Constuctor for the Database class.
Args:
roo... | class Database(object):
"""Database class holding information about node/label relationships, mappings from nodes to images and from images to status."""
def __init__(self, root_name='core'):
"""Constuctor for the Database class.
Args:
root_name (str, optional): Name given to the r... |
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained='open-mmlab://resnet50_v1c',
backbone=dict(
type='ResNetV1c',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
dilations=(1, 1, 2, 4),
strides=(1, 2, 1, 1),
... | norm_cfg = dict(type='BN', requires_grad=True)
model = dict(type='EncoderDecoder', pretrained='open-mmlab://resnet50_v1c', backbone=dict(type='ResNetV1c', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), dilations=(1, 1, 2, 4), strides=(1, 2, 1, 1), norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, style=... |
class Solution:
def longestAwesome(self, s: str) -> int:
table = {0 : -1}
mask = maxLen = 0
for i, c in enumerate(s):
mask ^= (1 << int(c))
for j in range(10):
mask2 = mask ^ (1 << j)
if mask2 in table:
maxLen = max(... | class Solution:
def longest_awesome(self, s: str) -> int:
table = {0: -1}
mask = max_len = 0
for (i, c) in enumerate(s):
mask ^= 1 << int(c)
for j in range(10):
mask2 = mask ^ 1 << j
if mask2 in table:
max_len = max... |
# This is what gets created by TextField.as_tensor with a SingleIdTokenIndexer
# and a TokenCharactersIndexer; see the code snippet above. This time we're using
# more intuitive names for the indexers and embedders.
token_tensor = {
'tokens': {'tokens': torch.LongTensor([[2, 4, 3, 5]])},
'token_characters': {'t... | token_tensor = {'tokens': {'tokens': torch.LongTensor([[2, 4, 3, 5]])}, 'token_characters': {'token_characters': torch.LongTensor([[[2, 5, 3], [4, 0, 0], [2, 1, 4], [5, 4, 0]]])}}
embedding = embedding(num_embeddings=6, embedding_dim=3)
character_embedding = embedding(num_embeddings=6, embedding_dim=3)
cnn_encoder = cn... |
{
"targets": [
{
"target_name": "decompressor",
"sources": ["decompressor.cpp"]
},
{
"target_name": "pow_solver",
"sources": ["pow_solver.cpp"]
}
]
}
| {'targets': [{'target_name': 'decompressor', 'sources': ['decompressor.cpp']}, {'target_name': 'pow_solver', 'sources': ['pow_solver.cpp']}]} |
class C4FileIO():
red_wins = 0
blue_wins = 0
def __init__(self):
try:
f = open("c4wins.txt", "r")
lines = f.readlines()
f.close()
if type(lines) == list:
self.deserialize_file(lines)
except FileNotFoundError:
print(... | class C4Fileio:
red_wins = 0
blue_wins = 0
def __init__(self):
try:
f = open('c4wins.txt', 'r')
lines = f.readlines()
f.close()
if type(lines) == list:
self.deserialize_file(lines)
except FileNotFoundError:
print('F... |
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load("//bazel_tools:haskell.bzl", "da_haskell_test")
load("//bazel_tools/sh:sh.bzl", "sh_inline_test")
def damlc_compile_test(
name,
srcs,
main,
damlc... | load('//bazel_tools:haskell.bzl', 'da_haskell_test')
load('//bazel_tools/sh:sh.bzl', 'sh_inline_test')
def damlc_compile_test(name, srcs, main, damlc='//compiler/damlc', stack_limit='', heap_limit='', **kwargs):
stack_opt = '-K' + stack_limit if stack_limit else ''
heap_opt = '-M' + heap_limit if heap_limit el... |
class InfiniteLineup:
def __init__(self, players):
self.players = players
def lineup(self):
lineup_max = len(self.players)
idx = 0
while True:
if idx < lineup_max:
yield self.players[idx]
else:
idx = 0
... | class Infinitelineup:
def __init__(self, players):
self.players = players
def lineup(self):
lineup_max = len(self.players)
idx = 0
while True:
if idx < lineup_max:
yield self.players[idx]
else:
idx = 0
yiel... |
class StoreObject:
def _log_template(self, token):
return f"<{token.server.upper()} {token.method}: {' '.join([str(token.params[k]) for k in token.params])}>"
async def get(self, token, *args, **kwargs):
raise NotImplementedError
async def set(self, token, response, *args, **kwargs):
... | class Storeobject:
def _log_template(self, token):
return f"<{token.server.upper()} {token.method}: {' '.join([str(token.params[k]) for k in token.params])}>"
async def get(self, token, *args, **kwargs):
raise NotImplementedError
async def set(self, token, response, *args, **kwargs):
... |
# ------------------------------
# 674. Longest Continuous Increasing Subsequence
#
# Description:
# Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).
# Example 1:
# Input: [1,3,5,4,7]
# Output: 3
# Explanation: The longest continuous increasing subsequence i... | class Solution(object):
def find_length_of_lcis(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxlen = 1
curlen = 1
if len(nums) == 0 or len(nums) == 1:
return len(nums)
for i in range(len(nums) - 1):
if nums[i] < nums... |
"""
Design and implement a data structure for Least Recently Used (LRU) cache. It
should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key
exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already... | """
Design and implement a data structure for Least Recently Used (LRU) cache. It
should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key
exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already... |
"""grating_coupler_meep - grating coupler meep"""
__version__ = "0.0.1"
__author__ = "Simon Bilodeau <<46427609+simbilod@users.noreply.github.com>>"
__all__ = []
| """grating_coupler_meep - grating coupler meep"""
__version__ = '0.0.1'
__author__ = 'Simon Bilodeau <<46427609+simbilod@users.noreply.github.com>>'
__all__ = [] |
class SIR:
def __init__(self, susceptible, infected, removed, region_id=None):
self.region_id = region_id
self.susceptible = susceptible
self.infected = infected
self.removed = removed
self.total_pop = susceptible + infected + removed
def copy(self):
return SIR... | class Sir:
def __init__(self, susceptible, infected, removed, region_id=None):
self.region_id = region_id
self.susceptible = susceptible
self.infected = infected
self.removed = removed
self.total_pop = susceptible + infected + removed
def copy(self):
return sir(... |
a = 10
b = 22
while b - a > 4:
c = b - (2 * a)
if c > 0:
d = c + 1
else:
d = c + 5
a = a + 3
b = b - 2
| a = 10
b = 22
while b - a > 4:
c = b - 2 * a
if c > 0:
d = c + 1
else:
d = c + 5
a = a + 3
b = b - 2 |
_html = """<HTML><HEAD><?HEAD><BODY>{}</BODY><?HTML>"""
def index_page():
content = """This is a simple api for exploring the <a href="http://www.geonames.org">geonames</a> <a href="http://download.geonames.org/export/dump">data</a>, specificially the cities1000 data, which is cities with population of greater t... | _html = '<HTML><HEAD><?HEAD><BODY>{}</BODY><?HTML>'
def index_page():
content = 'This is a simple api for exploring the <a href="http://www.geonames.org">geonames</a> <a href="http://download.geonames.org/export/dump">data</a>, specificially the cities1000 data, which is cities with population of greater than or e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.