content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#Will add a fixed header and return a sendable string (we should add pickle support here at some point somehow), also encodes the message for you
def createMsg(data):
msg = data
msg = f'{len(msg):<10}' + msg
return msg.encode("utf-8")
#streams data from the 'target' socket with an initial buffersiz... | def create_msg(data):
msg = data
msg = f'{len(msg):<10}' + msg
return msg.encode('utf-8')
def stream_data(target, bufferSize):
data = target.recv(bufferSize)
msglen = int(data[:bufferSize].strip())
decoded_data = ''
while len(decoded_data) < msglen:
print(decoded_data)
decod... |
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
last = {0:-1}
s = 0
dp = [0]*len(nums)
for i in range(len(nums)):
s += nums[i]
if s-target in last:
dp[i] = max(dp[i-1] if i-1>=0 else 0, 1+ (dp[last[s-target]] if last... | class Solution:
def max_non_overlapping(self, nums: List[int], target: int) -> int:
last = {0: -1}
s = 0
dp = [0] * len(nums)
for i in range(len(nums)):
s += nums[i]
if s - target in last:
dp[i] = max(dp[i - 1] if i - 1 >= 0 else 0, 1 + (dp[la... |
def ascii_cipher(message, key):
pfactor = max(
i for i in range(2, abs(key)+1)
if is_prime(i) and key%i==0
)*(-1 if key<0 else 1)
return ''.join(chr((ord(c)+pfactor)%128) for c in message)
def is_prime(n):
if n < 2: return False
return all(... | def ascii_cipher(message, key):
pfactor = max((i for i in range(2, abs(key) + 1) if is_prime(i) and key % i == 0)) * (-1 if key < 0 else 1)
return ''.join((chr((ord(c) + pfactor) % 128) for c in message))
def is_prime(n):
if n < 2:
return False
return all((n % i != 0 for i in range(2, round(pow... |
class Solution:
"""
@param heights: a matrix of integers
@return: an integer
"""
def trapRainWater(self, heights):
"""
:type heightMap: List[List[int]]
:rtype: int
"""
m = len(heights)
n = len(heights[0]) if m else 0
peakMap = [[0x7FFFFFF... | class Solution:
"""
@param heights: a matrix of integers
@return: an integer
"""
def trap_rain_water(self, heights):
"""
:type heightMap: List[List[int]]
:rtype: int
"""
m = len(heights)
n = len(heights[0]) if m else 0
peak_map = [[2147483647]... |
def add_two(a, b):
'''Adds two numbers together'''
return a + b
def multiply_two(a, b):
'''Multiplies two numbers together'''
return a * b
| def add_two(a, b):
"""Adds two numbers together"""
return a + b
def multiply_two(a, b):
"""Multiplies two numbers together"""
return a * b |
# # example string
# string = 'cat'
# width = 5
# print right justified string
# print(string.rjust(width))
# print(string.rjust(width))
# # example string
# string = 'cat'
# width = 5
# fillchar = '*'
# # print right justified string
# print(string.rjust(width, fillchar))
# # .centre function
# string = "Python ... | size = 5
a = list(map(chr, range(97, 122)))
m = a[size - 1::-1] + a[:size]
print(m) |
"""
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
R... | """
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
R... |
def test_use_provider(accounts, networks):
with networks.fantom.local.use_provider("test"):
account = accounts.test_accounts[0]
account.transfer(account, 100)
| def test_use_provider(accounts, networks):
with networks.fantom.local.use_provider('test'):
account = accounts.test_accounts[0]
account.transfer(account, 100) |
class Field(object):
def render(self, field):
raise NotImplementedError('Field.render needs to be defined')
class Attr(Field):
def __init__(self, attr, default=None, type=None):
self.attr = attr
self.default = default
if type is None:
self.type = lambda x: x
... | class Field(object):
def render(self, field):
raise not_implemented_error('Field.render needs to be defined')
class Attr(Field):
def __init__(self, attr, default=None, type=None):
self.attr = attr
self.default = default
if type is None:
self.type = lambda x: x
... |
def set_elements_sum(a, b):
c = []
for i in range(len(a)):
result = a[i] + b[i]
c.append(result)
return c
ll = [1, 2, 3, 4, 5]
ll2 = [3, 4, 5, 6, 7]
print(set_elements_sum(ll, ll2))
# [4, 6, 8, 10, 12]
| def set_elements_sum(a, b):
c = []
for i in range(len(a)):
result = a[i] + b[i]
c.append(result)
return c
ll = [1, 2, 3, 4, 5]
ll2 = [3, 4, 5, 6, 7]
print(set_elements_sum(ll, ll2)) |
# URI Online Judge 1133
X = int(input())
Y = int(input())
soma = 0
if Y < X:
X, Y = Y, X
for i in range(X,Y+1):
if i%13!=0:
soma += i
print(soma) | x = int(input())
y = int(input())
soma = 0
if Y < X:
(x, y) = (Y, X)
for i in range(X, Y + 1):
if i % 13 != 0:
soma += i
print(soma) |
salario = float(input())
if (salario >= 0 and salario <= 2000.00):
print('Isento')
elif (salario >= 2000.01 and salario <= 3000.00):
resto = salario - 2000
resul = resto * 0.08
print('R$ {:.2f}'.format(resul))
elif (salario >= 3000.01 and salario <= 4500.00):
resto = salario - 3000
resul = (res... | salario = float(input())
if salario >= 0 and salario <= 2000.0:
print('Isento')
elif salario >= 2000.01 and salario <= 3000.0:
resto = salario - 2000
resul = resto * 0.08
print('R$ {:.2f}'.format(resul))
elif salario >= 3000.01 and salario <= 4500.0:
resto = salario - 3000
resul = resto * 0.18 +... |
for i in range(int(input())):
a, b, c = map(int, input().split())
mi = min(a, b)
ma = max(a, b)
half_circle_people = (ma - mi)
full_circle_people = 2 * half_circle_people
if ma > half_circle_people * 2 or c > full_circle_people:
print(-1)
else:
print((c - half_circle_people... | for i in range(int(input())):
(a, b, c) = map(int, input().split())
mi = min(a, b)
ma = max(a, b)
half_circle_people = ma - mi
full_circle_people = 2 * half_circle_people
if ma > half_circle_people * 2 or c > full_circle_people:
print(-1)
else:
print((c - half_circle_people -... |
# model settings
model = dict(
type='Recognizer3DRPL',
backbone=dict(
type='ResNet3dSlowOnly',
depth=50,
pretrained='torchvision://resnet50',
lateral=False,
out_indices=(2, 3),
conv1_kernel=(1, 7, 7),
conv1_stride_t=1,
pool1_stride_t=1,
inf... | model = dict(type='Recognizer3DRPL', backbone=dict(type='ResNet3dSlowOnly', depth=50, pretrained='torchvision://resnet50', lateral=False, out_indices=(2, 3), conv1_kernel=(1, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(0, 0, 1, 1), norm_eval=False), neck=dict(type='TPN', in_channels=(1024, 2048), out_channels=1... |
def make_divider():
return {"type": "divider"}
def make_markdown(text):
return {"type": "mrkdwn", "text": text }
def make_section(text):
return {"type":"section", "text": make_markdown(text)}
def make_context(*args):
return {"type":"context", "elements": [*args]}
def make_blocks(*args):
return [... | def make_divider():
return {'type': 'divider'}
def make_markdown(text):
return {'type': 'mrkdwn', 'text': text}
def make_section(text):
return {'type': 'section', 'text': make_markdown(text)}
def make_context(*args):
return {'type': 'context', 'elements': [*args]}
def make_blocks(*args):
return ... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/nvidia/linorobot_ws/src/imu_calib/include;/usr/local/include/eigen3".split(';') if "/home/nvidia/linorobot_ws/src/imu_calib/include;/usr/local/include/eigen3" != "" else []
PROJECT_CATKIN_DEPENDS... | catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/nvidia/linorobot_ws/src/imu_calib/include;/usr/local/include/eigen3'.split(';') if '/home/nvidia/linorobot_ws/src/imu_calib/include;/usr/local/include/eigen3' != '' else []
project_catkin_depends = 'cmake_modules;roscpp;sensor_msgs;lino_msgs'.replace('... |
numero = int(input("Entre com um numero inteiro e menor que 1000: "))
if numero > 1000:
print("Numero invalido")
else:
unidade = numero % 10
numero = (numero - unidade) / 10
dezena = int(numero % 10)
numero = (numero - dezena) / 10
centena = int(numero)
print(f"{centena} centena(s) , {dezena... | numero = int(input('Entre com um numero inteiro e menor que 1000: '))
if numero > 1000:
print('Numero invalido')
else:
unidade = numero % 10
numero = (numero - unidade) / 10
dezena = int(numero % 10)
numero = (numero - dezena) / 10
centena = int(numero)
print(f'{centena} centena(s) , {dezena... |
def str_to_bool(s):
if isinstance(s, bool): # do not convert if already a boolean
return s
else:
if s == 'True' \
or s == 'true' \
or s == '1' \
or s == 1 \
or s == True:
return True
elif s == 'False' \
... | def str_to_bool(s):
if isinstance(s, bool):
return s
elif s == 'True' or s == 'true' or s == '1' or (s == 1) or (s == True):
return True
elif s == 'False' or s == 'false' or s == '0' or (s == 0) or (s == False):
return False
return False |
"""Version
==========
"""
__version__ = "0.4.0"
| """Version
==========
"""
__version__ = '0.4.0' |
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
ver1 = version1.split('.')
ver2 = version2.split('.')
def removeLeadingZeros(s):
while len(s) > 1 and s[0] == '0':
s = s[1:]
return s
ver1... | class Solution:
def compare_version(self, version1: str, version2: str) -> int:
ver1 = version1.split('.')
ver2 = version2.split('.')
def remove_leading_zeros(s):
while len(s) > 1 and s[0] == '0':
s = s[1:]
return s
ver1 = [remove_leading_zer... |
GUIDs = {
"ASROCK_ACPIS4_DXE_GUID": [69196166, 45078, 18382, 175, 197, 34, 105, 237, 212, 173, 100],
"ASROCK_USBRT_GUID": [82487969, 10657, 4567, 136, 56, 0, 80, 4, 115, 212, 235],
"ASROCK_RAID_SETUP_GUID": [152494882, 14144, 12750, 173, 98, 189, 23, 44, 236, 202, 54],
"ASROCK_RAID_LOADER_GUID": [16450... | gui_ds = {'ASROCK_ACPIS4_DXE_GUID': [69196166, 45078, 18382, 175, 197, 34, 105, 237, 212, 173, 100], 'ASROCK_USBRT_GUID': [82487969, 10657, 4567, 136, 56, 0, 80, 4, 115, 212, 235], 'ASROCK_RAID_SETUP_GUID': [152494882, 14144, 12750, 173, 98, 189, 23, 44, 236, 202, 54], 'ASROCK_RAID_LOADER_GUID': [164506669, 19843, 1759... |
"""
General unit tests
"""
class TestClass:
def test_base(self):
assert 42 == 42
| """
General unit tests
"""
class Testclass:
def test_base(self):
assert 42 == 42 |
'''
Python program to convert the distance (in feet) to inches,yards, and miles
'''
def distanceInInches (d_ft):
print("The distance in inches is %i inches." %(d_ft * 12))
def distanceInYard (d_ft):
print("The distance in yards is %.2f yards." %(d_ft / 3.0))
def distanceInMiles (d_ft):
print("The distanc... | """
Python program to convert the distance (in feet) to inches,yards, and miles
"""
def distance_in_inches(d_ft):
print('The distance in inches is %i inches.' % (d_ft * 12))
def distance_in_yard(d_ft):
print('The distance in yards is %.2f yards.' % (d_ft / 3.0))
def distance_in_miles(d_ft):
print('The di... |
def somme(liste_nombres):
pass
def moyenne(liste_nombres):
pass
| def somme(liste_nombres):
pass
def moyenne(liste_nombres):
pass |
class Solution:
def solve(self, genes):
ans = 0
seen = set()
genes = set(genes)
for gene in genes:
if gene in seen:
continue
ans += 1
dfs = [gene]
seen.add(gene)
while dfs:
cur = dfs.pop()
... | class Solution:
def solve(self, genes):
ans = 0
seen = set()
genes = set(genes)
for gene in genes:
if gene in seen:
continue
ans += 1
dfs = [gene]
seen.add(gene)
while dfs:
cur = dfs.pop()
... |
def title1(content):
return "<h1 class='display-1'>{}</h1>".format(content)
def title2(content):
return "<h2 class='display-2'>{}</h2>".format(content)
def title3(content):
return "<h3 class='display-3'>{}</h3>".format(content)
def title4(content):
return "<h4 class='display-4'>{}... | def title1(content):
return "<h1 class='display-1'>{}</h1>".format(content)
def title2(content):
return "<h2 class='display-2'>{}</h2>".format(content)
def title3(content):
return "<h3 class='display-3'>{}</h3>".format(content)
def title4(content):
return "<h4 class='display-4'>{}</h4>".format(conten... |
class Constants:
# DATA TYPES
GENERATE_EPR_IF_NONE = 'generate_epr_if_none'
AWAIT_ACK = 'await_ack'
SEQUENCE_NUMBER = 'sequence_number'
PAYLOAD = 'payload'
PAYLOAD_TYPE = 'payload_type'
SENDER = 'sender'
RECEIVER = 'receiver'
PROTOCOL = 'protocol'
KEY = 'key'
# WAIT TIME
... | class Constants:
generate_epr_if_none = 'generate_epr_if_none'
await_ack = 'await_ack'
sequence_number = 'sequence_number'
payload = 'payload'
payload_type = 'payload_type'
sender = 'sender'
receiver = 'receiver'
protocol = 'protocol'
key = 'key'
wait_time = 10
epr = 0
da... |
#--------------------------------------------------------------------#
# Help program.
# Created by: Jim - https://www.youtube.com/watch?v=XCgWYx-lGl8
# Changed by: Thiago Piovesan
#--------------------------------------------------------------------#
# When to use class methods and when to use static methods ?
#-----... | class Item:
@staticmethod
def is_integer():
"""
This should do something that has a relationship
with the class, but not something that must be unique
per instance!
"""
@classmethod
def instantiate_from_something(cls):
"""
This should also do som... |
FIPS_Reference = {
"AL":"01",
"AK":"02",
"AZ":"04",
"AR":"05",
"AS":"60",
"CA":"06",
"CO":"08",
"CT":"09",
"DE":"10",
"FL":"12",
"GA":"13",
"GU":"66",
"HI":"15",
"ID":"16",
"IL":"17",
"IN":"18... | fips__reference = {'AL': '01', 'AK': '02', 'AZ': '04', 'AR': '05', 'AS': '60', 'CA': '06', 'CO': '08', 'CT': '09', 'DE': '10', 'FL': '12', 'GA': '13', 'GU': '66', 'HI': '15', 'ID': '16', 'IL': '17', 'IN': '18', 'IA': '19', 'KS': '20', 'KY': '21', 'LA': '22', 'ME': '23', 'MD': '24', 'MA': '25', 'MI': '26', 'MN': '27', '... |
def check_full_text(fb_full_text, filter_full_text) -> bool:
if filter_full_text is None or fb_full_text == filter_full_text:
return True
return False
def check_contains(fb_contains, filter_contains) -> bool:
if filter_contains is None:
return True
intersection = list(fb_contains & fil... | def check_full_text(fb_full_text, filter_full_text) -> bool:
if filter_full_text is None or fb_full_text == filter_full_text:
return True
return False
def check_contains(fb_contains, filter_contains) -> bool:
if filter_contains is None:
return True
intersection = list(fb_contains & filt... |
class _Manager(type):
""" Singletone for cProfile manager """
_inst = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._inst:
cls._inst[cls] = super(_Manager, cls).__call__(*args, **kwargs)
return cls._inst[cls]
class ProfileManager(metaclass=_Manager):
def __init... | class _Manager(type):
""" Singletone for cProfile manager """
_inst = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._inst:
cls._inst[cls] = super(_Manager, cls).__call__(*args, **kwargs)
return cls._inst[cls]
class Profilemanager(metaclass=_Manager):
def __init_... |
class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
sums = sum(nums)
index = 0
res = 0
for ele in nums:
res += index*ele
index += 1
ans = res
for i in range(1,len(nums)):
res = res + sums - (len(nums))*nums[len(nums... | class Solution:
def max_rotate_function(self, nums: List[int]) -> int:
sums = sum(nums)
index = 0
res = 0
for ele in nums:
res += index * ele
index += 1
ans = res
for i in range(1, len(nums)):
res = res + sums - len(nums) * nums[le... |
def is_even(n):
return n % 2 == 0
def is_odd(n):
return not is_even(n)
lost_numbers = (4, 8, 15, 16, 23, 42)
| def is_even(n):
return n % 2 == 0
def is_odd(n):
return not is_even(n)
lost_numbers = (4, 8, 15, 16, 23, 42) |
# You are given two non-empty linked lists representing two non-negative integers.
# The digits are stored in reverse order and each of their nodes contain a single digit.
# Add the two numbers and return it as a linked list.
# You may assume the two numbers do not contain any leading zero, except the number 0 itself... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def add_two_numbers(self, l1, l2):
dummy = list_node(-1)
cur = dummy
t = 0
while l1 or l2 or t:
if l1:
t += l1.val
l... |
# Given two strings s and t, determine if they are isomorphic.
# Two strings s and t are isomorphic if the characters in s can be replaced to
# get t.
# All occurrences of a character must be replaced with another character while
# preserving the order of characters. No two characters may map to the same
# character,... | class Dictsetsolution:
def is_isomorphic(self, s: str, t: str) -> bool:
replacements = {}
mapped = set()
for (s_let, t_let) in zip(s, t):
if (replacement := replacements.get(s_let)):
if replacement != t_let:
return False
else:
... |
def mergeSort(elements):
if len(elements) == 0 or len(elements) == 1:
# BASE CASE
return elements
middle = len(elements) // 2
left = mergeSort(elements[:middle])
right = mergeSort(elements[middle:])
if left == [] or right == []:
return left or right
result = []
i, ... | def merge_sort(elements):
if len(elements) == 0 or len(elements) == 1:
return elements
middle = len(elements) // 2
left = merge_sort(elements[:middle])
right = merge_sort(elements[middle:])
if left == [] or right == []:
return left or right
result = []
(i, j) = (0, 0)
whi... |
__author__ = 'James Myatt'
__version__ = '0.0.2'
__all__ = [
'monitor', 'sensor', 'utils',
'time', 'w1therm'
]
| __author__ = 'James Myatt'
__version__ = '0.0.2'
__all__ = ['monitor', 'sensor', 'utils', 'time', 'w1therm'] |
class SocketAPIError(Exception):
pass
class InvalidRequestError(SocketAPIError):
pass
class InvalidURIError(InvalidRequestError):
pass
class NotFoundError(InvalidRequestError):
pass
| class Socketapierror(Exception):
pass
class Invalidrequesterror(SocketAPIError):
pass
class Invalidurierror(InvalidRequestError):
pass
class Notfounderror(InvalidRequestError):
pass |
# Prints out a string
print("Mary had a little lamb.")
# Prints out a formatted string
print("Its fleece was white as {}.".format('snow'))
# Prints out another string
print("and everywhere that Mary went.")
# Prints a period for ten times
print("." * 10) # what'd that do?
# Assign a letter to string variable
end1 = "... | print('Mary had a little lamb.')
print('Its fleece was white as {}.'.format('snow'))
print('and everywhere that Mary went.')
print('.' * 10)
end1 = 'C'
end2 = 'h'
end3 = 'e'
end4 = 'e'
end5 = 's'
end6 = 'e'
end7 = 'B'
end8 = 'u'
end9 = 'r'
end10 = 'g'
end11 = 'e'
end12 = 'r'
print(end1 + end2 + end3 + end4 + end5 + end... |
"""
Drones library and API version.
"""
DRONES_VERSION = "0.1.2"
| """
Drones library and API version.
"""
drones_version = '0.1.2' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class HookitConnectionError(Exception):
pass
__all__ = ['HookitConnectionError']
| class Hookitconnectionerror(Exception):
pass
__all__ = ['HookitConnectionError'] |
def get_gene_ne(global_variables,gene_dictionary):
values_list = []
# gets the ordered samples
sample_list = global_variables["sample_list"]
for sample in sample_list:
values_list.append(gene_dictionary[sample])
return values_list
| def get_gene_ne(global_variables, gene_dictionary):
values_list = []
sample_list = global_variables['sample_list']
for sample in sample_list:
values_list.append(gene_dictionary[sample])
return values_list |
def ceasear_encode( msg, key ):
code = ""
key = ord(key.upper())-ord("A")
for c in msg.upper():
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
new_ord = ord(c)+key
if new_ord > ord("Z"):
new_ord -= 26
code += chr(new_ord)
else:
code +=... | def ceasear_encode(msg, key):
code = ''
key = ord(key.upper()) - ord('A')
for c in msg.upper():
if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
new_ord = ord(c) + key
if new_ord > ord('Z'):
new_ord -= 26
code += chr(new_ord)
else:
code +=... |
def version():
"""Function takes no aruguments and returns a STR value of the current version of the library. This value should match
the value in the setup.py
:param None
:return str value of the current version of the library
:rtype str
>>> version()
1.0.33
"""
print ('1.0.34') | def version():
"""Function takes no aruguments and returns a STR value of the current version of the library. This value should match
the value in the setup.py
:param None
:return str value of the current version of the library
:rtype str
>>> version()
1.0.33
"""
print('1.0.34') |
"""
The main module of DAFEST project.
ADAFEST is an abbreviation: 'A Data-Driven Approach to Estimating / Evaluating Software Testability'
The full version of source code will be available
as soon as the relevant paper(s) are published.
"""
class Main():
"""Welcome to project ADAFEST
This file contains t... | """
The main module of DAFEST project.
ADAFEST is an abbreviation: 'A Data-Driven Approach to Estimating / Evaluating Software Testability'
The full version of source code will be available
as soon as the relevant paper(s) are published.
"""
class Main:
"""Welcome to project ADAFEST
This file contains the ... |
def sublime():
return [
('MacOS', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126.dmg', 'sublime/sublime.dmg'),
('Windows (32-bit)', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126%20Setup.exe', 'sublime/sublime-x86.exe'), # noqa
('Windows (64-bit)', 'https:... | def sublime():
return [('MacOS', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126.dmg', 'sublime/sublime.dmg'), ('Windows (32-bit)', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126%20Setup.exe', 'sublime/sublime-x86.exe'), ('Windows (64-bit)', 'https://download.sublimetext.com/Sublime... |
class PyEVMError(Exception):
"""
Base class for all py-hvm errors.
"""
pass
class VMNotFound(PyEVMError):
"""
Raised when no VM is available for the provided block number.
"""
pass
class NoGenesisBlockPresent(PyEVMError):
"""
Raised when a block is imported but there is no gen... | class Pyevmerror(Exception):
"""
Base class for all py-hvm errors.
"""
pass
class Vmnotfound(PyEVMError):
"""
Raised when no VM is available for the provided block number.
"""
pass
class Nogenesisblockpresent(PyEVMError):
"""
Raised when a block is imported but there is no gene... |
example_data = """\
1721
979
366
299
675
1456\
"""
data = """\
1914
1931
1892
1584
1546
1988
1494
1709
1624
1755
1849
1430
1890
1675
1604
1580
1500
1277
1729
1456
2002
1075
1512
895
1843
1921
1904
1989
1407
1552
1714
757
1733
1459
1777
1440
1649
1409
1662
1968
1775
1998
1754
1938
1964
1415
1990
1997
1870
1664
1145
178... | example_data = '1721\n979\n366\n299\n675\n1456'
data = '1914\n1931\n1892\n1584\n1546\n1988\n1494\n1709\n1624\n1755\n1849\n1430\n1890\n1675\n1604\n1580\n1500\n1277\n1729\n1456\n2002\n1075\n1512\n895\n1843\n1921\n1904\n1989\n1407\n1552\n1714\n757\n1733\n1459\n1777\n1440\n1649\n1409\n1662\n1968\n1775\n1998\n1754\n1938\n19... |
#ID of the project
project_id = ""
#List of paths where the folders to check are
project_paths = []
#Destination of the sync, trailing slash
destination_path = ""
##################################
#Postgres database and rw user
##################################
db_host = ""
db_db = ""
db_user = ""
... | project_id = ''
project_paths = []
destination_path = ''
db_host = ''
db_db = ''
db_user = ''
sleep = 180 |
class Solution:
def summaryRanges(self, nums):
if not nums:
return nums
results = []
start = end = nums[0]
for i in nums:
if i != end:
rng = f"{start}->{end-1}" if start != (end - 1) else f"{start}"
results.append(rng)
... | class Solution:
def summary_ranges(self, nums):
if not nums:
return nums
results = []
start = end = nums[0]
for i in nums:
if i != end:
rng = f'{start}->{end - 1}' if start != end - 1 else f'{start}'
results.append(rng)
... |
class Solution:
def totalNQueens(self, n: int) -> int:
def dfs(row):
if row == 0:
return 1
count = 0
for col in range(n):
if col not in col_blacklist and \
row - col not in major_blacklist and \
row + ... | class Solution:
def total_n_queens(self, n: int) -> int:
def dfs(row):
if row == 0:
return 1
count = 0
for col in range(n):
if col not in col_blacklist and row - col not in major_blacklist and (row + col not in minor_blacklist):
... |
N = int(input())
R = []
for i in range(0, N*2) :
if i%2 == 0 : R.append("*")
else : R.append(" ")
for l in range(0, N) :
P1 = P2 = ""
for i in range(0, N) :
P1 += R[i]
print(P1)
for i in range(N*2-1, N-1, -1) :
P2 += R[i]
print(P2) | n = int(input())
r = []
for i in range(0, N * 2):
if i % 2 == 0:
R.append('*')
else:
R.append(' ')
for l in range(0, N):
p1 = p2 = ''
for i in range(0, N):
p1 += R[i]
print(P1)
for i in range(N * 2 - 1, N - 1, -1):
p2 += R[i]
print(P2) |
#
# PySNMP MIB module SYMMCOMMONPTP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMCOMMONPTP
# Produced by pysmi-0.3.4 at Tue Jul 30 11:34:16 2019
# On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt
# Using Python version 3.7.4 (default, J... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint) ... |
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
non_zeros = [i for i in range(len(nums)) if nums[i] != 0] # List comprehension to keep only numbers that are non -zero
nz = len(non_zeros)
nums[:nz] = [nums[i] for i in non_zeros] # edit the list to add non zero num... | class Solution:
def move_zeroes(self, nums: List[int]) -> None:
non_zeros = [i for i in range(len(nums)) if nums[i] != 0]
nz = len(non_zeros)
nums[:nz] = [nums[i] for i in non_zeros]
nums[nz:] = [0] * (len(nums) - nz) |
DEFAULT_OCR_AUTO_OCR = True
DEFAULT_OCR_BACKEND = 'mayan.apps.ocr.backends.tesseract.Tesseract'
DEFAULT_OCR_BACKEND_ARGUMENTS = {'environment': {'OMP_THREAD_LIMIT': '1'}}
TASK_DOCUMENT_VERSION_PAGE_OCR_RETRY_DELAY = 10
TASK_DOCUMENT_VERSION_PAGE_OCR_TIMEOUT = 10 * 60 # 10 Minutes per page
| default_ocr_auto_ocr = True
default_ocr_backend = 'mayan.apps.ocr.backends.tesseract.Tesseract'
default_ocr_backend_arguments = {'environment': {'OMP_THREAD_LIMIT': '1'}}
task_document_version_page_ocr_retry_delay = 10
task_document_version_page_ocr_timeout = 10 * 60 |
input()
c = int(input())
a = sorted((map(int, input().split())))
a.sort(key= lambda x: x%c)
print(*a) | input()
c = int(input())
a = sorted(map(int, input().split()))
a.sort(key=lambda x: x % c)
print(*a) |
def greet(name):
return "Hello {}".format(name)
print(greet("Alice"))
def greet2(name):
def greet_message():
return "Hello"
return "{} {}".format(greet_message(),name)
print(greet2("Alice"))
def change_name_greet(func):
name = "Alice"
return func(name)
print(change_name_greet(greet))
... | def greet(name):
return 'Hello {}'.format(name)
print(greet('Alice'))
def greet2(name):
def greet_message():
return 'Hello'
return '{} {}'.format(greet_message(), name)
print(greet2('Alice'))
def change_name_greet(func):
name = 'Alice'
return func(name)
print(change_name_greet(greet))
de... |
class Helpers(object):
"""
Adds additional helper functions that aren't part of the core or extended
API.
"""
def __init__(self, api):
self.api = api
def is_promotable(self, tail):
# type: (TransactionHash) -> bool
"""
Determines if a tail transaction is promotable.
:param tail:
... | class Helpers(object):
"""
Adds additional helper functions that aren't part of the core or extended
API.
"""
def __init__(self, api):
self.api = api
def is_promotable(self, tail):
"""
Determines if a tail transaction is promotable.
:param tail:
Transaction hash. Must ... |
class FormClosedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.Form.FormClosed event.
FormClosedEventArgs(closeReason: CloseReason)
"""
@staticmethod
def __new__(self, closeReason):
""" __new__(cls: type,closeReason: CloseReason) """
pass
Clos... | class Formclosedeventargs(EventArgs):
"""
Provides data for the System.Windows.Forms.Form.FormClosed event.
FormClosedEventArgs(closeReason: CloseReason)
"""
@staticmethod
def __new__(self, closeReason):
""" __new__(cls: type,closeReason: CloseReason) """
pass
close_reason = prop... |
s = b'abc'; print(s.islower(), s)
s = b'Abc'; print(s.islower(), s)
s = b'ABC'; print(s.islower(), s)
s = b'123'; print(s.islower(), s)
s = b'(_)'; print(s.islower(), s)
s = b'(abc)'; print(s.islower(), s)
s = b'(aBc)'; print(s.islower(), s)
s = bytearray(b'abc'); print(s.islower(), s)
s = bytearray(b'Abc'); print(s.i... | s = b'abc'
print(s.islower(), s)
s = b'Abc'
print(s.islower(), s)
s = b'ABC'
print(s.islower(), s)
s = b'123'
print(s.islower(), s)
s = b'(_)'
print(s.islower(), s)
s = b'(abc)'
print(s.islower(), s)
s = b'(aBc)'
print(s.islower(), s)
s = bytearray(b'abc')
print(s.islower(), s)
s = bytearray(b'Abc')
print(s.islower(), ... |
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height)-1
res = 0
area = 0
while i < j:
area = min(height[i],height[j])*(j-i)
#print(area)
res = max(res,area)
if height[i]<height[j]:
i+... | class Solution:
def max_area(self, height: List[int]) -> int:
i = 0
j = len(height) - 1
res = 0
area = 0
while i < j:
area = min(height[i], height[j]) * (j - i)
res = max(res, area)
if height[i] < height[j]:
i += 1
... |
explanations = {
'gamma': '''
Proportion of tree modifications that should use mutrel-informed choice for
node to move, rather than uniform choice
''',
'zeta': '''
Proportion of tree modifications that should use mutrel-informed choice for
destination to move node to, rather than uniform choice
... | explanations = {'gamma': '\n Proportion of tree modifications that should use mutrel-informed choice for\n node to move, rather than uniform choice\n ', 'zeta': '\n Proportion of tree modifications that should use mutrel-informed choice for\n destination to move node to, rather than uniform choice\n ', 'i... |
def _impl(_ctx):
pass
bad_attrs = rule(implementation = _impl, attrs = {"1234isntvalid": attr.int()})
| def _impl(_ctx):
pass
bad_attrs = rule(implementation=_impl, attrs={'1234isntvalid': attr.int()}) |
# Copyright (c) 2017 Hristo Iliev <github@hiliev.eu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of c... | dmu_type_desc = ['unallocated', 'object directory', 'object array', 'packed nvlist', 'packed nvlist size', 'bpobj', 'bpobj header', 'SPA space map header', 'SPA space map', 'ZIL intent log', 'DMU dnode', 'DMU objset', 'DSL directory', 'DSL directory child map', 'DSL dataset snap map', 'DSL props', 'DSL dataset', 'ZFS z... |
def caesar_encode(phrase, shift):
res=[]
for i,j in enumerate(phrase.split()):
res.append("".join(chr(ord("a")+(ord(k)-ord("a")+shift+i)%26) for k in j))
return " ".join(res) | def caesar_encode(phrase, shift):
res = []
for (i, j) in enumerate(phrase.split()):
res.append(''.join((chr(ord('a') + (ord(k) - ord('a') + shift + i) % 26) for k in j)))
return ' '.join(res) |
expected_output = {
'ints': {
'Ethernet 1/1/1': {
'ip_address': 'unassigned',
'ok': True,
'method': 'unset',
'status': 'up',
'protocol': 'up'
},
'Ethernet 1/1/2': {
'ip_address': 'unassigned',
'ok': True,
... | expected_output = {'ints': {'Ethernet 1/1/1': {'ip_address': 'unassigned', 'ok': True, 'method': 'unset', 'status': 'up', 'protocol': 'up'}, 'Ethernet 1/1/2': {'ip_address': 'unassigned', 'ok': True, 'method': 'unset', 'status': 'up', 'protocol': 'up'}, 'Ethernet 1/1/3': {'ip_address': 'unassigned', 'ok': True, 'method... |
class UnshortenerOld():
"""
Todo option selenium ?
"""
def __init__(self,
logger=None,
verbose=True,
maxItemCount=100000000,
maxDataSizeMo=10000,
dataDir=None,
seleniumBrowserCount=20,
... | class Unshortenerold:
"""
Todo option selenium ?
"""
def __init__(self, logger=None, verbose=True, maxItemCount=100000000, maxDataSizeMo=10000, dataDir=None, seleniumBrowserCount=20, resetBrowsersRate=0.1, useSelenium=False, seleniumBrowsersIsNice=True, storeAll=False, readOnly=False, shortenersDom... |
class Solution:
def removeElement(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
print(count)
return(count)
obj = Solution()
obj.removeElement([3,2,2,3], 3)
obj.removeEl... | class Solution:
def remove_element(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
print(count)
return count
obj = solution()
obj.removeElement([3, 2, 2, 3], 3)
obj.removeElement([... |
#!/usr/bin/env python3
class Solution:
def buddStrings(self, A, B):
la, lb = len(A), len(B)
if la != lb:
return False
diff = [i for i in range(la) if A[i] != B[i]]
if len(diff) > 2 or len(diff) == 1:
return False
elif len(diff) == 0 and len(set(A)) ==... | class Solution:
def budd_strings(self, A, B):
(la, lb) = (len(A), len(B))
if la != lb:
return False
diff = [i for i in range(la) if A[i] != B[i]]
if len(diff) > 2 or len(diff) == 1:
return False
elif len(diff) == 0 and len(set(A)) == la:
r... |
print('this is the first line of second.py')
for x in range(20):
print(x)
print('this is the chunk of code added to the fourth branch')
print('Im editing this file in GitHub to see if fetch finds it')
print('adding this code to push to the main on the remote repository') | print('this is the first line of second.py')
for x in range(20):
print(x)
print('this is the chunk of code added to the fourth branch')
print('Im editing this file in GitHub to see if fetch finds it')
print('adding this code to push to the main on the remote repository') |
def count_substring(string, sub_string):
k = len(sub_string)
ans = 0
for i in range(len(string)):
if i+k > len(string):
break
if sub_string == string[i:i+k]:
ans += 1
return ans
if __name__ == '__main__':
string = input().strip()
sub_string = input().stri... | def count_substring(string, sub_string):
k = len(sub_string)
ans = 0
for i in range(len(string)):
if i + k > len(string):
break
if sub_string == string[i:i + k]:
ans += 1
return ans
if __name__ == '__main__':
string = input().strip()
sub_string = input().s... |
print("Hello World")
my_name = input("Whats your name? ")
print("Hello " + my_name)
print('Did you know that your name is ' + str(len(my_name)) + ' letters long!')
| print('Hello World')
my_name = input('Whats your name? ')
print('Hello ' + my_name)
print('Did you know that your name is ' + str(len(my_name)) + ' letters long!') |
"""
37. How to get the nrows, ncolumns, datatype, summary stats of each column of a dataframe? Also get the array and list equivalent.
"""
"""
Difficulty Level: L2
"""
"""
Get the number of rows, columns, datatype and summary statistics of each column of the Cars93 dataset. Also get the numpy array and list equivalent ... | """
37. How to get the nrows, ncolumns, datatype, summary stats of each column of a dataframe? Also get the array and list equivalent.
"""
'\nDifficulty Level: L2\n'
'\nGet the number of rows, columns, datatype and summary statistics of each column of the Cars93 dataset. Also get the numpy array and list equivalent of ... |
#py_screener.py
def screener(user_inp=None):
"""A function to square only floating points.
Returns custom exceptions if an int or complex is encountered."""
#make sure something was input
if not user_inp:
print("Ummm...did you type in ANYTHING?")
return
#If it *might* be a floa... | def screener(user_inp=None):
"""A function to square only floating points.
Returns custom exceptions if an int or complex is encountered."""
if not user_inp:
print('Ummm...did you type in ANYTHING?')
return
if '.' in user_inp:
try:
inp_as_float = float(user_inp)
... |
default_mapping = {
'Recipient Name': 'recipient_name',
'Recipient DUNS Number': 'recipient_unique_id',
'Awarding Agency': 'awarding_toptier_agency_name',
'Awarding Agency Code': 'awarding_toptier_agency_code',
'Awarding Sub Agency': 'awarding_subtier_agency_name',
'Awarding Sub Agency Code': 'a... | default_mapping = {'Recipient Name': 'recipient_name', 'Recipient DUNS Number': 'recipient_unique_id', 'Awarding Agency': 'awarding_toptier_agency_name', 'Awarding Agency Code': 'awarding_toptier_agency_code', 'Awarding Sub Agency': 'awarding_subtier_agency_name', 'Awarding Sub Agency Code': 'awarding_subtier_agency_co... |
class Reporting(object):
def __init__(self, verbose=False, debug=False):
self.verbose_flag = verbose
self.debug_flag = debug
def error(self, msg):
pass
def debug(self, msg):
pass
def verbose(self, msg):
pass
| class Reporting(object):
def __init__(self, verbose=False, debug=False):
self.verbose_flag = verbose
self.debug_flag = debug
def error(self, msg):
pass
def debug(self, msg):
pass
def verbose(self, msg):
pass |
def iloc(records, rows=':', cols=':') -> list:
"""A Pandas .iloc-like function.
Args:
records (list): A 2-D list.
rows (str or int): The indices of rows. Default is ':'.
cols (str or int): The indices of columns. Default is ':'.
Returns:
list: The sliced records.
Examp... | def iloc(records, rows=':', cols=':') -> list:
"""A Pandas .iloc-like function.
Args:
records (list): A 2-D list.
rows (str or int): The indices of rows. Default is ':'.
cols (str or int): The indices of columns. Default is ':'.
Returns:
list: The sliced records.
Examp... |
class Solution:
def isValid(self, s: str) -> bool:
if not s: return True
if len(s) % 2: return False
if s[0] in ']})': return False
maps = {'(':')', '{':'}', '[':']'}
stack = []
for char in s:
if char in '({[':
stack.appen... | class Solution:
def is_valid(self, s: str) -> bool:
if not s:
return True
if len(s) % 2:
return False
if s[0] in ']})':
return False
maps = {'(': ')', '{': '}', '[': ']'}
stack = []
for char in s:
if char in '({[':
... |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/next-sparse-binary-number/0
def sol(num):
"""
By definition of sparse number two 1s cannot be adjacent but zeroes can be
If two 1s are adjacent and we want to make a bigger number we cannot
make the either of the bits 0, so only option le... | def sol(num):
"""
By definition of sparse number two 1s cannot be adjacent but zeroes can be
If two 1s are adjacent and we want to make a bigger number we cannot
make the either of the bits 0, so only option left is we make the third
bit 1 if it is 0 or we add an extra bit
"""
b = list(bin(n... |
command = input()
kids = 0
adults = 0
while command != "Christmas":
peoples_age = int(command)
if peoples_age <= 16:
kids += 1
elif peoples_age > 16:
adults += 1
command = input()
if command == "Christmas":
total_toys_price = kids * 5
total_sweater_price = adults * 15
pri... | command = input()
kids = 0
adults = 0
while command != 'Christmas':
peoples_age = int(command)
if peoples_age <= 16:
kids += 1
elif peoples_age > 16:
adults += 1
command = input()
if command == 'Christmas':
total_toys_price = kids * 5
total_sweater_price = adults * 15
print(f... |
class Solution(object):
def findBestValue(self, arr, target):
arr.sort(reverse = True)
while arr and target >= arr[-1]*len(arr):
temp = arr[-1]
target -= arr.pop()
if not arr:
return temp
res = target / float(len(arr))
if res % 1 > 0.5:
... | class Solution(object):
def find_best_value(self, arr, target):
arr.sort(reverse=True)
while arr and target >= arr[-1] * len(arr):
temp = arr[-1]
target -= arr.pop()
if not arr:
return temp
res = target / float(len(arr))
if res % 1 > 0.5:
... |
# Converts RGB to GRB which is needed by the lightstrip
def Color(red, green, blue, white = 0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (green <<... | def color(red, green, blue, white=0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return white << 24 | green << 16 | red << 8 | blue
def get_rgb(color):
r = 255 ... |
class MockRequests:
def __init__(self, ok=True, json_data=None):
self.ok = ok
self.json_data = json_data
self.get_method_called = False
def __call__(self, *args, **kwargs):
self.get_method_called = True
self.response = MockResponse(json_data=self.json_data)
retur... | class Mockrequests:
def __init__(self, ok=True, json_data=None):
self.ok = ok
self.json_data = json_data
self.get_method_called = False
def __call__(self, *args, **kwargs):
self.get_method_called = True
self.response = mock_response(json_data=self.json_data)
ret... |
# -*- coding: utf-8 -*-
class Solution:
def minCostToMoveChips(self, chips):
count_even, count_odd = 0, 0
for chip in chips:
if chip % 2 == 0:
count_even += 1
else:
count_odd += 1
return min(count_even, count_odd)
if __name__ == '_... | class Solution:
def min_cost_to_move_chips(self, chips):
(count_even, count_odd) = (0, 0)
for chip in chips:
if chip % 2 == 0:
count_even += 1
else:
count_odd += 1
return min(count_even, count_odd)
if __name__ == '__main__':
soluti... |
"""Module for user service exceptions"""
__all__ = [
'UserNotFoundException',
'UserIsExistsException',
]
class UserNotFoundException(Exception):
"""Indicates that user not found
Args:
message: Detailed message
"""
def __init__(self, message: str) -> None:
self.message = mess... | """Module for user service exceptions"""
__all__ = ['UserNotFoundException', 'UserIsExistsException']
class Usernotfoundexception(Exception):
"""Indicates that user not found
Args:
message: Detailed message
"""
def __init__(self, message: str) -> None:
self.message = message
class Us... |
def _copy_cmd(ctx, file_list, target_dir):
dest_list = []
if file_list == None or len(file_list) == 0:
return dest_list
shell_content = ""
batch_file_name = "%s-copy-files.bat" % (ctx.label.name)
bat = ctx.actions.declare_file(batch_file_name)
src_file_list = []
for (src_file, rela... | def _copy_cmd(ctx, file_list, target_dir):
dest_list = []
if file_list == None or len(file_list) == 0:
return dest_list
shell_content = ''
batch_file_name = '%s-copy-files.bat' % ctx.label.name
bat = ctx.actions.declare_file(batch_file_name)
src_file_list = []
for (src_file, relative... |
class Enum(object):
@classmethod
def parse(cls, value):
options = cls.options()
result = []
for k, v in options.items():
if type(v) is not int or v == 0:
continue
if value == 0 or (value & v) == v:
result.append(v)
retur... | class Enum(object):
@classmethod
def parse(cls, value):
options = cls.options()
result = []
for (k, v) in options.items():
if type(v) is not int or v == 0:
continue
if value == 0 or value & v == v:
result.append(v)
return r... |
class Model:
def __init__(self):
pass
class Optimizer:
def __init__(self):
pass
| class Model:
def __init__(self):
pass
class Optimizer:
def __init__(self):
pass |
currency = {
'GDP' : 1.3,
'EUR' : 1.08,
'USD' : 1.0,
'AUD' : 0.66,
'JPY' : 0.0090
}
while True:
intialcur = str(input('Please Enter the currency you want to convert from\n: ')).upper()
while True:
if intialcur in currency:
break
else:
intialcur = str(... | currency = {'GDP': 1.3, 'EUR': 1.08, 'USD': 1.0, 'AUD': 0.66, 'JPY': 0.009}
while True:
intialcur = str(input('Please Enter the currency you want to convert from\n: ')).upper()
while True:
if intialcur in currency:
break
else:
intialcur = str(input('Not in list. Please En... |
"""
Implementation of a specific learning rate scheduler for GANs.
"""
class DRS_LRScheduler:
"""
Learning rate scheduler for training GANs. Supports GAN specific LR scheduling
policies, such as the linear decay policy using in SN-GAN paper as based on the
original chainer implementation. However, one... | """
Implementation of a specific learning rate scheduler for GANs.
"""
class Drs_Lrscheduler:
"""
Learning rate scheduler for training GANs. Supports GAN specific LR scheduling
policies, such as the linear decay policy using in SN-GAN paper as based on the
original chainer implementation. However, one ... |
n, a, b = map(int, input().split())
ans = 0
for i in range(1, n+1):
str_i = str(i)
sum = 0
for j in range(len(str_i)):
sum += int(str_i[j])
if a <= sum <= b:
ans +=i
print(ans)
| (n, a, b) = map(int, input().split())
ans = 0
for i in range(1, n + 1):
str_i = str(i)
sum = 0
for j in range(len(str_i)):
sum += int(str_i[j])
if a <= sum <= b:
ans += i
print(ans) |
VERSION = "0.0.2"
VERSION_GUI = "0.0.2"
VERSION_CUI = "0.0.0"
VERSION_AUDIOCABLE = "0.0.2"
VERSION_ROUTE = "0.0.2"
VERSION_SETINGS = "0.0.1"
CALLBACK_AUDIOCABLE_SELECTED = None
CALLBACK_ROUTE_SELECTED = None
SETTINGS = None
CONFIGURATION = None
PATH_ROOT = ""
PATH_SETTINGS = "" | version = '0.0.2'
version_gui = '0.0.2'
version_cui = '0.0.0'
version_audiocable = '0.0.2'
version_route = '0.0.2'
version_setings = '0.0.1'
callback_audiocable_selected = None
callback_route_selected = None
settings = None
configuration = None
path_root = ''
path_settings = '' |
def xor_reverse(iterable):
lenght = len(iterable)
i = 0
while i < lenght // 2:
iterable[i] ^= iterable[lenght - i - 1]
iterable[lenght - i - 1] ^= iterable[i]
iterable[i] ^= iterable[lenght - i - 1]
i += 1
return iterable
| def xor_reverse(iterable):
lenght = len(iterable)
i = 0
while i < lenght // 2:
iterable[i] ^= iterable[lenght - i - 1]
iterable[lenght - i - 1] ^= iterable[i]
iterable[i] ^= iterable[lenght - i - 1]
i += 1
return iterable |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | def load_arguments(commands_loader, _):
with commands_loader.argument_context('apim api policy') as c:
c.argument('api_id', options_list=['--api-id', '-a'], help='API revision identifier. Must be unique in the current API Management service instance.')
c.argument('xml', options_list=['--xml-value', ... |
# Variables that contain the user credentials to access Twitter API.
ACCESS_TOKEN = "570634225-AnsM63tVCpI4yeFwpj6QfSJTwm3pUx6onf30fI2Z"
ACCESS_TOKEN_SECRET = "ykA5CW0lWpl3VDiIRqJ5rhJjsQc6fyt0pps22tLAywXUJ"
CONSUMER_KEY = "iRwp1I7vH0cBoWNIO5w0uxURN"
CONSUMER_SECRET = "5rA8XDisNbzwTueiCiZG7JXEZe5T4HRiwLbFjWMTWlyNoU35r4... | access_token = '570634225-AnsM63tVCpI4yeFwpj6QfSJTwm3pUx6onf30fI2Z'
access_token_secret = 'ykA5CW0lWpl3VDiIRqJ5rhJjsQc6fyt0pps22tLAywXUJ'
consumer_key = 'iRwp1I7vH0cBoWNIO5w0uxURN'
consumer_secret = '5rA8XDisNbzwTueiCiZG7JXEZe5T4HRiwLbFjWMTWlyNoU35r4' |
def split_data(input, output, validation_percentage=0.1):
num_sets = output.shape[0]
num_validation = int(num_sets * validation_percentage)
return (input[:-num_validation], output[:-num_validation]), (input[-num_validation:], output[-num_validation:])
| def split_data(input, output, validation_percentage=0.1):
num_sets = output.shape[0]
num_validation = int(num_sets * validation_percentage)
return ((input[:-num_validation], output[:-num_validation]), (input[-num_validation:], output[-num_validation:])) |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 1st solution
# O(n) time | O(1) space
profit = 0
start = prices[0]
end = start
for i, price in enumerate(prices):
if price >= end and i < len(prices) - 1:
end = price
... | class Solution:
def max_profit(self, prices: List[int]) -> int:
profit = 0
start = prices[0]
end = start
for (i, price) in enumerate(prices):
if price >= end and i < len(prices) - 1:
end = price
else:
if price >= end:
... |
class Stat:
def __init__(self):
self.sum = {}
self.sum_square = {}
self.count = {}
def add(self, key, value):
self.count[key] = self.count.get(key, 0) + 1
self.sum[key] = self.sum.get(key, 0.0) + value
self.sum_square[key] = self.sum_square.get(key, 0.0) + value... | class Stat:
def __init__(self):
self.sum = {}
self.sum_square = {}
self.count = {}
def add(self, key, value):
self.count[key] = self.count.get(key, 0) + 1
self.sum[key] = self.sum.get(key, 0.0) + value
self.sum_square[key] = self.sum_square.get(key, 0.0) + value... |
BUY = 1
SALE = 2
OrderType = [
(BUY, 'BUY'),
(SALE, 'SALE')
] | buy = 1
sale = 2
order_type = [(BUY, 'BUY'), (SALE, 'SALE')] |
# A function with Behavior That varies Over Time
# A function compound value have a body and a parent frame
# The parent frame contains the balance, the local state of the withdraw function
# Non-Local Assignment & Persistent Local State
# Work for python 3
def make_withdraw(balance):
""" Return a withdraw fun... | def make_withdraw(balance):
""" Return a withdraw function with a starting balance."""
def withdraw(amount):
nonlocal balance
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
return balance
def deposit(amount):
nonlocal balance... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.