content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
category_layers = {
"title": "Hazards",
"abstract": "",
"layers": [
{
"include": "ows_refactored.hazards.burntarea.ows_provisional_ba_cfg.layers",
"type": "python",
},
]
}
| category_layers = {'title': 'Hazards', 'abstract': '', 'layers': [{'include': 'ows_refactored.hazards.burntarea.ows_provisional_ba_cfg.layers', 'type': 'python'}]} |
class Logger:
# Time: O(1), Space: O(M) all incoming messages
def __init__(self):
# Initialize a data structure to store messages
self.messages = {}
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
# If the message streaming in does not exist add to dictionary
... | class Logger:
def __init__(self):
self.messages = {}
def should_print_message(self, timestamp: int, message: str) -> bool:
if message not in self.messages:
self.messages[message] = timestamp
return True
elif timestamp >= self.messages[message] + 10:
... |
def add_native_methods(clazz):
def getScrollbarSize__int__(a0):
raise NotImplementedError()
def setValues__int__int__int__int__(a0, a1, a2, a3, a4):
raise NotImplementedError()
def setLineIncrement__int__(a0, a1):
raise NotImplementedError()
def setPageIncrement__int__(a0, a1)... | def add_native_methods(clazz):
def get_scrollbar_size__int__(a0):
raise not_implemented_error()
def set_values__int__int__int__int__(a0, a1, a2, a3, a4):
raise not_implemented_error()
def set_line_increment__int__(a0, a1):
raise not_implemented_error()
def set_page_increment_... |
"""
Avoid already-imported warning cause of we are importing this package from
run wrapper for loading config.
You can see documentation here:
https://docs.pytest.org/en/latest/reference.html
under section PYTEST_DONT_REWRITE
"""
| """
Avoid already-imported warning cause of we are importing this package from
run wrapper for loading config.
You can see documentation here:
https://docs.pytest.org/en/latest/reference.html
under section PYTEST_DONT_REWRITE
""" |
number = int(input("Which number do you want to choose"))
if number % 2 == 0:
print("This is an even number.")
else:
print("This is an odd number.") | number = int(input('Which number do you want to choose'))
if number % 2 == 0:
print('This is an even number.')
else:
print('This is an odd number.') |
# General info
AUTHOR_NAME = "Jeremy Gordon"
SITENAME = "Flow"
EMAIL_PREFIX = "[ Flow ] "
TAGLINE = "A personal dashboard to focus on what matters"
SECURE_BASE = "https://flowdash.co"
# Emails
APP_OWNER = "onejgordon@gmail.com"
ADMIN_EMAIL = APP_OWNER
DAILY_REPORT_RECIPS = [APP_OWNER]
SENDER_EMAIL = APP_OWNER
NOTIF_E... | author_name = 'Jeremy Gordon'
sitename = 'Flow'
email_prefix = '[ Flow ] '
tagline = 'A personal dashboard to focus on what matters'
secure_base = 'https://flowdash.co'
app_owner = 'onejgordon@gmail.com'
admin_email = APP_OWNER
daily_report_recips = [APP_OWNER]
sender_email = APP_OWNER
notif_emails = [APP_OWNER]
gcs_re... |
class StandartIO:
def read(self, file_name):
f = open(file_name, "r")
result = f.read()
f.close()
return result
def write(self, file_name, data):
f = open(file_name, "w")
f.write(data)
f.close()
def append(self, file_name, data, line):
cont... | class Standartio:
def read(self, file_name):
f = open(file_name, 'r')
result = f.read()
f.close()
return result
def write(self, file_name, data):
f = open(file_name, 'w')
f.write(data)
f.close()
def append(self, file_name, data, line):
conte... |
N, M = map(int, input().split())
grid = [input() for _ in range(N)]
max_length = min(N, M)
def is_square(n):
for i in range(N-n+1):
for j in range(M-n+1):
if is_same(n, i, j):
return True
return False
def is_same(k, x, y):
if grid[x][y] == grid[x][y+k-1] == grid[x+k-1][... | (n, m) = map(int, input().split())
grid = [input() for _ in range(N)]
max_length = min(N, M)
def is_square(n):
for i in range(N - n + 1):
for j in range(M - n + 1):
if is_same(n, i, j):
return True
return False
def is_same(k, x, y):
if grid[x][y] == grid[x][y + k - 1] =... |
"""Pylons requires that packages have a lib.base and lib.helpers
So we've added on here so we can run tests in the context of the tg
package itself, pylons will likely remove this restriction before
1.0 and this package can then be removed.
""" | """Pylons requires that packages have a lib.base and lib.helpers
So we've added on here so we can run tests in the context of the tg
package itself, pylons will likely remove this restriction before
1.0 and this package can then be removed.
""" |
def KGI(serial):
if len(str(serial)) == 10 :
enterprise = "362"
tests = "3713713713713"
synthetic = enterprise+str(serial)
step1 =[]
for i in range(len(synthetic)):
step1.append(str(int(synthetic[i])*int(tests[i])))
step2 = 0
for i in rang... | def kgi(serial):
if len(str(serial)) == 10:
enterprise = '362'
tests = '3713713713713'
synthetic = enterprise + str(serial)
step1 = []
for i in range(len(synthetic)):
step1.append(str(int(synthetic[i]) * int(tests[i])))
step2 = 0
for i in range(len... |
class JadeError(Exception):
# RPC error codes
INVALID_REQUEST = -32600
UNKNOWN_METHOD = -32601
BAD_PARAMETERS = -32602
INTERNAL_ERROR = -32603
# Implementation specific error codes: -32000 to -32099
USER_CANCELLED = -32000
PROTOCOL_ERROR = -32001
HW_LOCKED = -32002
NETWORK_MISMA... | class Jadeerror(Exception):
invalid_request = -32600
unknown_method = -32601
bad_parameters = -32602
internal_error = -32603
user_cancelled = -32000
protocol_error = -32001
hw_locked = -32002
network_mismatch = -32003
def __init__(self, code, message, data):
self.code = code... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... | class Solution(object):
def zigzag_level_order(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
self.levels = []
self.recurse(root, 0)
result = []
for i in range(len(self.levels)):
level = self.levels[i]
if i %... |
"""
Dictionaries are lists of key value pairs.
The key can be any object that doesn't change and the value can be any object.
The key and values have a colon ':' between them.
{ Key:Value, Key:Value, Key:Value}
"""
#
# Creating empty dictionaries
#
data = {}
data = dict()
#
# Dictionary with three pairs usin... | """
Dictionaries are lists of key value pairs.
The key can be any object that doesn't change and the value can be any object.
The key and values have a colon ':' between them.
{ Key:Value, Key:Value, Key:Value}
"""
data = {}
data = dict()
numbers = {1: 'one', 2: 'two', 3: 'three'}
data = {'FirstName': 'Graham', ... |
def sum(arr):
if len(arr) == 1:
return arr[0]
return arr[0] + sum(arr[1:])
print(sum([2, 2, 4, 6])) # 14
| def sum(arr):
if len(arr) == 1:
return arr[0]
return arr[0] + sum(arr[1:])
print(sum([2, 2, 4, 6])) |
WEEK0 = 'week0'
WEEK1 = 'week1'
MONTH0 = 'month0'
MONTH1 = 'month1'
DATE_RANGES = [WEEK0, WEEK1, MONTH0, MONTH1]
FORMS_SUBMITTED = 'forms_submitted'
CASES_TOTAL = 'cases_total'
CASES_ACTIVE = 'cases_active'
CASES_OPENED = 'cases_opened'
CASES_CLOSED = 'cases_closed'
LEGACY_TOTAL_CASES = 'totalCases'
LEGACY_CASES_UP... | week0 = 'week0'
week1 = 'week1'
month0 = 'month0'
month1 = 'month1'
date_ranges = [WEEK0, WEEK1, MONTH0, MONTH1]
forms_submitted = 'forms_submitted'
cases_total = 'cases_total'
cases_active = 'cases_active'
cases_opened = 'cases_opened'
cases_closed = 'cases_closed'
legacy_total_cases = 'totalCases'
legacy_cases_update... |
# for no processing
# the generators for non essential parameters need to provide the
# default value when called with None
def nothing(strin):
if strin is None:
return 'default'
return strin
def prot_core(strin):
return strin.split(',')
# {'keyword in input file':(essential?,method to call(pr... | def nothing(strin):
if strin is None:
return 'default'
return strin
def prot_core(strin):
return strin.split(',')
parameters = {'michaels_test_message': (True, nothing)} |
# Minimum distance to skip in meters for skeleton creation.
skip_rate = 100
# seconds to skip while creating the estimate trail from raw trail
jump_seconds = 100
# Distance vehicle can travel away from route, used in case of identifying trails that leave a skeleton and then join again.
d1 = 1000 # meters
# Distance to ... | skip_rate = 100
jump_seconds = 100
d1 = 1000
d2 = 60
min_route_length = 8000
allowed_distance = 100
allowed_time = 10
allowed_angle = 15
data_location = 'G:/Repos/Trans-Portal'
bsf_location = '../BusStopage/Busstop/'
fa_location = '../RoadNatureDetection/'
archive = './archive/' |
'''
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
'''
| """
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
""" |
class CinemaDatabaseMixin:
"""
mixin to make spider use database's cinema table
"""
use_cinema_database = True
class ShowingDatabaseMixin:
"""
mixin to make spider use database's showing table
"""
use_showing_database = True
class MovieDatabaseMixin:
"""
mixin to make spider ... | class Cinemadatabasemixin:
"""
mixin to make spider use database's cinema table
"""
use_cinema_database = True
class Showingdatabasemixin:
"""
mixin to make spider use database's showing table
"""
use_showing_database = True
class Moviedatabasemixin:
"""
mixin to make spider us... |
def f1():
print('call f1')
def f2():
return 'some value'
| def f1():
print('call f1')
def f2():
return 'some value' |
"""API key storage for direct order retrieval."""
# Key example:
#
# KEYS = {
# 'bittrex': {
# 'key': 'mykey',
# 'secret': 'mysecret'
# }
# }
KEYS = {
}
| """API key storage for direct order retrieval."""
keys = {} |
"""Rules for importing Nixpkgs packages."""
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "workspace_and_buildfile")
load("@bazel_skylib//lib:sets.bzl", "sets")
load("@bazel_skylib//lib:versions.bzl", "versions")
load("@bazel_tools//tools/cpp:cc_configure.bzl", "cc_autoconf_impl")
load(
"@bazel_tools//tool... | """Rules for importing Nixpkgs packages."""
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'workspace_and_buildfile')
load('@bazel_skylib//lib:sets.bzl', 'sets')
load('@bazel_skylib//lib:versions.bzl', 'versions')
load('@bazel_tools//tools/cpp:cc_configure.bzl', 'cc_autoconf_impl')
load('@bazel_tools//tools/cpp:... |
{
"name" : "ZK Biometric Device Integration Kware (ZKTECO) Demo (UDP)",
"version" : "1.0",
"author" : "JUVENTUD PRODUCTIVA VENEZOLANA",
"category" : "HR",
"website" : "https://www.youtube.com/channel/UCTj66IUz5M-QV15Mtbx_7yg",
"description": "Module for the connection between odoo and zkteco dev... | {'name': 'ZK Biometric Device Integration Kware (ZKTECO) Demo (UDP)', 'version': '1.0', 'author': 'JUVENTUD PRODUCTIVA VENEZOLANA', 'category': 'HR', 'website': 'https://www.youtube.com/channel/UCTj66IUz5M-QV15Mtbx_7yg', 'description': 'Module for the connection between odoo and zkteco devices for the control of employ... |
class HierarchicalVirtualizationHeaderDesiredSizes(object):
""" HierarchicalVirtualizationHeaderDesiredSizes(logicalSize: Size,pixelSize: Size) """
def Equals(self,*__args):
"""
Equals(self: HierarchicalVirtualizationHeaderDesiredSizes,comparisonHeaderSizes: HierarchicalVirtualizationHeaderDesiredSizes) -> bo... | class Hierarchicalvirtualizationheaderdesiredsizes(object):
""" HierarchicalVirtualizationHeaderDesiredSizes(logicalSize: Size,pixelSize: Size) """
def equals(self, *__args):
"""
Equals(self: HierarchicalVirtualizationHeaderDesiredSizes,comparisonHeaderSizes: HierarchicalVirtualizationHeaderDesiredSi... |
f = open("1/input.txt", "rt")
# read line by line
lines = f.readlines()
line = lines[0]
floor = 0
firstBasement = None
for i in range(0, len(line)):
if line[i] == "(":
floor += 1
else:
floor -= 1
if (floor < 0) & (firstBasement == None):
firstBasement = i+1
print("answer 1 - " +... | f = open('1/input.txt', 'rt')
lines = f.readlines()
line = lines[0]
floor = 0
first_basement = None
for i in range(0, len(line)):
if line[i] == '(':
floor += 1
else:
floor -= 1
if (floor < 0) & (firstBasement == None):
first_basement = i + 1
print('answer 1 - ' + str(floor))
print('a... |
a = [int(x) for x in input().split()]
if a[0] >= a[1]:
a[1] += 24
print(f"O JOGO DUROU {a[1] - a[0]} HORA(S)") | a = [int(x) for x in input().split()]
if a[0] >= a[1]:
a[1] += 24
print(f'O JOGO DUROU {a[1] - a[0]} HORA(S)') |
# -*- coding: utf-8 -*-
R = float(input())
PI = 3.14159
VOLUME = (4 / 3) * PI * (R ** 3)
print("VOLUME = %.3f" % (VOLUME)) | r = float(input())
pi = 3.14159
volume = 4 / 3 * PI * R ** 3
print('VOLUME = %.3f' % VOLUME) |
f = open("textfile.txt");
for line in f:
print (line)
f.close()
| f = open('textfile.txt')
for line in f:
print(line)
f.close() |
# search_data: The data to be used in a search POST.
search_data = {
'metodo': 'buscar',
'acao': '',
'resumoFormacao': '',
'resumoAtividade': '',
'resumoAtuacao': '',
'resumoProducao': '',
'resumoPesquisador': '',
'resumoIdioma': '',
'resumoPresencaDGP': '',
'resumoModalidade': '... | search_data = {'metodo': 'buscar', 'acao': '', 'resumoFormacao': '', 'resumoAtividade': '', 'resumoAtuacao': '', 'resumoProducao': '', 'resumoPesquisador': '', 'resumoIdioma': '', 'resumoPresencaDGP': '', 'resumoModalidade': 'Bolsas+de+PQ+de+categorias0', 'modoIndAdhoc': '', 'buscaAvancada': '0', 'filtros.buscaNome': '... |
class Solution(object):
def destCity(self, paths):
origin, destination = [], []
for p in paths:
origin.append(p[0])
destination.append(p[1])
for d in destination:
if d not in origin :
return d | class Solution(object):
def dest_city(self, paths):
(origin, destination) = ([], [])
for p in paths:
origin.append(p[0])
destination.append(p[1])
for d in destination:
if d not in origin:
return d |
class AsyncRunner:
async def __call__(self, facade_method, *args, **kwargs):
await self.connection.rpc(facade_method(*args, **kwargs))
class ThreadedRunner:
pass
# Methods are descriptors??
# get is called with params
# set gets called with the result?
# This could let us fake the protocol we want
#... | class Asyncrunner:
async def __call__(self, facade_method, *args, **kwargs):
await self.connection.rpc(facade_method(*args, **kwargs))
class Threadedrunner:
pass |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def make_list(values: list[int]) -> list[ListNode]:
v = []
for i, val in enumerate(values):
v.append(ListNode(val))
if i > 0:
v[i - 1].next = v[i]
return v
def same_values(head: ListNode,... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
def make_list(values: list[int]) -> list[ListNode]:
v = []
for (i, val) in enumerate(values):
v.append(list_node(val))
if i > 0:
v[i - 1].next = v[i]
return v
def same_values(head: ListNod... |
"""
Default disk quota assigned to each new user
Units: Bytes (Base 2 - 1 kiB = 1024 bytes)
Default: 100 MiB
Note: Make migrations when updating value
"""
DEFAULT_QUOTA = 104857600
"""
How long the 'Change Password' URL should be
valid, in days.
Current: 1 day (24 Hours)
"""
PASSWORD_RESET_TIMEOUT_DAYS = 1
"""
Extern... | """
Default disk quota assigned to each new user
Units: Bytes (Base 2 - 1 kiB = 1024 bytes)
Default: 100 MiB
Note: Make migrations when updating value
"""
default_quota = 104857600
"\nHow long the 'Change Password' URL should be\nvalid, in days.\nCurrent: 1 day (24 Hours)\n"
password_reset_timeout_days = 1
'\nExternal ... |
def test_d_1():
assert True
def test_d_2():
assert True
def test_d_3():
assert True
| def test_d_1():
assert True
def test_d_2():
assert True
def test_d_3():
assert True |
#!/usr/bin/env python3
class Node():
def __init__(self, parent=None, position=None):
self.parent = parent # parent node
self.position = position
#self.position = (position[1], position[0]) # y, x
self.distance_from_start = 0
self.distance_to_end = 0
self.cost = ... | class Node:
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.distance_from_start = 0
self.distance_to_end = 0
self.cost = 0
self.move = 0
def __str__(self):
if self.position == None:
return 'N... |
class ContactList(list):
def search(self, name):
"""Return all contacts that contain the search value
in their name."""
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
... | class Contactlist(list):
def search(self, name):
"""Return all contacts that contain the search value
in their name."""
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts... |
registry = set()
def register(active=True):
def decorate(func):
print('Running registry (active=%s)->decorate(%s)' % (active, func))
if active:
registry.add(func)
else:
registry.discard(func)
return func
return decorate
@register(active=False)
def f1()... | registry = set()
def register(active=True):
def decorate(func):
print('Running registry (active=%s)->decorate(%s)' % (active, func))
if active:
registry.add(func)
else:
registry.discard(func)
return func
return decorate
@register(active=False)
def f1():... |
'''
Description:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
'''
class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permuteUnique(s... | """
Description:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
"""
class Solution:
def permute_unique(self, num):
length = len(num)
if length == 0:
return []... |
# -*- coding: utf-8 -*-
"""
1669. Merge In Between Linked Lists
You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
The blue edges and nodes in the following figure indicate the result:
Build the result... | """
1669. Merge In Between Linked Lists
You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
The blue edges and nodes in the following figure indicate the result:
Build the result list and return its hea... |
def x1(y):
if y < 10:
z = x1(y+1)
z += 1
return z + 3
return y
def x2(y):
if y < 10:
z = x2(y+1)
return z + 3
return y
x1(5)
x2(5) | def x1(y):
if y < 10:
z = x1(y + 1)
z += 1
return z + 3
return y
def x2(y):
if y < 10:
z = x2(y + 1)
return z + 3
return y
x1(5)
x2(5) |
# This file is used with the GYP meta build system.
# http://code.google.com/p/gyp
# To build try this:
# svn co http://gyp.googlecode.com/svn/trunk gyp
# ./gyp/gyp -f make --depth=`pwd` libexpat.gyp
# make
# ./out/Debug/test
{
'target_defaults': {
'default_configuration': 'Debug',
'configurations': ... | {'target_defaults': {'default_configuration': 'Debug', 'configurations': {'Debug': {'defines': ['DEBUG', '_DEBUG'], 'msvs_settings': {'VCCLCompilerTool': {'RuntimeLibrary': 1}}}, 'Release': {'defines': ['NDEBUG'], 'msvs_settings': {'VCCLCompilerTool': {'RuntimeLibrary': 0}}}}, 'msvs_settings': {'VCCLCompilerTool': {}, ... |
x = [1,2,3]
y = [1,2,3]
print(x == y)
print(x is y)
| x = [1, 2, 3]
y = [1, 2, 3]
print(x == y)
print(x is y) |
class KostenPlaatsError(Exception):
pass
class ServerError(Exception):
pass
class FaultCodeNotFoundError(Exception):
"""Exception when faultcode not found"""
pass
class TwinfieldFaultCode(Exception):
"""Exception when Twinfield has raised a faultcode"""
pass
class SelectOfficeError(Exc... | class Kostenplaatserror(Exception):
pass
class Servererror(Exception):
pass
class Faultcodenotfounderror(Exception):
"""Exception when faultcode not found"""
pass
class Twinfieldfaultcode(Exception):
"""Exception when Twinfield has raised a faultcode"""
pass
class Selectofficeerror(Exception... |
# Equal
# https://www.interviewbit.com/problems/equal/
#
# Given an array A of integers, find the index of values that satisfy A + B = C + D, where A,B,C & D are integers values in the array
#
# Note:
#
# 1) Return the indices `A1 B1 C1 D1`, so that
# A[A1] + A[B1] = A[C1] + A[D1]
# A1 < B1, C1 < D1
# A1 < C1, B1... | class Solution:
def intersect(self, l1, l2):
return [x for x in l1 if x in l2]
def equal(self, A):
(dp, ans) = (dict(), list())
for i in range(len(A)):
for j in range(i + 1, len(A)):
(s, st) = (A[i] + A[j], [i, j])
if s in dp:
... |
{
"targets": [
{
"target_name": "gomodule_addon",
"sources": ["nodegomodule.cc"],
"include_dirs": [
"<(module_root_dir)/../../"
],
"libraries": ["<(module_root_dir)/../../../gomodule/build/gomodule.so"]
}
]
}
| {'targets': [{'target_name': 'gomodule_addon', 'sources': ['nodegomodule.cc'], 'include_dirs': ['<(module_root_dir)/../../'], 'libraries': ['<(module_root_dir)/../../../gomodule/build/gomodule.so']}]} |
{
"targets": [
{
# OpenSSL has a lot of config options, with some default options
# enabling known insecure algorithms. What's a good combinations
# of openssl config options?
# ./config no-asm no-shared no-ssl2 no-ssl3 no-hw no-zlib no-threads
#... | {'targets': [{'target_name': 'openssl', 'type': 'static_library', 'sources': ['1.0.1j/openssl-1.0.1j/crypto/aes/aes_cbc.c', '1.0.1j/openssl-1.0.1j/crypto/aes/aes_cfb.c', '1.0.1j/openssl-1.0.1j/crypto/aes/aes_core.c', '1.0.1j/openssl-1.0.1j/crypto/aes/aes_ctr.c', '1.0.1j/openssl-1.0.1j/crypto/aes/aes_ecb.c', '1.0.1j/ope... |
def make_matrix(rows=0, columns=0, list_of_list=[[]]):
'''
(int, int, list of list) -> list of list (i.e. matrix)
Return a list of list (i.e. matrix) from "list_of_list" if given
or if not given a "list_of_list" parameter,
then prompt user to type in values for each row
and return a matrix with ... | def make_matrix(rows=0, columns=0, list_of_list=[[]]):
"""
(int, int, list of list) -> list of list (i.e. matrix)
Return a list of list (i.e. matrix) from "list_of_list" if given
or if not given a "list_of_list" parameter,
then prompt user to type in values for each row
and return a matrix with ... |
# date: 2019.09.24
# https://stackoverflow.com/questions/58085910/python-convert-u0048-style-unicode-to-normal-string/58086131#58086131
print('#U0048#U0045#U004C#U004C#U004F'.replace('#U', '\\u').encode().decode('raw_unicode_escape'))
| print('#U0048#U0045#U004C#U004C#U004F'.replace('#U', '\\u').encode().decode('raw_unicode_escape')) |
a, b = map(int, input().split())
product = a * b
if product % 2 == 0:
print("Even")
else:
print("Odd")
| (a, b) = map(int, input().split())
product = a * b
if product % 2 == 0:
print('Even')
else:
print('Odd') |
SSS_VERSION = '1.0'
SSS_FORMAT = 'json'
SERVICE_TYPE = 'sss'
ENDPOINT_TYPE = 'publicURL'
AUTH_TYPE = "identity"
ACTION_PREFIX = ""
| sss_version = '1.0'
sss_format = 'json'
service_type = 'sss'
endpoint_type = 'publicURL'
auth_type = 'identity'
action_prefix = '' |
fd=open('NIST.result','r')
output = fd.readlines()
BLEUStrIndex = output.index('BLEU score = ')
blu_new = float(output[BLEUStrIndex+13:BLEUStrIndex+19])
| fd = open('NIST.result', 'r')
output = fd.readlines()
bleu_str_index = output.index('BLEU score = ')
blu_new = float(output[BLEUStrIndex + 13:BLEUStrIndex + 19]) |
class Solution:
def strWithout3a3b(self, A, B):
"""
:type A: int
:type B: int
:rtype: str
"""
if A < B:
s_list = []
while A>0 and B>0:
A -= 1
B -= 1
s_list.append('ba')
index = 0
... | class Solution:
def str_without3a3b(self, A, B):
"""
:type A: int
:type B: int
:rtype: str
"""
if A < B:
s_list = []
while A > 0 and B > 0:
a -= 1
b -= 1
s_list.append('ba')
index = 0... |
# Given an array of integers ( sorted) and integer Val.Implement a function that takes A
# and Val as input parameters and returns the lower bound of Val. ex- A =[-1,-1,2,3,5] Val=4
# Ans=3. As 3 is smaller than 4
def lowerBound(arr, key):
s = 0
e = len(arr)
while s<=e:
mid = (s+e)//2
if ... | def lower_bound(arr, key):
s = 0
e = len(arr)
while s <= e:
mid = (s + e) // 2
if arr[mid] == key:
arr[mid] = key
elif arr[mid] < key:
s = mid + 1
else:
e = mid - 1
return arr[mid]
print(lower_bound([-1, -1, 2, 3, 5], 4)) |
expected_output = {
'model': 'C9300-24P',
'os': 'iosxe',
'platform': 'cat9k',
'version': '17.06.01',
}
| expected_output = {'model': 'C9300-24P', 'os': 'iosxe', 'platform': 'cat9k', 'version': '17.06.01'} |
massA = float(input("Enter first mass - unit kg\n"))
massB = float(input("Enter second mass - unit kg\n"))
radius = float(input("Enter radius - unit metres\n"))
Gravity = 6.673*(10**(-11))
force = Gravity * massA * massB / (radius**2)
print("The force of gravity acting on the bodies is",round(force,5),"N")
| mass_a = float(input('Enter first mass - unit kg\n'))
mass_b = float(input('Enter second mass - unit kg\n'))
radius = float(input('Enter radius - unit metres\n'))
gravity = 6.673 * 10 ** (-11)
force = Gravity * massA * massB / radius ** 2
print('The force of gravity acting on the bodies is', round(force, 5), 'N') |
#Section 1: Terminology
# 1) What is a recursive function?
# A recursive function is a function that call itself
#
# 2) What happens if there is no base case defined in a recursive function?
# Without the base the recursive function wouldn't be complete and it will get an error message.
#
#
# 3) What is the first thi... | def type1():
n = raw_input('Next: ')
if n == '':
return avgodd
else:
return type1()
def odd(n):
if n / 2 == int:
return 0
else:
return n
def main():
t = type1()
odd1 = odd(n)
main()
def output():
' The average of odd number is{}'.format(avgOfodd) |
class Constants: # pylint: disable=too-few-public-methods
"""
TO CHANNEL FROM BOT: Login URL prefix
"""
TO_CHANNEL_FROM_BOT_LOGIN_URL_PREFIX = 'https://login.microsoftonline.com/'
"""
TO CHANNEL FROM BOT: Login URL token endpoint path
"""
TO_CHANNEL_FROM_BOT_TOKEN_ENDPOINT_PATH = '/oaut... | class Constants:
"""
TO CHANNEL FROM BOT: Login URL prefix
"""
to_channel_from_bot_login_url_prefix = 'https://login.microsoftonline.com/'
'\n TO CHANNEL FROM BOT: Login URL token endpoint path\n '
to_channel_from_bot_token_endpoint_path = '/oauth2/v2.0/token'
'\n TO CHANNEL FROM BO... |
a=int(input(">>"))
s1=0
while a>0:
s=a%10
a=int(a/10)
s1=s1+s
#print(s)
print(s1)
| a = int(input('>>'))
s1 = 0
while a > 0:
s = a % 10
a = int(a / 10)
s1 = s1 + s
print(s1) |
STKMarketData_t = {
"trading_day": "string",
"update_time": "string",
"update_millisec": "int",
"update_sequence": "int",
"instrument_id": "string",
"exchange_id": "string",
"exchange_inst_id": "string",
"instrument_status": "int",
"last_price": "double",
"volume": "int",
"la... | stk_market_data_t = {'trading_day': 'string', 'update_time': 'string', 'update_millisec': 'int', 'update_sequence': 'int', 'instrument_id': 'string', 'exchange_id': 'string', 'exchange_inst_id': 'string', 'instrument_status': 'int', 'last_price': 'double', 'volume': 'int', 'last_volume': 'int', 'turnover': 'double', 'o... |
class Other:
def __init__(self, _name):
self._name = _name
@property
def name(self):
return self._name
@staticmethod
def decode(data):
f_name = data["name"]
if not isinstance(f_name, unicode):
raise Exception("not a string")
return Other(f_name)
def encode(self):
data = di... | class Other:
def __init__(self, _name):
self._name = _name
@property
def name(self):
return self._name
@staticmethod
def decode(data):
f_name = data['name']
if not isinstance(f_name, unicode):
raise exception('not a string')
return other(f_name)... |
'''
dengan python bisa melakukan manipulasi sebuah file
sumber referensi: https://www.petanikode.com/python-file/
ditulis pada: 14-02-2021
'''
#membaca file yang akan di tulis
#w = write, ini digunakan untuk mengubah isi dari sebuah file
file = open('file.txt', 'w')
#membuat sebuah user inputan
text = input('masukka... | """
dengan python bisa melakukan manipulasi sebuah file
sumber referensi: https://www.petanikode.com/python-file/
ditulis pada: 14-02-2021
"""
file = open('file.txt', 'w')
text = input('masukkan kata >>> ')
file.write(text)
print('menulis isi file dengan output = {isi}'.format(isi=text)) |
# EX 1: Bank Exercise
#
# Create a Bank, an Account, and a Customer class.
# All classes should be in a single file.
# The bank class should be able to hold many account.
# You should be able to add new accounts.
# he Account class should have relevant details.
# The Customer class Should also have relevant details.
#
... | class Bank:
def __init__(self):
self.accounts = list()
def add_account(self, new_entry):
self.accounts.append(new_entry)
def print_accounts(self):
for account in self.accounts:
print('account number: ', account.id)
class Account:
def __init__(self, id):
s... |
# This function checks if the number(num)
# is a prime number or not
# and It is the most fastest, the most optimised and the shortest function I have created so far
# At first if number is greater than 1,
# and it is not devided by 2 and it is not to itself either,
# Then it devide this number to all prime numbers unt... | def is_prime(num):
return all((num % i for i in range(3, int(num ** 0.5) + 1, 2))) if num > 1 and num % 2 != 0 else True if num == 2 else False |
#!/usr/bin/env python3
def permurarion(s, start):
if not s or start<0:
return
if start == len(s) -1:
print("".join(s))
else:
i = start
while i < len(s):
s[i], s[start] = s[start], s[i]
permurarion(s, start+1)
s[i], s[start] = s[start... | def permurarion(s, start):
if not s or start < 0:
return
if start == len(s) - 1:
print(''.join(s))
else:
i = start
while i < len(s):
(s[i], s[start]) = (s[start], s[i])
permurarion(s, start + 1)
(s[i], s[start]) = (s[start], s[i])
... |
"""
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last... | """
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last... |
##Patterns: E1128
def test():
return None
##Err: E1128
no_value_returned = test() | def test():
return None
no_value_returned = test() |
# Class decorator alternative to mixins
def LoggedMapping(cls):
cls_getitem = cls.__getitem__
cls_setitem = cls.__setitem__
cls_delitem = cls.__delitem__
def __getitem__(self, key):
print('Getting %s' % key)
return cls_getitem(self, key)
def __setitem__(self, key, value):
... | def logged_mapping(cls):
cls_getitem = cls.__getitem__
cls_setitem = cls.__setitem__
cls_delitem = cls.__delitem__
def __getitem__(self, key):
print('Getting %s' % key)
return cls_getitem(self, key)
def __setitem__(self, key, value):
print('Setting %s = %r' % (key, value))
... |
t = int(input)
while t:
i = int(input())
print(sum([(-1 ** i) / (2 * i + 1) for i in range(i)]))
t -= 1
| t = int(input)
while t:
i = int(input())
print(sum([-1 ** i / (2 * i + 1) for i in range(i)]))
t -= 1 |
#
# PySNMP MIB module Finisher-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Finisher-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:03:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) ... |
#!/usr/bin/env python3
N = int(input().strip())
arr = [int(i) for i in input().strip().split()]
sorted_arr = sorted(arr)
diff_arr = [sorted_arr[i + 1] - sorted_arr[i] for i in range(0, N - 1)]
min_diff = min(diff_arr)
idx = [i for i in range(len(diff_arr)) if diff_arr[i] == min_diff]
for i in idx:
print(sorted_arr... | n = int(input().strip())
arr = [int(i) for i in input().strip().split()]
sorted_arr = sorted(arr)
diff_arr = [sorted_arr[i + 1] - sorted_arr[i] for i in range(0, N - 1)]
min_diff = min(diff_arr)
idx = [i for i in range(len(diff_arr)) if diff_arr[i] == min_diff]
for i in idx:
print(sorted_arr[i], sorted_arr[i + 1], ... |
expected_output = {
"pod": {
1: {
"node": {
1: {
"name": "msl-ifav205-ifc1",
"node": 1,
"pod": 1,
"role": "controller",
"version": "5.1(2e)"
},
101:... | expected_output = {'pod': {1: {'node': {1: {'name': 'msl-ifav205-ifc1', 'node': 1, 'pod': 1, 'role': 'controller', 'version': '5.1(2e)'}, 101: {'name': 'msl-ifav205-leaf1', 'node': 101, 'pod': 1, 'role': 'leaf', 'version': 'n9000-15.1(2e)'}, 201: {'name': 'msl-ifav205-spine1', 'node': 201, 'pod': 1, 'role': 'spine', 'v... |
#
# Copyright (c) 2017 Digital Shadows Ltd.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
#
__version__ = '1.1.0'
| __version__ = '1.1.0' |
test = open('test.txt', 'r')
arr = []
for group in test:
arr.append(int(group.split()[0]))
# Correct Answers:
# - Part 1: 10884537
# - Part 2: 1261309
# ======= Part 1 =======
def part1():
for i in range(25, len(arr)):
sum = False
for j in range(i - 25, i):
if arr[i] -... | test = open('test.txt', 'r')
arr = []
for group in test:
arr.append(int(group.split()[0]))
def part1():
for i in range(25, len(arr)):
sum = False
for j in range(i - 25, i):
if arr[i] - arr[j] in arr[i - 25:i] and arr[i] - arr[j] != arr[j]:
sum = True
... |
#!/usr/bin/python3
# -*-coding:utf-8-*-
__author__ = "Bannings"
class Solution:
def detectCapitalUse(self, word: str) -> bool:
isupper = word[-1].isupper()
for i in range(len(word) - 2, -1, -1):
if word[i].isupper() != isupper and (isupper or i != 0):
return False
... | __author__ = 'Bannings'
class Solution:
def detect_capital_use(self, word: str) -> bool:
isupper = word[-1].isupper()
for i in range(len(word) - 2, -1, -1):
if word[i].isupper() != isupper and (isupper or i != 0):
return False
return True
if __name__ == '__main_... |
# -*- coding: utf-8 -*-
"""
:author: David Siroky (siroky@dasir.cz)
"license: MIT License (see LICENSE.txt or
U{http://www.opensource.org/licenses/mit-license.php})
"""
VERSION = "1.6"
PROTOCOL_VERSION = 1
| """
:author: David Siroky (siroky@dasir.cz)
"license: MIT License (see LICENSE.txt or
U{http://www.opensource.org/licenses/mit-license.php})
"""
version = '1.6'
protocol_version = 1 |
shapenet_30afd2ef2ed30238aa3d0a2f00b54836 = dict(filename= "30afd2ef2ed30238aa3d0a2f00b54836.png" , basic= "dining", subordinate= "dining_00" , subset="A", cluster= 1, object_num= 0, pose= 35, url= "https://s3.amazonaws.com/shapenet-graphical-conventions/30afd2ef2ed30238aa3d0a2f00b54836.png",width= 256, height= 256);
s... | shapenet_30afd2ef2ed30238aa3d0a2f00b54836 = dict(filename='30afd2ef2ed30238aa3d0a2f00b54836.png', basic='dining', subordinate='dining_00', subset='A', cluster=1, object_num=0, pose=35, url='https://s3.amazonaws.com/shapenet-graphical-conventions/30afd2ef2ed30238aa3d0a2f00b54836.png', width=256, height=256)
shapenet_30d... |
IN_PREDICTION="../predictionsULMFiT_200_noLM.csv"
IN_GOLD="../data/sentiment2/tgt-test.txt"
# pred-sentiment.txt Accuracy: 0.9025
# pred-sentiment-trans.txt 0.9008333333333334
# ../pred-sentiment2.txt" 0.9462672372800761
# ../pred-sentiment2-gru.txt 0.948644793152639
# ../pred-sentiment2-large.txt" 0.9481692819781264
... | in_prediction = '../predictionsULMFiT_200_noLM.csv'
in_gold = '../data/sentiment2/tgt-test.txt'
def accuracy(gold, predictions):
correct = 0
if len(predictions) < len(gold):
gold = gold[:len(predictions)]
all = len(gold)
for (g, p) in zip(gold, predictions):
if g == p:
corre... |
# Copyright 2020 The Google Earth Engine Community Authors
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | """Google Earth Engine Developer's Guide examples for 'Images - Gradients'."""
image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').select('B8')
xy_grad = image.gradient()
gradient = xy_grad.select('x').pow(2).add(xy_grad.select('y').pow(2)).sqrt()
direction = xy_grad.select('y').atan2(xy_grad.select('x'))
map_... |
class Footers(object):
def __init__(self, footers: dict, document):
# TODO
self._footers = footers
self._document = document
| class Footers(object):
def __init__(self, footers: dict, document):
self._footers = footers
self._document = document |
def log_error(e):
"""
It is always a good idea to log errors.
This function just prints them, but you can
make it do anything.
"""
print(e)
| def log_error(e):
"""
It is always a good idea to log errors.
This function just prints them, but you can
make it do anything.
"""
print(e) |
# Input: A list / array with integers. For example:
# [3, 4, 1, 2, 9]
# Returns:
# Nothing. However, this function will print out
# a pair of numbers that adds up to 10. For example,
# 1, 9. If no such pair is found, it should print
# "There is no pair that adds up to 10.".
def pair10(given_list):
numbers_se... | def pair10(given_list):
numbers_seen = {}
for item in given_list:
if 10 - item in numbers_seen:
return [10 - item, item]
else:
numbers_seen[item] = 1
if __name__ == '__main__':
print('\n Which pair adds up to 10? (Should print 1, 9)\n\n [3, 4, 1, 2, 9]\n ')
... |
# 62. Unique Paths
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
paths = [[(0 if k > 0 and i > 0 else 1) for i in range(m)] for k in range(n)]
for col in range(1, m):
for row in range(1, n):
if row > 0:
paths[row][col] += path... | class Solution:
def unique_paths(self, m: int, n: int) -> int:
paths = [[0 if k > 0 and i > 0 else 1 for i in range(m)] for k in range(n)]
for col in range(1, m):
for row in range(1, n):
if row > 0:
paths[row][col] += paths[row - 1][col]
... |
# Finite State Expression Parser Function
# Authored by Vishnuprasadh
def parser(fa, fa_dict):
fa_dict.update({"start": ""})
fa_dict.update({"final": []})
fa_dict.update({"transitions": {}})
start = final = False # Keeps track of start and final states
init_tracker = -1 # Keeps track of the begi... | def parser(fa, fa_dict):
fa_dict.update({'start': ''})
fa_dict.update({'final': []})
fa_dict.update({'transitions': {}})
start = final = False
init_tracker = -1
end_tracker = -1
state = ''
key = ''
for (i, x) in enumerate(fa):
if x == '<':
continue
elif x ... |
"""
Allergies exercise
"""
class Allergies:
"""
Class to get all allergies from a score
"""
def __init__(self, score):
"""
Calculate list of allergies from score using dynamic programming
"""
self.dct = {
1: "eggs",
2: "peanuts",
... | """
Allergies exercise
"""
class Allergies:
"""
Class to get all allergies from a score
"""
def __init__(self, score):
"""
Calculate list of allergies from score using dynamic programming
"""
self.dct = {1: 'eggs', 2: 'peanuts', 4: 'shellfish', 8: 'strawberr... |
# CHALLENGE: https://www.hackerrank.com/challenges/30-2d-arrays
def build_arr():
arr = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
arr.append(arr_t)
return arr
def is_square_arr(arr):
for e in arr:
if len(e) != len(arr):
... | def build_arr():
arr = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
arr.append(arr_t)
return arr
def is_square_arr(arr):
for e in arr:
if len(e) != len(arr):
raise value_error('Input is not a n * n 2d array')
return... |
class Solution:
def twoSum(self, nums, target):
'''
# leetcode problem: https://leetcode.com/problems/two-sum/
Method-1: Bruteforce
time compx: O(n^2)
space compx: O(1)
def twoSum(self, nums, targer):
"""TODO: Docstring for bruteForceTwoSum.
... | class Solution:
def two_sum(self, nums, target):
'''
# leetcode problem: https://leetcode.com/problems/two-sum/
Method-1: Bruteforce
time compx: O(n^2)
space compx: O(1)
def twoSum(self, nums, targer):
"""TODO: Docstring for bruteForceTwoSum.
... |
#Copyright ReportLab Europe Ltd. 2000-2006
#see license.txt for license details
__version__=''' $Id: boxstuff.py 2960 2006-08-23 21:41:33Z andy $ '''
def anchorAdjustXY(anchor,x,y,width,height):
if anchor not in ('sw','s','se'):
if anchor in ('e','c','w'):
y -= height/2.
else:
... | __version__ = ' $Id: boxstuff.py 2960 2006-08-23 21:41:33Z andy $ '
def anchor_adjust_xy(anchor, x, y, width, height):
if anchor not in ('sw', 's', 'se'):
if anchor in ('e', 'c', 'w'):
y -= height / 2.0
else:
y -= height
if anchor not in ('nw', 'w', 'sw'):
if anc... |
"""
This Module populate or provide the starting material
for running the SELECTA workflow.
Information from the process_selection table as well
as the SELECTA propertie.txt files are consumed here.
"""
__author__ = 'Nima Pakseresht, Blaise Alako'
class selection:
"""
This Class Initialise the SELECTA workfl... | """
This Module populate or provide the starting material
for running the SELECTA workflow.
Information from the process_selection table as well
as the SELECTA propertie.txt files are consumed here.
"""
__author__ = 'Nima Pakseresht, Blaise Alako'
class Selection:
"""
This Class Initialise the SELECTA workflow... |
companions = int(input())
days = int(input())
coins = 0
for day in range(1, days + 1):
if day % 15 == 0:
companions += 5
if day % 10 == 0:
companions -= 2
if day % 5 == 0:
coins += (companions * 20)
if day % 3 == 0:
coins -= (companions * 2)
if day % 3 == ... | companions = int(input())
days = int(input())
coins = 0
for day in range(1, days + 1):
if day % 15 == 0:
companions += 5
if day % 10 == 0:
companions -= 2
if day % 5 == 0:
coins += companions * 20
if day % 3 == 0:
coins -= companions * 2
if day % 3 == 0:
... |
#
# PySNMP MIB module ZXTM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZXTM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:48:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_size_constraint, value_range_constraint) ... |
'''
Takes raw radiosonde data file from NSGRA-2, removes data that's not required by the simulator, outputs _filtered version.
This _filtered file is the file MAPLEAF expects when using radiosonde mean wind models
'''
if __name__ == "__main__":
# Adjust input (unfiltered) file location here
filePath ... | """
Takes raw radiosonde data file from NSGRA-2, removes data that's not required by the simulator, outputs _filtered version.
This _filtered file is the file MAPLEAF expects when using radiosonde mean wind models
"""
if __name__ == '__main__':
file_path = 'MAPLEAF/Examples/Wind/RadioSondeEdmonton.txt'
... |
class FakeTimer:
def __init__(self, time, function, args=None, kwargs=None):
self._time = time
self._function = function
self._args = args if args is not None else []
self._kwargs = kwargs if kwargs is not None else {}
self._canceled = False
self._started = False
... | class Faketimer:
def __init__(self, time, function, args=None, kwargs=None):
self._time = time
self._function = function
self._args = args if args is not None else []
self._kwargs = kwargs if kwargs is not None else {}
self._canceled = False
self._started = False
... |
# Declare a variable of `name` with an input and a string of "Welcome to the Boba Shop! What is your name?".
name = input("Welcome to the Boba Shop! What is your name?")
# Check if `name` is not an empty string or equal to `None`.
if name != "" or name == None:
# If so, write a print with a string of "Hello" conca... | name = input('Welcome to the Boba Shop! What is your name?')
if name != '' or name == None:
print(f'Hello {name}')
beverage = input('What kind of boba drink would you like?')
sweetness_level = input('How sweet do you want your drink: 0, 50, 100, or 200?')
if sweetness_level == 50:
sweetness = 'h... |
# *************************************************************************
#
# Copyright (c) 2021 Andrei Gramakov. All rights reserved.
#
# This file is licensed under the terms of the MIT license.
# For a copy, see: https://opensource.org/licenses/MIT
#
# site: https://agramakov.me
# e-mail: mail@agramakov.me
#
#... | concept_to_command = 'concept2commands_interpreter'
emotioncore_datadsc = 'EmotionCoreDataDescriptor'
emotioncore_write = 'EmotionCoreWrite'
i2_c = 'i2c_server'
sensor_data_to_concept = 'data2concept_interpreter' |
class Solution:
def solve(self, nums, k):
mods = set()
last = 0
psum = 0
for num in nums:
psum += num
if psum%k in mods: return True
mods.add(last)
last = psum%k
return False
| class Solution:
def solve(self, nums, k):
mods = set()
last = 0
psum = 0
for num in nums:
psum += num
if psum % k in mods:
return True
mods.add(last)
last = psum % k
return False |
class FrameworkRichTextComposition(FrameworkTextComposition):
""" Represents a composition related to text input. You can use this class to find the text position of the composition or the result string. """
CompositionEnd=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the end posit... | class Frameworkrichtextcomposition(FrameworkTextComposition):
""" Represents a composition related to text input. You can use this class to find the text position of the composition or the result string. """
composition_end = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | class Targetsexception(Exception):
"""
Base class for generic package related exceptions.
"""
pass
class Filesystemexception(TargetsException):
"""
Base class for generic file system exceptions.
"""
pass
class Filealreadyexists(FileSystemException):
"""
Raised when a fi... |
def minimumAbsoluteDifference(arr):
# Another way to define this problem is "find the pair of numbers with the smallest distance from each other".
# Easiest to begin approaching this problem is to sort the data set.
sorted_arr = list(sorted(arr))
pairs = zip(sorted_arr, sorted_arr[1:])
# The da... | def minimum_absolute_difference(arr):
sorted_arr = list(sorted(arr))
pairs = zip(sorted_arr, sorted_arr[1:])
smallest_pair = min(pairs, key=lambda pair: abs(pair[0] - pair[1]))
return abs(smallest_pair[0] - smallest_pair[1])
if __name__ == '__main__':
with open('test_case.txt') as f:
n = int... |
def sqrt(x):
i = 1
while i*i<=x:
i*=2
y=0
while i>0:
if(y+i)**2<=x:
y+=i
i//=2
return y
t=100**100
print(sum(
int(c) for c in str(sqrt(t*2))[:100]
))
ans = sum(
sum(int(c) for c in str(sqrt(i * t))[ : 100])
for i in range(1,101)
if sqrt(i)**2 != ... | def sqrt(x):
i = 1
while i * i <= x:
i *= 2
y = 0
while i > 0:
if (y + i) ** 2 <= x:
y += i
i //= 2
return y
t = 100 ** 100
print(sum((int(c) for c in str(sqrt(t * 2))[:100])))
ans = sum((sum((int(c) for c in str(sqrt(i * t))[:100])) for i in range(1, 101) if sqrt... |
candyCan = ["apple", "strawberry", "grape", "mango"]
print(candyCan[1])
print(candyCan[-1])
print(candyCan[1:3]) | candy_can = ['apple', 'strawberry', 'grape', 'mango']
print(candyCan[1])
print(candyCan[-1])
print(candyCan[1:3]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.