content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Repository(object):
def byLocation(self, locationString): # pragma: no cover
"""Get the provenance for a file at the given location.
In the case of a dicom series, this returns the provenance for the
series.
Args:
locationString (str): Loc... | class Repository(object):
def by_location(self, locationString):
"""Get the provenance for a file at the given location.
In the case of a dicom series, this returns the provenance for the
series.
Args:
locationString (str): Location of the image file.
Return... |
"""
--- Day 20: Firewall Rules ---
You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the
corporate firewall only allows communication with certain external IP addresses.
You've retrieved the list of blocked IPs from the firewall, but the list seems to be ... | """
--- Day 20: Firewall Rules ---
You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the
corporate firewall only allows communication with certain external IP addresses.
You've retrieved the list of blocked IPs from the firewall, but the list seems to be ... |
# Get the starting fibonacci numbers
start1 = int(input("First fibonacci number: "))
start2 = int(input("Second fibonacci number: "))
# New line
print("")
fibonacci = [start1, start2]
for i in range(2, 102):
current_fibonacci = fibonacci[i - 1] + fibonacci[i - 2]
fibonacci.append(current_fibonacci)
# Print a... | start1 = int(input('First fibonacci number: '))
start2 = int(input('Second fibonacci number: '))
print('')
fibonacci = [start1, start2]
for i in range(2, 102):
current_fibonacci = fibonacci[i - 1] + fibonacci[i - 2]
fibonacci.append(current_fibonacci)
for val in fibonacci:
print(val)
input('\r\nPress enter ... |
m = 'John Smithfather'
a = m[:-6]
b = m[-6:]
print(b.title() + ": " + a)
print('AsDf'.lower(), 'AsDf'.upper()) | m = 'John Smithfather'
a = m[:-6]
b = m[-6:]
print(b.title() + ': ' + a)
print('AsDf'.lower(), 'AsDf'.upper()) |
num=int(input("Enter number:"))
if (num > 0):
print(num,"is a positive number")
else:
print(num,"is not a positive number")
| num = int(input('Enter number:'))
if num > 0:
print(num, 'is a positive number')
else:
print(num, 'is not a positive number') |
class _DoubleLinkedBase:
class _Node:
__slots__ = '_element', '_prev', '_next'
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def __init__(self):
self._header = self._Node(None, None, None)
... | class _Doublelinkedbase:
class _Node:
__slots__ = ('_element', '_prev', '_next')
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def __init__(self):
self._header = self._Node(None, None, None)
... |
expected_output = {
"tag": {
"VRF1": {
"hostname_db": {
"hostname": {
"7777.77ff.eeee": {"hostname": "R7", "level": 2},
"2222.22ff.4444": {"hostname": "R2", "local_router": True},
}
}
},
"test": {... | expected_output = {'tag': {'VRF1': {'hostname_db': {'hostname': {'7777.77ff.eeee': {'hostname': 'R7', 'level': 2}, '2222.22ff.4444': {'hostname': 'R2', 'local_router': True}}}}, 'test': {'hostname_db': {'hostname': {'9999.99ff.3333': {'hostname': 'R9', 'level': 2}, '8888.88ff.1111': {'hostname': 'R8', 'level': 2}, '777... |
def add_binary(a, b):
"""
Implement a function that adds two numbers together and
returns their sum in binary.
The conversion can be done before, or after the addition.
The binary number returned should be a string.
"""
return str(bin(a+b)[2:])
# TESTS
assert add_binary(1, 1) == "10"
asser... | def add_binary(a, b):
"""
Implement a function that adds two numbers together and
returns their sum in binary.
The conversion can be done before, or after the addition.
The binary number returned should be a string.
"""
return str(bin(a + b)[2:])
assert add_binary(1, 1) == '10'
assert add_bi... |
RUN_CREATE_DATA = {
"root_name": "agent",
"agent_name": "agent",
"component_spec": {
"components": {
"agent==f39000a113abf6d7fcd93f2eaabce4cab8873fb0": {
"class_name": "SB3PPOAgent",
"dependencies": {
"environment": (
... | run_create_data = {'root_name': 'agent', 'agent_name': 'agent', 'component_spec': {'components': {'agent==f39000a113abf6d7fcd93f2eaabce4cab8873fb0': {'class_name': 'SB3PPOAgent', 'dependencies': {'environment': 'environment==f39000a113abf6d7fcd93f2eaabce4cab8873fb0', 'tracker': 'tracker==f39000a113abf6d7fcd93f2eaabce4c... |
#from pydrive_functions import write_trees_csvs
"""
write_trees_csvs()
df = get_trees_dataframes()
df2 = get_image_ids(df, ids_file.images_ids)
df2.to_csv('result.csv')
""" | """
write_trees_csvs()
df = get_trees_dataframes()
df2 = get_image_ids(df, ids_file.images_ids)
df2.to_csv('result.csv')
""" |
def calculateSeat(line, numRows, numColumns):
def getSeatParameter(line, up, down, currentCharNum, numChars, minValue, maxValue):
if line[currentCharNum] == up:
if currentCharNum == numChars:
return maxValue
currentCharNum += 1
return getSeatParameter(line... | def calculate_seat(line, numRows, numColumns):
def get_seat_parameter(line, up, down, currentCharNum, numChars, minValue, maxValue):
if line[currentCharNum] == up:
if currentCharNum == numChars:
return maxValue
current_char_num += 1
return get_seat_parame... |
#Ex 1041 Coordenadas de um ponto 10/04/2020
x, y = map(float, input().split())
if x > 0 and y > 0:
print('Q1')
elif x < 0 and y > 0:
print('Q2')
if x > 0 and y < 0:
print('Q4')
elif x < 0 and y < 0:
print('Q3')
elif x == 0 and y == 0:
print('Origem')
| (x, y) = map(float, input().split())
if x > 0 and y > 0:
print('Q1')
elif x < 0 and y > 0:
print('Q2')
if x > 0 and y < 0:
print('Q4')
elif x < 0 and y < 0:
print('Q3')
elif x == 0 and y == 0:
print('Origem') |
N = 10
I = 60
CROSSBAR_FEEDBACK_DELAY = 75e-12
CROSSBAR_INPUT_DELAY = 95e-12
| n = 10
i = 60
crossbar_feedback_delay = 7.5e-11
crossbar_input_delay = 9.5e-11 |
def howdoyoudo():
global helvar
if helvar <= 2:
i01.mouth.speak("I'm fine thank you")
helvar += 1
elif helvar == 3:
i01.mouth.speak("you have already said that at least twice")
i01.moveArm("left",43,88,22,10)
i01.moveArm("right",20,90,30,10)
i01.moveHand("left",0,0,0,0,0,119)
i01.moveH... | def howdoyoudo():
global helvar
if helvar <= 2:
i01.mouth.speak("I'm fine thank you")
helvar += 1
elif helvar == 3:
i01.mouth.speak('you have already said that at least twice')
i01.moveArm('left', 43, 88, 22, 10)
i01.moveArm('right', 20, 90, 30, 10)
i01.moveHa... |
# flake8: noqa
# fmt: off
"""List of Valorant API available regions and endpoints."""
REGION_URL = {
"BR": "https://br.api.riotgames.com",
"EUN": "https://eun.api.riotgames.com",
"AP": "https://ap.api.riotgames.com",
"KR": "https://kr.api.riotgames.com",
"LATAM": "https://latam.api.riotgames.com",... | """List of Valorant API available regions and endpoints."""
region_url = {'BR': 'https://br.api.riotgames.com', 'EUN': 'https://eun.api.riotgames.com', 'AP': 'https://ap.api.riotgames.com', 'KR': 'https://kr.api.riotgames.com', 'LATAM': 'https://latam.api.riotgames.com', 'NA': 'https://na.api.riotgames.com'}
api_path =... |
levelsMap = [
#level 1-1
("g1","f1",[["ma1","ma3","ma5","b1","m1","e1","m1","b1","ma1","ma3","ma5"],
["ma2","ma4","ma6","b1","b1","b1","b1","b1","ma2","ma4","ma6"],
["b1","b1","b1","m1","b1","m1","b1","m1","b1","b1","b1"],
["m1","b1","b1","b1","b1","b1","b1","b1","b1","b1","m1... | levels_map = [('g1', 'f1', [['ma1', 'ma3', 'ma5', 'b1', 'm1', 'e1', 'm1', 'b1', 'ma1', 'ma3', 'ma5'], ['ma2', 'ma4', 'ma6', 'b1', 'b1', 'b1', 'b1', 'b1', 'ma2', 'ma4', 'ma6'], ['b1', 'b1', 'b1', 'm1', 'b1', 'm1', 'b1', 'm1', 'b1', 'b1', 'b1'], ['m1', 'b1', 'b1', 'b1', 'b1', 'b1', 'b1', 'b1', 'b1', 'b1', 'm1'], ['b1', '... |
#
# PySNMP MIB module S5-TCS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/S5-TCS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:35:57 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:... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint, constraints_union) ... |
STRING_51_CHARS = "SFOTYFUZTMDSOULXMKVFDOBQWNBAVGANMVLXQQZZQZQHBLJRZNY"
STRING_301_CHARS = (
"ZFOMVKXETILJKBZPVKOYAUPNYWWWUICNEVXVPWNAMGCNHDBRMATGPMUHUZHUJKFWWLXBQXVDNCGJHAPKEK"
"DZCXKBXEHWCWBYDIGNYXTOFWWNLPBTVIGTNQKIQDHUAHZPWQDKKCHERBYKLAUOOKJXJJLGOPSCRVEHCOAD"
"BFYKJTXHMPPYWQVXCVGNNSXLNIHVKTVMEOIRXQDPLHID... | string_51_chars = 'SFOTYFUZTMDSOULXMKVFDOBQWNBAVGANMVLXQQZZQZQHBLJRZNY'
string_301_chars = 'ZFOMVKXETILJKBZPVKOYAUPNYWWWUICNEVXVPWNAMGCNHDBRMATGPMUHUZHUJKFWWLXBQXVDNCGJHAPKEKDZCXKBXEHWCWBYDIGNYXTOFWWNLPBTVIGTNQKIQDHUAHZPWQDKKCHERBYKLAUOOKJXJJLGOPSCRVEHCOADBFYKJTXHMPPYWQVXCVGNNSXLNIHVKTVMEOIRXQDPLHIDZBAHUEDWXKXILEBOLILO... |
# You will be given series of strings until you receive an "end" command. Write a program that reverses strings and prints each pair on separate line in the format "{word} = {reversed word}".
while True:
word = input()
if word == 'end':
break
reversed_word = word[::-1]
print(f"{word} = {r... | while True:
word = input()
if word == 'end':
break
reversed_word = word[::-1]
print(f'{word} = {reversed_word}') |
name = "doxygen"
version = "1.8.18"
authors = [
"Dimitri van Heesch"
]
description = \
"""
Doxygen is the de facto standard tool for generating documentation from annotated C++ sources, but it also supports
other popular programming languages such as C, Objective-C, C#, PHP, Java, Python, IDL (Corba,... | name = 'doxygen'
version = '1.8.18'
authors = ['Dimitri van Heesch']
description = '\n Doxygen is the de facto standard tool for generating documentation from annotated C++ sources, but it also supports\n other popular programming languages such as C, Objective-C, C#, PHP, Java, Python, IDL (Corba, Microsoft, and... |
class Node():
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def tree_in(node_list):
list_in = input().split()
l = len(list_in)
node_list.append(Node(list_in[0]))
for i in range(1, l):
if list_in[i] == "Non... | class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def tree_in(node_list):
list_in = input().split()
l = len(list_in)
node_list.append(node(list_in[0]))
for i in range(1, l):
if list_in[i] == 'None'... |
for t in range(int(input())):
n,k,v=map(int,input().split())
a=list(map(int,input().split()))
s=0
for i in range(n):
s+=a[i]
x=(((n+k)*v)-s)/k
x=float(x)
if x>0:
if((x).is_integer()):
print(int(x))
else:
print(-1)
else:
print(-1) | for t in range(int(input())):
(n, k, v) = map(int, input().split())
a = list(map(int, input().split()))
s = 0
for i in range(n):
s += a[i]
x = ((n + k) * v - s) / k
x = float(x)
if x > 0:
if x.is_integer():
print(int(x))
else:
print(-1)
els... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def diameterOfBinaryTree(self, root):
self.ans = 1
def dfs(node):
if not node: return 0
l = dfs(node.left... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def diameter_of_binary_tree(self, root):
self.ans = 1
def dfs(node):
if not node:
return 0
l = dfs(node.left)
r =... |
#!/usr/bin/python
# Author: Michael Music
# Date: 8/1/2019
# Description: Coolplayer+ Buffer Overflow Exploit
# Exercise in BOFs following the securitysift guide
# Tested on Windows XP
# Notes:
# I will be assuming that EBX is the only register pointing to input buffer.
# Since EBX points to the very beginning of ... | exploit_string = ''
exploit_string += '\x83Ãd' * 3
exploit_string += 'ÿã'
exploit_string += 'A' * (260 - len(exploit_string))
exploit_string += 'S<\x87|'
exploit_string += '\x90' * 60
exploit_string += 'Ì' * 500
exploit_string += 'C' * (10000 - len(exploit_string))
out = 'crash.m3u'
text = open(out, 'w')
text.write(exp... |
"""Generate model benchmark source file using template.
"""
_TEMPLATE = "//src/cpp:models_benchmark.cc.template"
def _generate_models_benchmark_src_impl(ctx):
ctx.actions.expand_template(
template = ctx.file._template,
output = ctx.outputs.source_file,
substitutions = {
"{BENCH... | """Generate model benchmark source file using template.
"""
_template = '//src/cpp:models_benchmark.cc.template'
def _generate_models_benchmark_src_impl(ctx):
ctx.actions.expand_template(template=ctx.file._template, output=ctx.outputs.source_file, substitutions={'{BENCHMARK_NAME}': ctx.attr.benchmark_name, '{TFLIT... |
def is_true(value):
"""
Helper function for getting a bool form a query string.
"""
if hasattr(value, "lower"):
return value.lower() not in ("false", "0")
return bool(value)
| def is_true(value):
"""
Helper function for getting a bool form a query string.
"""
if hasattr(value, 'lower'):
return value.lower() not in ('false', '0')
return bool(value) |
#
# PySNMP MIB module EICON-MIB-TRACE (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EICON-MIB-TRACE
# Produced by pysmi-0.3.4 at Mon Apr 29 18:45:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_size_constraint, value_range_constraint) ... |
n=int(input())
dp=[[1]*3 for i in range(2)]
for i in range(1,n):
dp[i%2][0]=(dp[(i-1)%2][0]+dp[(i-1)%2][1]+dp[(i-1)%2][2])%9901
dp[i%2][1]=(dp[(i-1)%2][0]+dp[(i-1)%2][2])%9901
dp[i%2][2]=(dp[(i-1)%2][0]+dp[(i-1)%2][1])%9901
n-=1
print((dp[n%2][0]+dp[n%2][1]+dp[n%2][2])%9901) | n = int(input())
dp = [[1] * 3 for i in range(2)]
for i in range(1, n):
dp[i % 2][0] = (dp[(i - 1) % 2][0] + dp[(i - 1) % 2][1] + dp[(i - 1) % 2][2]) % 9901
dp[i % 2][1] = (dp[(i - 1) % 2][0] + dp[(i - 1) % 2][2]) % 9901
dp[i % 2][2] = (dp[(i - 1) % 2][0] + dp[(i - 1) % 2][1]) % 9901
n -= 1
print((dp[n % 2]... |
'''
The cost of a stock on each day is given in an array.
Find the max profit that you can make by buying and selling in those days.
Only 1 stock can be held at a time.
For example:
Array = {100, 180, 260, 310, 40, 535, 695}
The maximum profit can earned by buying on day 0, selling on day 3.
Again buy on day 4 and sel... | """
The cost of a stock on each day is given in an array.
Find the max profit that you can make by buying and selling in those days.
Only 1 stock can be held at a time.
For example:
Array = {100, 180, 260, 310, 40, 535, 695}
The maximum profit can earned by buying on day 0, selling on day 3.
Again buy on day 4 and sel... |
# data input
inp1 = input().split()
inp2 = input().split()
# data processing
code1 = inp1[0]
num_code1 = int(inp1[1])
unit_value1 = float(inp1[2])
code2 = inp2[0]
num_code2 = int(inp2[1])
unit_value2 = float(inp2[2])
price = num_code1 * unit_value1 + num_code2 * unit_value2
# data output
print('VALOR A PAGAR: R$',... | inp1 = input().split()
inp2 = input().split()
code1 = inp1[0]
num_code1 = int(inp1[1])
unit_value1 = float(inp1[2])
code2 = inp2[0]
num_code2 = int(inp2[1])
unit_value2 = float(inp2[2])
price = num_code1 * unit_value1 + num_code2 * unit_value2
print('VALOR A PAGAR: R$', '%.2f' % price) |
class BaseCloudController:
pass
| class Basecloudcontroller:
pass |
"""
Integration test settings
"""
DYNAMODB_HOST = 'http://localhost:8000' | """
Integration test settings
"""
dynamodb_host = 'http://localhost:8000' |
__import__("math", fromlist=[])
__import__("xml.sax.xmlreader")
result = "subpackage_2"
class PackageBSubpackage2Object_0:
pass
def dynamic_import_test(name: str):
__import__(name)
| __import__('math', fromlist=[])
__import__('xml.sax.xmlreader')
result = 'subpackage_2'
class Packagebsubpackage2Object_0:
pass
def dynamic_import_test(name: str):
__import__(name) |
def timeConversion(s):
ampm = s[-2:]
hr = s[:2]
if ampm == 'AM':
return s[:-2] if hr != '12' else '00' + s[2:-2]
return s[:-2] if hr == '12' else str(int(s[:2]) + 12) + s[2:-2]
if __name__ == '__main__':
s1 = '07:05:45PM'
assert timeConversion(s1) == '19:05:45'
s2 = '07:05:45AM'
... | def time_conversion(s):
ampm = s[-2:]
hr = s[:2]
if ampm == 'AM':
return s[:-2] if hr != '12' else '00' + s[2:-2]
return s[:-2] if hr == '12' else str(int(s[:2]) + 12) + s[2:-2]
if __name__ == '__main__':
s1 = '07:05:45PM'
assert time_conversion(s1) == '19:05:45'
s2 = '07:05:45AM'
... |
MAJOR = 0
MINOR = 2
RELEASE = 4
VERSION = '%d.%d.%d' % (MAJOR, MINOR, RELEASE)
def at_least_version(versionstring):
"""Is versionstring='X.Y.Z' at least the current version?"""
(major, minor, release) = versionstring.split('.')
return at_least_major_version(major) and at_least_minor_version(minor) and at_... | major = 0
minor = 2
release = 4
version = '%d.%d.%d' % (MAJOR, MINOR, RELEASE)
def at_least_version(versionstring):
"""Is versionstring='X.Y.Z' at least the current version?"""
(major, minor, release) = versionstring.split('.')
return at_least_major_version(major) and at_least_minor_version(minor) and at_l... |
def get_metrics(history):
plot_metrics = [
k for k in history.keys()
if k not in ['epoch', 'batches'] and not k.startswith('val_')
]
return plot_metrics
def get_metric_vs_epoch(history, metric, batches=True):
data = []
val_metric = f'val_{metric}'
for key in [metric, val_metric... | def get_metrics(history):
plot_metrics = [k for k in history.keys() if k not in ['epoch', 'batches'] and (not k.startswith('val_'))]
return plot_metrics
def get_metric_vs_epoch(history, metric, batches=True):
data = []
val_metric = f'val_{metric}'
for key in [metric, val_metric]:
if key in ... |
DEFAULT_JOB_CLASS = 'choreo.multirq.job.Job'
DEFAULT_QUEUE_CLASS = 'choreo.multirq.Queue'
DEFAULT_WORKER_CLASS = 'choreo.retry.RetryWorker'
DEFAULT_CONNECTION_CLASS = 'redis.StrictRedis'
DEFAULT_WORKER_TTL = 420
DEFAULT_RESULT_TTL = 500
| default_job_class = 'choreo.multirq.job.Job'
default_queue_class = 'choreo.multirq.Queue'
default_worker_class = 'choreo.retry.RetryWorker'
default_connection_class = 'redis.StrictRedis'
default_worker_ttl = 420
default_result_ttl = 500 |
#Aligam GiSAXS sample
#
def align_gisaxs_height_subh( rang = 0.3, point = 31 ,der=False ):
det_exposure_time(0.5)
sample_id(user_name='test', sample_name='test')
yield from bp.rel_scan([pil1M,pil1mroi1,pil1mroi2], piezo.y, -rang, rang, point)
ps(der=der)
... | def align_gisaxs_height_subh(rang=0.3, point=31, der=False):
det_exposure_time(0.5)
sample_id(user_name='test', sample_name='test')
yield from bp.rel_scan([pil1M, pil1mroi1, pil1mroi2], piezo.y, -rang, rang, point)
ps(der=der)
yield from bps.mv(piezo.y, ps.cen)
def align_gisaxs_th_subh(rang=0.3, po... |
# TODO: Give better variable names
# TODO: Make v3 and v4 optional arguments
def find(v1, v2, v3, v4):
return v1.index(v2, v3, v4)
| def find(v1, v2, v3, v4):
return v1.index(v2, v3, v4) |
# AUTHOR: prm1999
# Python3 Concept: Rotate the word in the list.
# GITHUB: https://github.com/prm1999
# Function
def rotate(arr, n):
n = len(arr)
i = 1
x = arr[n - 1]
for i in range(n - 1, 0, -1):
arr[i] = arr[i - 1]
arr[0] = x
return arr
#main
A = [1, 2, 3, 4, 5]
a=rotate(A,5)
... | def rotate(arr, n):
n = len(arr)
i = 1
x = arr[n - 1]
for i in range(n - 1, 0, -1):
arr[i] = arr[i - 1]
arr[0] = x
return arr
a = [1, 2, 3, 4, 5]
a = rotate(A, 5)
print(a) |
#
# PySNMP MIB module TERAWAVE-terasystem-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TERAWAVE-terasystem-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:16:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) ... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
#Filename: soreted_iter.py
colors = [ 'red', 'green', 'blue', 'yellow' ]
for color in sorted(colors):
print (color)
# >>> blue
# green
# red
# yellow
for color in sorted(colors, reverse=True):
print (color)
# >>> yellow
# red
# green
# blue
... | colors = ['red', 'green', 'blue', 'yellow']
for color in sorted(colors):
print(color)
for color in sorted(colors, reverse=True):
print(color)
def compare_length(c1, c2):
if len(c1) < len(c2):
return -1
if len(c1) > len(c2):
return 1
return 0
print(sorted(colors, key=len)) |
#Ejercicio 2
palabra=input ("Escribe una palabra y vamos a analizar si es polindroma o no: ")
p=len(palabra)
capicua=""
while p>0:
p=p-1
capicua=capicua+palabra[p] #Concateno las letras una por una y las guardo
if palabra ==capicua:
print("La palabra escogida es polindroma")
if palabra!= capicua:
... | palabra = input('Escribe una palabra y vamos a analizar si es polindroma o no: ')
p = len(palabra)
capicua = ''
while p > 0:
p = p - 1
capicua = capicua + palabra[p]
if palabra == capicua:
print('La palabra escogida es polindroma')
if palabra != capicua:
print('La palabra escogida no es polindroma') |
print("Hello World")
# The basics
name = "joey"
age = 27
print(name + str(age))
testList = [0,1,2]
testList.append(3)
testList.append(4)
for member in testList:
print(member)
for index,member in enumerate(testList):
print("Index: " + str(index) + " item: " + str(member))
# List Combining
list1 = [1,3,5,7... | print('Hello World')
name = 'joey'
age = 27
print(name + str(age))
test_list = [0, 1, 2]
testList.append(3)
testList.append(4)
for member in testList:
print(member)
for (index, member) in enumerate(testList):
print('Index: ' + str(index) + ' item: ' + str(member))
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
print... |
days = int(input())
type_of_room = input()
feedback = input()
price = 0
nights = days - 1
if type_of_room == 'room for one person':
price = 18
cost = nights * price
elif type_of_room == 'apartment':
price = 25
cost = nights * price
if days < 10:
cost = cost - (cost * 30 /100)
elif 10 <... | days = int(input())
type_of_room = input()
feedback = input()
price = 0
nights = days - 1
if type_of_room == 'room for one person':
price = 18
cost = nights * price
elif type_of_room == 'apartment':
price = 25
cost = nights * price
if days < 10:
cost = cost - cost * 30 / 100
elif 10 <= d... |
class A(object):
def go(self):
print("go A go!")
def stop(self):
print("stop A stop!")
def pause(self):
raise Exception("Not Implemented")
class B(A):
def go(self):
super(B, self).go()
print("go B go!")
class C(A):
def go(self):
super(C, self).go()
... | class A(object):
def go(self):
print('go A go!')
def stop(self):
print('stop A stop!')
def pause(self):
raise exception('Not Implemented')
class B(A):
def go(self):
super(B, self).go()
print('go B go!')
class C(A):
def go(self):
super(C, self).g... |
#
# @lc app=leetcode id=902 lang=python3
#
# [902] Numbers At Most N Given Digit Set
#
# @lc code=start
class Solution:
def atMostNGivenDigitSet(self, D: List[str], N: int) -> int:
s = str(N)
n = len(s)
ans = sum(len(D) ** i for i in range(1, n))
for i, c in enumerate(s):
... | class Solution:
def at_most_n_given_digit_set(self, D: List[str], N: int) -> int:
s = str(N)
n = len(s)
ans = sum((len(D) ** i for i in range(1, n)))
for (i, c) in enumerate(s):
ans += len(D) ** (n - i - 1) * sum((d < c for d in D))
if c not in D:
... |
fields = ["one", "two", "three", "four", "five", "six"]
together = ":".join(fields)
print(together) # one:two:three:four:five:six
together = ':'.join(fields)
print(together) # one:two and three:four:five:six
mixed = ' -=<> '.join(fields)
print(mixed) # one -=<> two and three -=<> four -=<> five -=<> six
another = '... | fields = ['one', 'two', 'three', 'four', 'five', 'six']
together = ':'.join(fields)
print(together)
together = ':'.join(fields)
print(together)
mixed = ' -=<> '.join(fields)
print(mixed)
another = ''.join(fields)
print(another) |
# vim: set fileencoding=<utf-8> :
'''Counting k-mers'''
__version__ = '0.1.0'
| """Counting k-mers"""
__version__ = '0.1.0' |
# Registry Class
# CMD
# Refer this in Detectron2
class Registry:
def __init__(self, name):
self._name = name
self._obj_map = {}
def _do_register(self, name, obj):
assert (name not in self._obj_map), "The object named: {} was already registered in {} registry! ".format(name, self.... | class Registry:
def __init__(self, name):
self._name = name
self._obj_map = {}
def _do_register(self, name, obj):
assert name not in self._obj_map, 'The object named: {} was already registered in {} registry! '.format(name, self._name)
self._obj_map[name] = obj
def registe... |
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
res = []
for i in range(len(s)-1,-1,-1):
res.append(s[i])
return ''.join(res)
| class Solution(object):
def reverse_string(self, s):
"""
:type s: str
:rtype: str
"""
res = []
for i in range(len(s) - 1, -1, -1):
res.append(s[i])
return ''.join(res) |
# Use the file name mbox-short.txt as the file name
file_name = input("Enter file name: ")
fh = open(file_name)
count = 0
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
pos = line.find('0')
total += float(line[pos:pos + 6])
count += 1
average = total... | file_name = input('Enter file name: ')
fh = open(file_name)
count = 0
total = 0
for line in fh:
if not line.startswith('X-DSPAM-Confidence:'):
continue
pos = line.find('0')
total += float(line[pos:pos + 6])
count += 1
average = total / count
print('Average spam confidence:', average) |
print("hello")
o= input ("input operation ")
x= int(input ("x = "))
y= int(input ("y = "))
if o == "+":
print (x+y)
elif o == "-":
print (x-y)
elif o == "*" :
print (x*y)
elif o == "/" :
if y==0 :
print ("it's a simple calc, don't be too smart")
else :
print (x/y)
elif o == "//" :... | print('hello')
o = input('input operation ')
x = int(input('x = '))
y = int(input('y = '))
if o == '+':
print(x + y)
elif o == '-':
print(x - y)
elif o == '*':
print(x * y)
elif o == '/':
if y == 0:
print("it's a simple calc, don't be too smart")
else:
print(x / y)
elif o == '//':
... |
wsgi_app = "tabby.wsgi:application"
workers = 4
preload_app = True
sendfile = True
max_requests = 1000
max_requests_jitter = 100
| wsgi_app = 'tabby.wsgi:application'
workers = 4
preload_app = True
sendfile = True
max_requests = 1000
max_requests_jitter = 100 |
class ScramException(Exception):
pass
class BadChallengeException(ScramException):
pass
class ExtraChallengeException(ScramException):
pass
class ServerScramError(ScramException):
pass
class BadSuccessException(ScramException):
pass
class NotAuthorizedException(ScramException):
pass
| class Scramexception(Exception):
pass
class Badchallengeexception(ScramException):
pass
class Extrachallengeexception(ScramException):
pass
class Serverscramerror(ScramException):
pass
class Badsuccessexception(ScramException):
pass
class Notauthorizedexception(ScramException):
pass |
# pylint: disable=missing-function-docstring, missing-module-docstring/
a = [i*j for i in range(1,3) for j in range(1,4) for k in range(i,j)]
n = 5
a = [i*j for i in range(1,n) for j in range(1,4) for k in range(i,j)]
| a = [i * j for i in range(1, 3) for j in range(1, 4) for k in range(i, j)]
n = 5
a = [i * j for i in range(1, n) for j in range(1, 4) for k in range(i, j)] |
"""
Syntax of while Loop
while test_condition:
body of while
"""
#Print first 5 natural numbers using while loop
count = 1
while count <= 5:
print(count)
count += 1
| """
Syntax of while Loop
while test_condition:
body of while
"""
count = 1
while count <= 5:
print(count)
count += 1 |
def get_lucky_numbers(self):
return self.execute("select lucky_number, count(lucky_number) as occurences, sum(case when outcome < 1 then 1 else 0 end) as negative_outcomes, sum(case when outcome > 1 then 1 else 0 end) as successful_outcomes from wager_history where lucky_number <> 0 group by lucky_number")
def ... | def get_lucky_numbers(self):
return self.execute('select lucky_number, count(lucky_number) as occurences, sum(case when outcome < 1 then 1 else 0 end) as negative_outcomes, sum(case when outcome > 1 then 1 else 0 end) as successful_outcomes from wager_history where lucky_number <> 0 group by lucky_number')
def ge... |
# This is not a real module, it's simply an introductory text.
"""
The Blender Game Engine Python API Reference
============================================
See U{release notes<http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/2.49/Game_Engine>} for updates, changes and new functionality in the Game Engine Pyt... | """
The Blender Game Engine Python API Reference
============================================
See U{release notes<http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/2.49/Game_Engine>} for updates, changes and new functionality in the Game Engine Python API.
Blender Game Engine Modules:
-----------------------... |
# Apr 21
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
result = 0
heap = []
count = 0
for start, end in intervals:
heapq.heappush(heap, [start, 1])
... | class Solution(object):
def min_meeting_rooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
result = 0
heap = []
count = 0
for (start, end) in intervals:
heapq.heappush(heap, [start, 1])
heapq.heappush(... |
class PlayerCharacter:
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("run")
return "done"
player1 = PlayerCharacter("Cindy", 50)
player2 = PlayerCharacter("Tom", 20)
print(player1.name)
print(player1.age)
print(player2.name)
print(... | class Playercharacter:
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print('run')
return 'done'
player1 = player_character('Cindy', 50)
player2 = player_character('Tom', 20)
print(player1.name)
print(player1.age)
print(player2.name)
print(player2... |
def Reverse(a):
return ' '.join(map(str, a.split()[::-1])) if not a.isspace() else a
if __name__ == '__main__':
print(Reverse(" "))
| def reverse(a):
return ' '.join(map(str, a.split()[::-1])) if not a.isspace() else a
if __name__ == '__main__':
print(reverse(' ')) |
DATA_DIR = "data/captcha_images_v2"
BATCH_SIZE = 8
IMAGE_WIDTH = 300
IMAGE_HEIGHT = 75
NUM_WORKERS = 8
EPOCHS = 200
DEVICE = "cuda"
| data_dir = 'data/captcha_images_v2'
batch_size = 8
image_width = 300
image_height = 75
num_workers = 8
epochs = 200
device = 'cuda' |
with open('dataset_3363_3.txt') as inf, open('MostPopularWord.txt','w') as ouf:
maxc = 0
s = inf.read().lower().strip().split()
s.sort()
for word in s:
counter = s.count(word)
if counter > maxc:
maxc = counter
result_word = word
ouf.write(result_word +' ' + st... | with open('dataset_3363_3.txt') as inf, open('MostPopularWord.txt', 'w') as ouf:
maxc = 0
s = inf.read().lower().strip().split()
s.sort()
for word in s:
counter = s.count(word)
if counter > maxc:
maxc = counter
result_word = word
ouf.write(result_word + ' ' + ... |
def mpii_get_sequence_info(subject_id, sequence):
switcher = {
"1 1": [6416,25],
"1 2": [12430,50],
"2 1": [6502,25],
"2 2": [6081,25],
"3 1": [12488,50],
"3 2": [12283,50],
"4 1": [6171,25],
"4 2": [6675,25],
"5 1": [12820,50],
"5 2... | def mpii_get_sequence_info(subject_id, sequence):
switcher = {'1 1': [6416, 25], '1 2': [12430, 50], '2 1': [6502, 25], '2 2': [6081, 25], '3 1': [12488, 50], '3 2': [12283, 50], '4 1': [6171, 25], '4 2': [6675, 25], '5 1': [12820, 50], '5 2': [12312, 50], '6 1': [6188, 25], '6 2': [6145, 25], '7 1': [6239, 25], '7... |
# by Kami Bigdely
# Extract Class
class FoodInfo:
def __init__(self, name, prep_time, is_veggie, food_type, cuisine, ingredients, recipe):
self.name = name
self.prep_time = prep_time
self.is_veggie = is_veggie
self.food_type = food_type
self.cuisine = cuisine
se... | class Foodinfo:
def __init__(self, name, prep_time, is_veggie, food_type, cuisine, ingredients, recipe):
self.name = name
self.prep_time = prep_time
self.is_veggie = is_veggie
self.food_type = food_type
self.cuisine = cuisine
self.ingredients = ingredients
se... |
class Solution:
def isHappy(self, n: int) -> bool:
seen = {}
while True:
if n in seen:
break
counter = 0
for i in range(len(str(n))):
counter += int(str(n)[i]) ** 2
seen[n] = 1
n = counter
counte... | class Solution:
def is_happy(self, n: int) -> bool:
seen = {}
while True:
if n in seen:
break
counter = 0
for i in range(len(str(n))):
counter += int(str(n)[i]) ** 2
seen[n] = 1
n = counter
count... |
def christmas_tree(n, h):
tree = ['*', '*', '***']
start = '*****'
for i in range(n):
tree.append(start)
for j in range(1, h):
tree.append('*' * (len(tree[-1]) + 2))
start += '**'
foot = '*' * h if h % 2 == 1 else '*' * h + '*'
tree += [foot for i in range(n)]
... | def christmas_tree(n, h):
tree = ['*', '*', '***']
start = '*****'
for i in range(n):
tree.append(start)
for j in range(1, h):
tree.append('*' * (len(tree[-1]) + 2))
start += '**'
foot = '*' * h if h % 2 == 1 else '*' * h + '*'
tree += [foot for i in range(n)]
... |
def turn_on_lights(lights, begin, end):
for x in range(begin[0], end[0]+1):
for y in range(begin[1], end[1]+1):
lights[x][y] = True
def turn_off_lights(lights, begin, end):
for x in range(begin[0], end[0]+1):
for y in range(begin[1], end[1]+1):
lights[x][y] = False
def ... | def turn_on_lights(lights, begin, end):
for x in range(begin[0], end[0] + 1):
for y in range(begin[1], end[1] + 1):
lights[x][y] = True
def turn_off_lights(lights, begin, end):
for x in range(begin[0], end[0] + 1):
for y in range(begin[1], end[1] + 1):
lights[x][y] = Fal... |
#!/usr/bin/env python
''' WIP
def main():
script_main('you-get', any_download, any_download_playlist)
if __name__ == "__main__":
main()
'''
| """ WIP
def main():
script_main('you-get', any_download, any_download_playlist)
if __name__ == "__main__":
main()
""" |
'''
@Date: 2019-09-10 20:36:03
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors: ywyz
@LastEditTime: 2019-09-10 20:41:39
'''
for number in range(1, 7):
spacenumber = 6 - number
while spacenumber >= 0:
print(" ", end=" ")
spacenumber -= 1
n = number
while ... | """
@Date: 2019-09-10 20:36:03
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors: ywyz
@LastEditTime: 2019-09-10 20:41:39
"""
for number in range(1, 7):
spacenumber = 6 - number
while spacenumber >= 0:
print(' ', end=' ')
spacenumber -= 1
n = number
while ... |
numeros = []
for n in range(1,101):
numeros.append(n)
print(numeros) | numeros = []
for n in range(1, 101):
numeros.append(n)
print(numeros) |
#!/usr/bin/env python
def organism(con):
con.executescript(
'''
CREATE TABLE Organisms
(
abbr TEXT PRIMARY KEY,
name TEXT
);
''')
def species(con):
con.executescript(
'''
CREATE TABLE Genes
(
gid TEXT PRIMARY KEY,
name TEXT
);
CREATE TABLE GeneEntrezGeneIds
(
gid TE... | def organism(con):
con.executescript('\nCREATE TABLE Organisms\n(\n abbr TEXT PRIMARY KEY,\n name TEXT\n);\n ')
def species(con):
con.executescript('\nCREATE TABLE Genes\n(\n gid TEXT PRIMARY KEY,\n name TEXT\n);\nCREATE TABLE GeneEntrezGeneIds\n(\n gid TEXT,\n entrez_gene_id TEXT,\n ... |
"""
Module Docstring
Docstrings: http://www.python.org/dev/peps/pep-0257/
"""
__author__ = 'Yannic Schneider (v@vendetta.ch)'
__copyright__ = 'Copyright (c) 20xx Yannic Schneider'
__license__ = 'WTFPL'
__vcs_id__ = '$Id$'
__version__ = '0.1' #Versioning: http://www.python.org/dev/peps/pep-0386/
#
## Code goes here.
#... | """
Module Docstring
Docstrings: http://www.python.org/dev/peps/pep-0257/
"""
__author__ = 'Yannic Schneider (v@vendetta.ch)'
__copyright__ = 'Copyright (c) 20xx Yannic Schneider'
__license__ = 'WTFPL'
__vcs_id__ = '$Id$'
__version__ = '0.1'
def read_file(path):
"""Read a file and return as string object"""
re... |
class DoubleExpression:
def __init__(self, value):
self.value = value
def accept(self, visitor):
visitor.visit(self)
| class Doubleexpression:
def __init__(self, value):
self.value = value
def accept(self, visitor):
visitor.visit(self) |
# Time: O(m + n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
curA, curB = headA, headB
while cu... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def get_intersection_node(self, headA, headB):
(cur_a, cur_b) = (headA, headB)
while curA != curB:
cur_a = curA.next if curA else headB
cur_b = curB.nex... |
#############################################
## hassioNode commandWord map
#############################################
print('Load hassioNode masterBedroom commandWord map')
wordMap = {
"Media": {
"Louder": [
{"id": 0, "type": "call_service", "domain": "media_player", "service": "volum... | print('Load hassioNode masterBedroom commandWord map')
word_map = {'Media': {'Louder': [{'id': 0, 'type': 'call_service', 'domain': 'media_player', 'service': 'volume_up', 'service_data': {'entity_id': 'media_player.master_bedroom'}}], 'Softer': [{'type': 'call_service', 'domain': 'media_player', 'service': 'volume_dow... |
"""Utility functions for the testing module.
Dribia 2021/08/04, irene <irene@dribia.com>
"""
| """Utility functions for the testing module.
Dribia 2021/08/04, irene <irene@dribia.com>
""" |
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def inc(x):
return x + 1
def test_add():
assert add(1, 2) == 3
def test_subtract():
assert subtract(2, 1) == 1
def test_inc():
assert inc(1) == 2
| def add(x, y):
return x + y
def subtract(x, y):
return x - y
def inc(x):
return x + 1
def test_add():
assert add(1, 2) == 3
def test_subtract():
assert subtract(2, 1) == 1
def test_inc():
assert inc(1) == 2 |
class lrd:
def __init__(self, waiting_time, start_lr, min_lr, factor):
self.waiting_time = waiting_time
self.start_lr = start_lr
self.min_lr = min_lr
self.factor = factor
self.min_value = 10000000000000000000
self.waited = 0
self.actual_lr = self.start_lr
... | class Lrd:
def __init__(self, waiting_time, start_lr, min_lr, factor):
self.waiting_time = waiting_time
self.start_lr = start_lr
self.min_lr = min_lr
self.factor = factor
self.min_value = 10000000000000000000
self.waited = 0
self.actual_lr = self.start_lr
... |
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
MAX_INT = (1 << 31) - 1
MIN_INT = -MAX_INT - 1
if x == MIN_INT: return 0
res = 0
p = x if x >= 0 else -x
while p != 0:
digit = p % 10
... | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
max_int = (1 << 31) - 1
min_int = -MAX_INT - 1
if x == MIN_INT:
return 0
res = 0
p = x if x >= 0 else -x
while p != 0:
digit = p % 1... |
#!/usr/bin/env python3
def check_palindrome(num):
num = str(num)
for i in range(0, int((len(num) + 1) / 2)):
if num[i] != num[-i]:
return False
return True
def simple_palindrome(num):
num = str(num)
return num == num[::-1]
biggest = 0
for i in range(100, 999)... | def check_palindrome(num):
num = str(num)
for i in range(0, int((len(num) + 1) / 2)):
if num[i] != num[-i]:
return False
return True
def simple_palindrome(num):
num = str(num)
return num == num[::-1]
biggest = 0
for i in range(100, 999):
for j in range(100, 999):
tem... |
"""
Reverse encoding functions.
Reverse encoding is the simplest of encoding methods. It just reverses order of
text characters.
"""
def encode(text: str) -> str:
"""
Reverse order of given text characters.
:param text: Text to reverse.
:return: Reversed text.
"""
reversed_text = "".join(cha... | """
Reverse encoding functions.
Reverse encoding is the simplest of encoding methods. It just reverses order of
text characters.
"""
def encode(text: str) -> str:
"""
Reverse order of given text characters.
:param text: Text to reverse.
:return: Reversed text.
"""
reversed_text = ''.join((cha... |
"""
Semantic adversarial Examples
"""
__all__ = ['semantic', 'Semantic']
def semantic(x, center:bool=True, max_val:float=1.):
"""
Semantic adversarial examples.
https://arxiv.org/abs/1703.06857
Note: data must either be centered (so that the negative image can be
made by simple negation) or must be in t... | """
Semantic adversarial Examples
"""
__all__ = ['semantic', 'Semantic']
def semantic(x, center: bool=True, max_val: float=1.0):
"""
Semantic adversarial examples.
https://arxiv.org/abs/1703.06857
Note: data must either be centered (so that the negative image can be
made by simple negation) or must be ... |
class Solution(object):
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
if name == typed:
return True
for c in name:
try:
index = typed.index(c)
ty... | class Solution(object):
def is_long_pressed_name(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
if name == typed:
return True
for c in name:
try:
index = typed.index(c)
typed =... |
def consume_rec(xs, fn, n=0):
if n <= 0:
fn(xs)
else:
for x in xs:
consume_rec(x, fn, n=n - 1)
| def consume_rec(xs, fn, n=0):
if n <= 0:
fn(xs)
else:
for x in xs:
consume_rec(x, fn, n=n - 1) |
# Load the double pendulum from Universal Robot Description Format
#tree = RigidBodyTree(FindResource("double_pendulum/double_pendulum.urdf"), FloatingBaseType.kFixed)
#tree = RigidBodyTree(FindResource("../../notebooks/three_link.urdf"), FloatingBaseType.kFixed)
#tree = RigidBodyTree(FindResource("../../drake/examples... | tree = rigid_body_tree(find_resource('../../notebooks/three_link.urdf'), FloatingBaseType.kFixed)
box_depth = 100
pi = math.pi
r = np.identity(3)
slope = 0
R[0, 0] = math.cos(slope)
R[0, 2] = math.sin(slope)
R[2, 0] = -math.sin(slope)
R[2, 2] = math.cos(slope)
x = isometry3(rotation=R, translation=[0, 0, -5.0])
color =... |
"""
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading ... | """
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading ... |
def info_file_parser(filename, verbose=False):
results = {}
infile = open(filename,'r')
for iline, line in enumerate(infile):
if line[0]=='#': continue
lines = line.split()
if len(lines)<2 : continue
if lines[0][0]=='#': continue
infotype = lines[0]
infotype... | def info_file_parser(filename, verbose=False):
results = {}
infile = open(filename, 'r')
for (iline, line) in enumerate(infile):
if line[0] == '#':
continue
lines = line.split()
if len(lines) < 2:
continue
if lines[0][0] == '#':
continue
... |
class AlreadyExists(Exception):
pass
class NoRights(Exception):
pass
class EntryNotFound(Exception):
pass
class LoginFailed(Exception):
pass
# input validation
""" Input validation """
class InvalidInput(Exception):
pass
| class Alreadyexists(Exception):
pass
class Norights(Exception):
pass
class Entrynotfound(Exception):
pass
class Loginfailed(Exception):
pass
' Input validation '
class Invalidinput(Exception):
pass |
class Country():
def __init__(self, name='Unspecified', population=None, size_kmsq=None): #keyword argument.
self.name = name
self.population = population
self.size_kmsq = size_kmsq
def __str__(self):
return self.name
if __name__ == '__main__':
usa = Country(name='United ... | class Country:
def __init__(self, name='Unspecified', population=None, size_kmsq=None):
self.name = name
self.population = population
self.size_kmsq = size_kmsq
def __str__(self):
return self.name
if __name__ == '__main__':
usa = country(name='United States of America', siz... |
def test_owner_register_success():
assert True
def test_owner_register_failure():
assert True
def test_worker_register_success():
assert True
def test_worker_register_failure():
assert True
def test_login_success():
assert True
def test_login_failure():
assert True
| def test_owner_register_success():
assert True
def test_owner_register_failure():
assert True
def test_worker_register_success():
assert True
def test_worker_register_failure():
assert True
def test_login_success():
assert True
def test_login_failure():
assert True |
class MoveTurn(object):
def __init__(self):
self.end = False
self.again = False
self.move = None
if __name__ == "__main__":
Print('This class has been checked and works as expected.') | class Moveturn(object):
def __init__(self):
self.end = False
self.again = False
self.move = None
if __name__ == '__main__':
print('This class has been checked and works as expected.') |
#
# Created on Fri Apr 10 2020
#
# Title: Leetcode - Min Stack
#
# Author: Vatsal Mistry
# Web: mistryvatsal.github.io
#
class MinStack:
def __init__(self):
# Creating 2 stacks, stack : original data; currMinimum : to hold current minimum upon each push
self.stack = list()
self.currMinimum ... | class Minstack:
def __init__(self):
self.stack = list()
self.currMinimum = list()
def push(self, x: int) -> None:
if len(self.stack) == 0 and len(self.currMinimum) == 0:
self.stack.append(x)
self.currMinimum.append(x)
else:
self.currMinimum.a... |
def insertionSort(aList):
first = 0
last = len(aList)-1
for CurrentPointer in range(first+1, last+1):
CurrentValue = aList[CurrentPointer]
Pointer = CurrentPointer - 1
while aList[Pointer] > CurrentValue and Pointer >= 0:
aList[Pointer+1] = aList[Pointer]
... | def insertion_sort(aList):
first = 0
last = len(aList) - 1
for current_pointer in range(first + 1, last + 1):
current_value = aList[CurrentPointer]
pointer = CurrentPointer - 1
while aList[Pointer] > CurrentValue and Pointer >= 0:
aList[Pointer + 1] = aList[Pointer]
... |
# 8.10) Implement a function to fill a matrix with a new color given a point and the matrix
def paint_fill(matrix, y, x, new_color):
# print(x, y)
len_x = len(matrix[0]) - 1
len_y = len(matrix[0][0]) - 1
if y < 0 or y > len_y or x < 0 or x > len_x:
return
if matrix[y][x] == new_color:
... | def paint_fill(matrix, y, x, new_color):
len_x = len(matrix[0]) - 1
len_y = len(matrix[0][0]) - 1
if y < 0 or y > len_y or x < 0 or (x > len_x):
return
if matrix[y][x] == new_color:
return
matrix[y][x] = new_color
paint_fill(matrix, y - 1, x, new_color)
paint_fill(matrix, y +... |
class Solution(object):
def sortedSquares(self, nums):
"""
:type A: List[int]
:rtype: List[int]
"""
squares = [0 for i in range(len(nums))]
# index iterator for squares array
i = len(squares) - 1
left = 0
right = len(nums) - 1
... | class Solution(object):
def sorted_squares(self, nums):
"""
:type A: List[int]
:rtype: List[int]
"""
squares = [0 for i in range(len(nums))]
i = len(squares) - 1
left = 0
right = len(nums) - 1
while left <= right:
if abs(nums[left]... |
fname = 'mydata.txt'
with open(fname, 'r') as md:
for line in md:
print(line)
# continue on with other code
fname = 'mydata2.txt'
with open(fname, 'w') as wr:
for i in range (20):
wr.write(str(i) + '\n')
| fname = 'mydata.txt'
with open(fname, 'r') as md:
for line in md:
print(line)
fname = 'mydata2.txt'
with open(fname, 'w') as wr:
for i in range(20):
wr.write(str(i) + '\n') |
class DeviceSwitch(object):
def __init__(self, device_data):
self.__device_data = device_data
def switch(self, key, value):
switcher = {
"identifier": self.__identifier,
"language": self.__language,
"timezone": self.__timezone,
"game_version": sel... | class Deviceswitch(object):
def __init__(self, device_data):
self.__device_data = device_data
def switch(self, key, value):
switcher = {'identifier': self.__identifier, 'language': self.__language, 'timezone': self.__timezone, 'game_version': self.__game_version, 'device_model': self.__device_... |
class PID(object):
def __init__(self, kp, ki, kd):
self.kp = kp
self.ki = ki
self.kd = kd
self.error_int = 0
self.error_prev = None
def control(self, error):
self.error_int += error
if self.error_prev is None:
self.error_prev = error
e... | class Pid(object):
def __init__(self, kp, ki, kd):
self.kp = kp
self.ki = ki
self.kd = kd
self.error_int = 0
self.error_prev = None
def control(self, error):
self.error_int += error
if self.error_prev is None:
self.error_prev = error
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.