content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
data = input()
courses = {}
while ":" in data:
student_name, id, course_name = data.split(":")
if course_name not in courses:
courses[course_name] = {}
courses[course_name][id] = student_name
data = input()
searched_course = data
searched_course_name_as_list = searched_course.split("_")
se... | data = input()
courses = {}
while ':' in data:
(student_name, id, course_name) = data.split(':')
if course_name not in courses:
courses[course_name] = {}
courses[course_name][id] = student_name
data = input()
searched_course = data
searched_course_name_as_list = searched_course.split('_')
search... |
nums = list()
while True:
nStr = input('Enter a number: ')
try:
if nStr == 'done':
break
n = float(nStr)
nums.append(n)
except:
print('Invalid input')
continue
print('Maximum: ',max(nums))
print('Minimum: ',min(nums)) | nums = list()
while True:
n_str = input('Enter a number: ')
try:
if nStr == 'done':
break
n = float(nStr)
nums.append(n)
except:
print('Invalid input')
continue
print('Maximum: ', max(nums))
print('Minimum: ', min(nums)) |
# to run this, add code from experiments_HSCC2021.py
def time_series_pulse():
path = Path(__file__).parent.parent / "data" / "real_data" / "datasets" / "basic_data"
filename1 = path / "pulse1-1.csv"
filename2 = path / "pulse1-2.csv"
filename3 = path / "pulse1-3.csv"
f1 = load_time_series(filename1,... | def time_series_pulse():
path = path(__file__).parent.parent / 'data' / 'real_data' / 'datasets' / 'basic_data'
filename1 = path / 'pulse1-1.csv'
filename2 = path / 'pulse1-2.csv'
filename3 = path / 'pulse1-3.csv'
f1 = load_time_series(filename1, 1)
f2 = load_time_series(filename2, 1)
f3 = l... |
#Day 1.3 Exercise!!
#First way I thought to do it without help
name = input("What is your name? ")
print(len(name))
#Way I found to do it from searching google
print(len(input("What is your name? "))) | name = input('What is your name? ')
print(len(name))
print(len(input('What is your name? '))) |
#-- THIS LINE SHOULD BE THE FIRST LINE OF YOUR SUBMISSION! --#
def tally(costs, discounts, rebate_factor):
cost = sum(costs)
discount = sum(discounts)
pre = (cost - discount) * rebate_factor
if pre < 0:
return 0
else:
return round(pre, 2)
#-- THIS LINE SHOULD BE THE LAST LINE OF ... | def tally(costs, discounts, rebate_factor):
cost = sum(costs)
discount = sum(discounts)
pre = (cost - discount) * rebate_factor
if pre < 0:
return 0
else:
return round(pre, 2)
assert tally([10, 24], [3, 4, 3], 0.3) == 7.2
assert tally([10], [20], 0.1) == 0 |
def soma (a,b):
print(f'A = {a} e B = {b}')
s=a+b
print(f'A soma A + B ={s}')
#Programa Principal
soma(4,5)
| def soma(a, b):
print(f'A = {a} e B = {b}')
s = a + b
print(f'A soma A + B ={s}')
soma(4, 5) |
def GCD(a,b):
if b == 0:
return a
else:
return GCD(b, a%b)
a = int(input())
b = int(input())
print(a*b//(GCD(a,b)))
| def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
a = int(input())
b = int(input())
print(a * b // gcd(a, b)) |
# -*- coding:utf-8 -*-
"""
"""
__date__ = "14/12/2017"
__author__ = "zhaojm"
| """
"""
__date__ = '14/12/2017'
__author__ = 'zhaojm' |
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '10/28/2020 4:52 PM'
# import re
#
#
# def format_qs_score(score_str):
# """
# help you generate a qs score
# 1 - 100 : 5
# 141-200 : 4
# =100: 4
# N/A 3
# :param score_str:
# :return:
# """
# score = 3
# if... | __author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '10/28/2020 4:52 PM' |
def Linear_Search(Test_arr, val):
index = 0
for i in range(len(Test_arr)):
if val > Test_arr[i]:
index = i+1
return index
def Insertion_Sort(Test_arr):
for i in range(1, len(Test_arr)):
val = Test_arr[i]
j = Linear_Search(Test_arr[:i], val)
Test_arr.pop(i)
... | def linear__search(Test_arr, val):
index = 0
for i in range(len(Test_arr)):
if val > Test_arr[i]:
index = i + 1
return index
def insertion__sort(Test_arr):
for i in range(1, len(Test_arr)):
val = Test_arr[i]
j = linear__search(Test_arr[:i], val)
Test_arr.pop(... |
class Wrapper(object):
wrapper_classes = {}
@classmethod
def wrap(cls, obj):
return cls(obj)
def __init__(self, wrapped):
self.__dict__['wrapped'] = wrapped
def __getattr__(self, name):
return getattr(self.wrapped, name)
def __setattr__(self, name, value):
set... | class Wrapper(object):
wrapper_classes = {}
@classmethod
def wrap(cls, obj):
return cls(obj)
def __init__(self, wrapped):
self.__dict__['wrapped'] = wrapped
def __getattr__(self, name):
return getattr(self.wrapped, name)
def __setattr__(self, name, value):
set... |
height = int(input())
for i in range(1,height+1) :
for j in range(1, i+1):
m = i*j
if(m <= 9):
print("",m,end = " ")
else:
print(m,end = " ")
print()
# Sample Input :- 5
# Output :-
# 1
# 2 4
# 3 6 9
# 4 8 12 16
# 5 10 15 20 25
| height = int(input())
for i in range(1, height + 1):
for j in range(1, i + 1):
m = i * j
if m <= 9:
print('', m, end=' ')
else:
print(m, end=' ')
print() |
"""WWUCS Bot module."""
__all__ = [
"__author__",
"__email__",
"__version__",
]
__author__ = "Reilly Tucker Siemens"
__email__ = "reilly@tuckersiemens.com"
__version__ = "0.1.0"
| """WWUCS Bot module."""
__all__ = ['__author__', '__email__', '__version__']
__author__ = 'Reilly Tucker Siemens'
__email__ = 'reilly@tuckersiemens.com'
__version__ = '0.1.0' |
"""
=========== What is Matter Parameters ===================
"""
#tups = [(125.0, 1.0), (125.0, 1.5), (125.0, 2.0), (125.0, 2.5), (125.0, 3.0), (150.0, 1.0), (150.0, 1.5), (150.0, 2.0), (150.0, 2.5), (150.0, 3.0), (175.0, 1.0), (175.0, 1.5), (175.0, 2.0), (175.0, 2.5), (175.0, 3.0), (200.0, 1.0), (200.0, 1.5), (200.0,... | """
=========== What is Matter Parameters ===================
"""
'\n=========== DUC Data ==========\n' |
x = 2
print(x)
# multiple assignment
a, b, c, d = (1, 2, 5, 9)
print(a, b, c, d)
print(type(str(a)))
| x = 2
print(x)
(a, b, c, d) = (1, 2, 5, 9)
print(a, b, c, d)
print(type(str(a))) |
# OpenWeatherMap API Key
weather_api_key = "ae41fcf95db0d612b74e2b509abe9684"
# Google API Key
g_key = "AIzaSyCuF1rT6NscWq62bcBm0tZM7hKlaeWfONQ" | weather_api_key = 'ae41fcf95db0d612b74e2b509abe9684'
g_key = 'AIzaSyCuF1rT6NscWq62bcBm0tZM7hKlaeWfONQ' |
"""File for holding the different verb forms for all of the verbs in the Total
English book series."""
verb_forms = {
'become' :
{
'normal' : 'become',
'present' : ['become','becomes'],
'past' : 'became',
'past participle' : 'become',
'gerund' : 'becoming',
},
'be':
{
'n... | """File for holding the different verb forms for all of the verbs in the Total
English book series."""
verb_forms = {'become': {'normal': 'become', 'present': ['become', 'becomes'], 'past': 'became', 'past participle': 'become', 'gerund': 'becoming'}, 'be': {'normal': 'be', 'present': ['am', 'is', 'are'], 'past': ['was... |
"""Role testing files using testinfra"""
def test_config_directory(host):
"""Check config directory"""
f = host.file("/etc/influxdb")
assert f.is_directory
assert f.user == "influxdb"
assert f.group == "root"
assert f.mode == 0o775
def test_data_directory(host):
"""Check data directory""... | """Role testing files using testinfra"""
def test_config_directory(host):
"""Check config directory"""
f = host.file('/etc/influxdb')
assert f.is_directory
assert f.user == 'influxdb'
assert f.group == 'root'
assert f.mode == 509
def test_data_directory(host):
"""Check data directory"""
... |
def apply(con, target_language="E"):
dict_field_desc = {}
try:
df = con.prepare_and_execute_query("DD03T", ["DDLANGUAGE", "FIELDNAME", "DDTEXT"], " WHERE DDLANGUAGE = '"+target_language+"'")
stream = df.to_dict("records")
for el in stream:
dict_field_desc[el["FIELDNAME"]] = e... | def apply(con, target_language='E'):
dict_field_desc = {}
try:
df = con.prepare_and_execute_query('DD03T', ['DDLANGUAGE', 'FIELDNAME', 'DDTEXT'], " WHERE DDLANGUAGE = '" + target_language + "'")
stream = df.to_dict('records')
for el in stream:
dict_field_desc[el['FIELDNAME']]... |
#AFTER PREPROCESSING AND TARGETS DEFINITION
newdataset.describe()
LET_IS.value_counts()
LET_IS.value_counts().plot(kind='bar', color='c')
Y_unica.value_counts()
Y_unica.value_counts().plot(kind='bar', color='c')
ZSN.value_counts().plot(kind='bar', color='c')
Survive.value_counts().plot(kind='bar', color='c')
| newdataset.describe()
LET_IS.value_counts()
LET_IS.value_counts().plot(kind='bar', color='c')
Y_unica.value_counts()
Y_unica.value_counts().plot(kind='bar', color='c')
ZSN.value_counts().plot(kind='bar', color='c')
Survive.value_counts().plot(kind='bar', color='c') |
def binarySearch(inputArray, searchElement):
minIndex = -1
maxIndex = len(inputArray)
while minIndex < maxIndex - 1:
currentIndex = (minIndex + maxIndex) // 2
currentElement = inputArray[currentIndex]
if currentElement < searchElement:
minIndex = currentIndex
... | def binary_search(inputArray, searchElement):
min_index = -1
max_index = len(inputArray)
while minIndex < maxIndex - 1:
current_index = (minIndex + maxIndex) // 2
current_element = inputArray[currentIndex]
if currentElement < searchElement:
min_index = currentIndex
... |
d_soldiers = []
class Soldier:
def __init__(self, id, name, team):
self.id = id
self.name = name
self.team = team
self.x = 0
self.y = 0
self.xVelo = 0
self.yVelo = 0
self.kills = 0
self.deaths = 0
self.alive = 'true'
self.driving = 'false'
self.gun = 0
self.ammo = 0
self.reloading = 'fa... | d_soldiers = []
class Soldier:
def __init__(self, id, name, team):
self.id = id
self.name = name
self.team = team
self.x = 0
self.y = 0
self.xVelo = 0
self.yVelo = 0
self.kills = 0
self.deaths = 0
self.alive = 'true'
self.driv... |
#from http://rosettacode.org/wiki/Greatest_subsequential_sum#Python
#pythran export maxsum(int list)
#pythran export maxsumseq(int list)
#pythran export maxsumit(int list)
#runas maxsum([0, 1, 0])
#runas maxsumseq([-1, 2, -1, 3, -1])
#runas maxsumit([-1, 1, 2, -5, -6])
def maxsum(sequence):
"""Return maximum sum."... | def maxsum(sequence):
"""Return maximum sum."""
(maxsofar, maxendinghere) = (0, 0)
for x in sequence:
maxendinghere = max(maxendinghere + x, 0)
maxsofar = max(maxsofar, maxendinghere)
return maxsofar
def maxsumseq(sequence):
(start, end, sum_start) = (-1, -1, -1)
(maxsum_, sum_)... |
def task_clean_junk():
"""Remove junk file"""
return {
'actions': ['rm -rdf $(find . | grep pycache)'],
'clean': True,
}
| def task_clean_junk():
"""Remove junk file"""
return {'actions': ['rm -rdf $(find . | grep pycache)'], 'clean': True} |
def gfg(x,l = []):
for i in range(x):
l.append(i*i)
print(l)
gfg(2)
gfg(3,[3,2,1])
gfg(3)
| def gfg(x, l=[]):
for i in range(x):
l.append(i * i)
print(l)
gfg(2)
gfg(3, [3, 2, 1])
gfg(3) |
"""Module help_info."""
__author__ = 'Joan A. Pinol (japinol)'
class HelpInfo:
"""Manages information used for help purposes."""
def print_help_keys(self):
print(' F1: \t show a help screen while playing the game'
' t: \t stats on/off\n'
' L_Ctrl + R_Alt + g... | """Module help_info."""
__author__ = 'Joan A. Pinol (japinol)'
class Helpinfo:
"""Manages information used for help purposes."""
def print_help_keys(self):
print(' F1: \t show a help screen while playing the game t: \t stats on/off\n L_Ctrl + R_Alt + g: grid\n p: \t pause\n ESC: exit game\n ^... |
def format_sql(schedule, table):
for week, schedule in schedule.items():
print(f"UPDATE {table} SET `block`=0, `week`={week} WHERE `name`='{schedule.leader}';")
for block, staffs in schedule.staffs.items():
for staff in staffs:
print(f"UPDATE {table} SET `block`={block}, ... | def format_sql(schedule, table):
for (week, schedule) in schedule.items():
print(f"UPDATE {table} SET `block`=0, `week`={week} WHERE `name`='{schedule.leader}';")
for (block, staffs) in schedule.staffs.items():
for staff in staffs:
print(f"UPDATE {table} SET `block`={bloc... |
class Node(object):
# XXX: legacy code support
kind = property(lambda self: self.__class__)
def _iterChildren(self):
for name in self.childAttrNames:
yield (name, getattr(self, name))
return
children = property(_iterChildren)
def dump(self, stream, indent=0):
... | class Node(object):
kind = property(lambda self: self.__class__)
def _iter_children(self):
for name in self.childAttrNames:
yield (name, getattr(self, name))
return
children = property(_iterChildren)
def dump(self, stream, indent=0):
for (attr, child) in self.childr... |
friendly_camera_mapping = {
"GM1913": "Oneplus 7 Pro",
"FC3170": "Mavic Air 2",
# An analogue scanner in FilmNeverDie
"SP500": "Canon AE-1 Program"
}
| friendly_camera_mapping = {'GM1913': 'Oneplus 7 Pro', 'FC3170': 'Mavic Air 2', 'SP500': 'Canon AE-1 Program'} |
# Defutils.py -- Contains parsing functions for definition files.
# Produces an organized list of tokens in the file.
def parse(filename):
f=open(filename, "r")
contents=f.read()
f.close()
# Tokenize the file:
#contents=contents.replace('\t', '\n')
lines=contents.splitlines()
outList=[]
... | def parse(filename):
f = open(filename, 'r')
contents = f.read()
f.close()
lines = contents.splitlines()
out_list = []
for l in lines:
if l[len(l) - 1] == ':':
outList.append([l.rstrip(':')])
elif l != '':
outList[len(outList) - 1].append(l)
return out... |
class Solution:
# @param s, a string
# @param wordDict, a set<string>
# @return a string[]
def wordBreak(self, s, wordDict):
n = len(s)
res = []
chars = ''.join(wordDict)
for i in xrange(n):
if s[i] not in chars:
return res
lw = s[-1]
... | class Solution:
def word_break(self, s, wordDict):
n = len(s)
res = []
chars = ''.join(wordDict)
for i in xrange(n):
if s[i] not in chars:
return res
lw = s[-1]
lw_end = False
for word in wordDict:
if word[-1] == lw:
... |
# -*- coding:utf-8 -*-
class BaseProvider(object):
@staticmethod
def loads(link_url):
raise NotImplementedError("Implemetion required.")
@staticmethod
def dumps(conf):
raise NotImplementedError("Implemetion required.")
| class Baseprovider(object):
@staticmethod
def loads(link_url):
raise not_implemented_error('Implemetion required.')
@staticmethod
def dumps(conf):
raise not_implemented_error('Implemetion required.') |
session.forget()
def get(args):
if args[0].startswith('__'):
return None
try:
obj = globals(), get(args[0])
for k in range(1, len(args)):
obj = getattr(obj, args[k])
return obj
except:
return None
def vars():
"""the running controller function!"""
... | session.forget()
def get(args):
if args[0].startswith('__'):
return None
try:
obj = (globals(), get(args[0]))
for k in range(1, len(args)):
obj = getattr(obj, args[k])
return obj
except:
return None
def vars():
"""the running controller function!"""
... |
# https://codegolf.stackexchange.com/a/11480
multiplication = []
for i in range(10):
multiplication.append(i * (i + 1))
for x in multiplication:
print(x) | multiplication = []
for i in range(10):
multiplication.append(i * (i + 1))
for x in multiplication:
print(x) |
"""
PSET-7
Part 2: Triggers (PhraseTriggers)
At this point, you have no way of writing a trigger that matches on
"New York City" -- the only triggers you know how to write would be
a trigger that would fire on "New" AND "York" AND "City" -- which
also fires on the phrase "New students at York University love the
c... | """
PSET-7
Part 2: Triggers (PhraseTriggers)
At this point, you have no way of writing a trigger that matches on
"New York City" -- the only triggers you know how to write would be
a trigger that would fire on "New" AND "York" AND "City" -- which
also fires on the phrase "New students at York University love the
c... |
# flake8: noqa
# errmsg.h
CR_ERROR_FIRST = 2000
CR_UNKNOWN_ERROR = 2000
CR_SOCKET_CREATE_ERROR = 2001
CR_CONNECTION_ERROR = 2002
CR_CONN_HOST_ERROR = 2003
CR_IPSOCK_ERROR = 2004
CR_UNKNOWN_HOST = 2005
CR_SERVER_GONE_ERROR = 2006
CR_VERSION_ERROR = 2007
CR_OUT_OF_MEMORY = 2008
CR_WRONG_HOST_INFO = 2009
CR_LOCALHOST_... | cr_error_first = 2000
cr_unknown_error = 2000
cr_socket_create_error = 2001
cr_connection_error = 2002
cr_conn_host_error = 2003
cr_ipsock_error = 2004
cr_unknown_host = 2005
cr_server_gone_error = 2006
cr_version_error = 2007
cr_out_of_memory = 2008
cr_wrong_host_info = 2009
cr_localhost_connection = 2010
cr_tcp_conne... |
# -*- coding: utf-8 -*-
class HTTP:
BAD_REQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
METHOD_NOT_ALLOWED = 405
CONFLICT = 409
UNSUPPORTED_MEDIA_TYPE = 415
| class Http:
bad_request = 400
unauthorized = 401
forbidden = 403
not_found = 404
method_not_allowed = 405
conflict = 409
unsupported_media_type = 415 |
"""EnvSpec class."""
class EnvSpec:
"""EnvSpec class.
Args:
observation_space (akro.Space): The observation space of the env.
action_space (akro.Space): The action space of the env.
"""
def __init__(self, observation_space, action_space):
self.observation_space = observation... | """EnvSpec class."""
class Envspec:
"""EnvSpec class.
Args:
observation_space (akro.Space): The observation space of the env.
action_space (akro.Space): The action space of the env.
"""
def __init__(self, observation_space, action_space):
self.observation_space = observation_... |
#
# PySNMP MIB module CISCO-DIAMETER-BASE-PROTOCOL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DIAMETER-BASE-PROTOCOL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:54:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, constraints_intersection, single_value_constraint) ... |
cantidad= input("Cuantas personas van a cenar?")
cant = int(cantidad)
print(cant)
if cant > 8:
print("Lo siento, tendran que esperar")
else:
print("La mesa esta lista")
| cantidad = input('Cuantas personas van a cenar?')
cant = int(cantidad)
print(cant)
if cant > 8:
print('Lo siento, tendran que esperar')
else:
print('La mesa esta lista') |
def parse_cookie(query: str) -> dict:
res = {}
if query:
data = query.split(';')
for i in data:
if '=' in i:
res[i.split('=')[0]] = '='.join(i.split('=')[1:])
return res
if __name__ == '__main__':
assert parse_cookie('name=Dima;') == {'name': 'Dima'}
as... | def parse_cookie(query: str) -> dict:
res = {}
if query:
data = query.split(';')
for i in data:
if '=' in i:
res[i.split('=')[0]] = '='.join(i.split('=')[1:])
return res
if __name__ == '__main__':
assert parse_cookie('name=Dima;') == {'name': 'Dima'}
asser... |
dbConfig = {
"user": "root",
"password": "123567l098",
"host": "localhost",
"database": "trackMe_dev"
} | db_config = {'user': 'root', 'password': '123567l098', 'host': 'localhost', 'database': 'trackMe_dev'} |
def pol_V(offset=None):
yield from mv(m1_simple_fbk,0)
cur_mono_e = pgm.en.user_readback.value
yield from mv(epu1.table,6) # 4 = 3rd harmonic; 6 = "testing V" 1st harmonic
if offset is not None:
yield from mv(epu1.offset,offset)
yield from mv(epu1.phase,28.5)
yield from mv(pgm.en,cur_mon... | def pol_v(offset=None):
yield from mv(m1_simple_fbk, 0)
cur_mono_e = pgm.en.user_readback.value
yield from mv(epu1.table, 6)
if offset is not None:
yield from mv(epu1.offset, offset)
yield from mv(epu1.phase, 28.5)
yield from mv(pgm.en, cur_mono_e + 1)
yield from mv(pgm.en, cur_mono_... |
COGNITO = "Cognito"
SERVERLESS_REPO = "ServerlessRepo"
MODE = "Mode"
XRAY = "XRay"
LAYERS = "Layers"
HTTP_API = "HttpApi"
IOT = "IoT"
CODE_DEPLOY = "CodeDeploy"
ARM = "ARM"
GATEWAY_RESPONSES = "GatewayResponses"
MSK = "MSK"
KMS = "KMS"
CWE_CWS_DLQ = "CweCwsDlq"
CODE_SIGN = "CodeSign"
MQ = "MQ"
USAGE_PLANS = "UsagePlans... | cognito = 'Cognito'
serverless_repo = 'ServerlessRepo'
mode = 'Mode'
xray = 'XRay'
layers = 'Layers'
http_api = 'HttpApi'
iot = 'IoT'
code_deploy = 'CodeDeploy'
arm = 'ARM'
gateway_responses = 'GatewayResponses'
msk = 'MSK'
kms = 'KMS'
cwe_cws_dlq = 'CweCwsDlq'
code_sign = 'CodeSign'
mq = 'MQ'
usage_plans = 'UsagePlans... |
EDGE = '101'
MIDDLE = '01010'
CODES = {
'A': (
'0001101', '0011001', '0010011', '0111101', '0100011', '0110001',
'0101111', '0111011', '0110111', '0001011'
),
'B': (
'0100111', '0110011', '0011011', '0100001', '0011101', '0111001',
'0000101', '0010001', '0001001', '0010111'
... | edge = '101'
middle = '01010'
codes = {'A': ('0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011'), 'B': ('0100111', '0110011', '0011011', '0100001', '0011101', '0111001', '0000101', '0010001', '0001001', '0010111'), 'C': ('1110010', '1100110', '1101100', '1000010... |
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Peter Sprygada <psprygada@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = r'''
options:
provider:
descriptio... | class Moduledocfragment(object):
documentation = '\noptions:\n provider:\n description:\n - A dict object containing connection details.\n type: dict\n suboptions:\n host:\n description:\n - Specifies the DNS host name or address for connecting to the remote\n instance... |
class Display():
def __init__(self, width, height):
self.width = width
self.height = height
def getSize(self):
return (self.width, self.height)
| class Display:
def __init__(self, width, height):
self.width = width
self.height = height
def get_size(self):
return (self.width, self.height) |
# O(n ** 2)
def bubble_sort(slist, asc=True):
need_exchanges = False
for iteration in range(len(slist))[:: -1]:
for j in range(iteration):
if asc:
if slist[j] > slist[j + 1]:
need_exchanges = True
slist[j], slist[j + 1] = slist[j + 1], ... | def bubble_sort(slist, asc=True):
need_exchanges = False
for iteration in range(len(slist))[::-1]:
for j in range(iteration):
if asc:
if slist[j] > slist[j + 1]:
need_exchanges = True
(slist[j], slist[j + 1]) = (slist[j + 1], slist[j])
... |
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
cycle = 2*(numRows-1)
if numRows == 1: cycle = 1
map = []
for i in range(numRows):
map.append('')
for j ... | class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
cycle = 2 * (numRows - 1)
if numRows == 1:
cycle = 1
map = []
for i in range(numRows):
map.append('')
fo... |
class Solution:
def maxLength(self, arr) -> int:
def helper(word):
temp=[]
temp[:0]=word
res=set()
for w in temp:
if w not in res:
res.add(w)
else:
return None
return res
... | class Solution:
def max_length(self, arr) -> int:
def helper(word):
temp = []
temp[:0] = word
res = set()
for w in temp:
if w not in res:
res.add(w)
else:
return None
return ... |
class Node(object):
def __init__(self, name):
self.name = name;
self.adjacencyList = [];
self.visited = False;
self.predecessor = None;
class BreadthFirstSearch(object):
def bfs(self, startNode):
queue = [];
queue.append(startNode);
startNode.visited = True;
# BFS -> queue ... | class Node(object):
def __init__(self, name):
self.name = name
self.adjacencyList = []
self.visited = False
self.predecessor = None
class Breadthfirstsearch(object):
def bfs(self, startNode):
queue = []
queue.append(startNode)
startNode.visited = True
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 15 11:31:06 2021
@author: a77510jm
"""
| """
Created on Thu Apr 15 11:31:06 2021
@author: a77510jm
""" |
###############################################################
#
# This function is... INSUFFICIENT. It was developed as an
# illustration of EDA lessons in the 2021 class. It's quick and
# works well.
#
# Want a higher grade version of me? Then try pandas-profiling:
# https://github.com/pandas-profiling/pandas-... | def insufficient_but_starting_eda(df, cat_vars_list=None):
"""
Parameters
----------
df : DATAFRAME
cat_vars_list : LIST, optional
A list of strings containing variable names in the dataframe
for variables where you want to see the number of unique values
and the 10 most... |
"""
Simple math operating functions for unit test
"""
def add(a, b):
"""
Adding to parameters and return result
:param a:
:param b:
:return:
"""
return a + b
def minus(a, b):
"""
subtraction
:param a:
:param b:
:return:
"""
return a - b
def multi(a, b):
... | """
Simple math operating functions for unit test
"""
def add(a, b):
"""
Adding to parameters and return result
:param a:
:param b:
:return:
"""
return a + b
def minus(a, b):
"""
subtraction
:param a:
:param b:
:return:
"""
return a - b
def multi(a, b):
"""... |
"""
flags.py
. should be renamed helpers...
. This file is scheduled for deletion
"""
"""
valid accessory tags:
"any_tag": {"code": "code_insert_as_string"} # execute arbitrary code to construct this key.
"dialect": csv.excel_tab # dialect of the file, default = csv, set this to use tsv. or sniffer
"skip_lines": num... | """
flags.py
. should be renamed helpers...
. This file is scheduled for deletion
"""
'\nvalid accessory tags:\n\n"any_tag": {"code": "code_insert_as_string"} # execute arbitrary code to construct this key.\n"dialect": csv.excel_tab # dialect of the file, default = csv, set this to use tsv. or sniffer\n"skip_lines": n... |
def get(isamAppliance, check_mode=False, force=False):
"""
Retrieve an overview of updates and licensing information
"""
return isamAppliance.invoke_get("Retrieve an overview of updates and licensing information",
"/updates/overview")
def get_licensing_info(isamAppl... | def get(isamAppliance, check_mode=False, force=False):
"""
Retrieve an overview of updates and licensing information
"""
return isamAppliance.invoke_get('Retrieve an overview of updates and licensing information', '/updates/overview')
def get_licensing_info(isamAppliance, check_mode=False, force=False)... |
"""Top-level package for etherscan-py."""
__author__ = """Julian Koh"""
__email__ = 'juliankohtx@gmail.com'
__version__ = '0.1.0'
| """Top-level package for etherscan-py."""
__author__ = 'Julian Koh'
__email__ = 'juliankohtx@gmail.com'
__version__ = '0.1.0' |
# UC10 - Evaluate price
#
# User U exists and has valid account
# We create two Users, User1_UC10, User2_UC10 and one new gasStation GasStationUC10
#
# Registered on a 1920x1080p, Google Chrome 100% zoom
### SETUP
#User1
click("1590678880209.png")
click("1590678953637.png")
wait(2)
type("1... | click('1590678880209.png')
click('1590678953637.png')
wait(2)
type('1590829373120.png', 'User1_UC10' + Key.TAB + 'user1uc10@polito.it' + Key.TAB + 'user1')
click('1590679157604.png')
click('1590788841790.png')
wait(2)
click('1590678880209.png')
wait(2)
click('1590678953637.png')
wait(2)
type('1590829373120.png', 'User2... |
self.description = "Install a package ('any' architecture)"
p = pmpkg("dummy")
p.files = ["bin/dummy",
"usr/man/man1/dummy.1"]
p.arch = 'any'
self.addpkg(p)
self.option["Architecture"] = ['auto']
self.args = "-U %s" % p.filename()
self.addrule("PACMAN_RETCODE=0")
self.addrule("PKG_EXIST=dummy")
for f in ... | self.description = "Install a package ('any' architecture)"
p = pmpkg('dummy')
p.files = ['bin/dummy', 'usr/man/man1/dummy.1']
p.arch = 'any'
self.addpkg(p)
self.option['Architecture'] = ['auto']
self.args = '-U %s' % p.filename()
self.addrule('PACMAN_RETCODE=0')
self.addrule('PKG_EXIST=dummy')
for f in p.files:
se... |
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Implement a stack that has the following methods:
push(val), which pushes an element onto the stack
pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it sh... | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Implement a stack that has the following methods:
push(val), which pushes an element onto the stack
pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it sh... |
x:[int] = None
x = []
print(x[0])
| x: [int] = None
x = []
print(x[0]) |
def remove_duplicates(lst):
new = []
for x in lst:
if x not in new:
new.append(x)
return new
| def remove_duplicates(lst):
new = []
for x in lst:
if x not in new:
new.append(x)
return new |
class Config:
# helps to store settings for an experiment.
def __init__(self, _experiments_folder_path='experiments', _dataset_name='dataset', _column_names='unknown',
_types={1:'integer', 2:'string', 3:'float', 4:'boolean', 5:'gender', 6:'unknown', 7:'date-iso-8601', 8:'date-eu', 9:'date-non-s... | class Config:
def __init__(self, _experiments_folder_path='experiments', _dataset_name='dataset', _column_names='unknown', _types={1: 'integer', 2: 'string', 3: 'float', 4: 'boolean', 5: 'gender', 6: 'unknown', 7: 'date-iso-8601', 8: 'date-eu', 9: 'date-non-std-subtype', 10: 'date-non-std', 11: 'positive integer',... |
data = (
'Lun ', # 0x00
'Kua ', # 0x01
'Ling ', # 0x02
'Bei ', # 0x03
'Lu ', # 0x04
'Li ', # 0x05
'Qiang ', # 0x06
'Pou ', # 0x07
'Juan ', # 0x08
'Min ', # 0x09
'Zui ', # 0x0a
'Peng ', # 0x0b
'An ', # 0x0c
'Pi ', # 0x0d
'Xian ', # 0x0e
'Ya ', # 0x0f
'Zhui ', # 0x10
'Le... | data = ('Lun ', 'Kua ', 'Ling ', 'Bei ', 'Lu ', 'Li ', 'Qiang ', 'Pou ', 'Juan ', 'Min ', 'Zui ', 'Peng ', 'An ', 'Pi ', 'Xian ', 'Ya ', 'Zhui ', 'Lei ', 'A ', 'Kong ', 'Ta ', 'Kun ', 'Du ', 'Wei ', 'Chui ', 'Zi ', 'Zheng ', 'Ben ', 'Nie ', 'Cong ', 'Qun ', 'Tan ', 'Ding ', 'Qi ', 'Qian ', 'Zhuo ', 'Qi ', 'Yu ', 'Jin '... |
def three_sum(nums):
"""
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
:param nums: list[int]
:return: list[list[int]]
"""
if len(nums) < 3:
return []
nums.sort()
... | def three_sum(nums):
"""
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
:param nums: list[int]
:return: list[list[int]]
"""
if len(nums) < 3:
return []
nums.sort()
... |
class Allergies(object):
def __init__(self, score):
pass
def allergic_to(self, item):
pass
@property
def lst(self):
pass
| class Allergies(object):
def __init__(self, score):
pass
def allergic_to(self, item):
pass
@property
def lst(self):
pass |
#
# PySNMP MIB module CISCO-IETF-PW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IETF-PW-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:43:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) ... |
_base_ = [
'../_base_/models/fpn_r50.py', '../_base_/datasets/onaho.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
model = dict(decode_head=dict(num_classes=2))
| _base_ = ['../_base_/models/fpn_r50.py', '../_base_/datasets/onaho.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py']
model = dict(decode_head=dict(num_classes=2)) |
def get_default_convnet_setting():
net_width, net_depth, net_act, net_norm, net_pooling = 128, 3, 'relu', 'instancenorm', 'avgpooling'
return net_width, net_depth, net_act, net_norm, net_pooling
def get_loops(ipc):
# Get the two hyper-parameters of outer-loop and inner-loop.
# The following values are ... | def get_default_convnet_setting():
(net_width, net_depth, net_act, net_norm, net_pooling) = (128, 3, 'relu', 'instancenorm', 'avgpooling')
return (net_width, net_depth, net_act, net_norm, net_pooling)
def get_loops(ipc):
if ipc == 1:
(outer_loop, inner_loop) = (1, 1)
elif ipc == 10:
(ou... |
"""
Space : O(1)
Time : O(n)
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
start, dp = 10**10, 0
for i in prices:
print(start)
start = min(start, i)
dp = max(dp, i-start)
return dp
| """
Space : O(1)
Time : O(n)
"""
class Solution:
def max_profit(self, prices: List[int]) -> int:
(start, dp) = (10 ** 10, 0)
for i in prices:
print(start)
start = min(start, i)
dp = max(dp, i - start)
return dp |
# node to capture and communicate game status
# written by Russell on 5/18
class Game_state():
node_weight = 1
# node_bias = 1 # not going to use this for now, but may need it later
list_of_moves = []
def __init__(self, node_list):
self.node_list = node_list
def num_moves(self):
... | class Game_State:
node_weight = 1
list_of_moves = []
def __init__(self, node_list):
self.node_list = node_list
def num_moves(self):
moves = 0
for i in range(len(self.node_list)):
if self.node_list[i].cell_contains() != '':
moves += 1
return m... |
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) <= 1:
... | class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) <= 1:
return intervals
intervals.sort(key=lambda x: x.start)
new_intervals = [intervals[0]]
for i in range(1, len(... |
class myIntSynthProvider(object):
def __init__(self, valobj, dict):
self.valobj = valobj
self.val = self.valobj.GetChildMemberWithName("theValue")
def num_children(self):
return 0
def get_child_at_index(self, index):
return None
def get_child_index(self, name):
... | class Myintsynthprovider(object):
def __init__(self, valobj, dict):
self.valobj = valobj
self.val = self.valobj.GetChildMemberWithName('theValue')
def num_children(self):
return 0
def get_child_at_index(self, index):
return None
def get_child_index(self, name):
... |
# -*- coding: utf-8 -*-
"""Module init code."""
__version__ = '0.0.0'
__author__ = 'Your Name'
__email__ = 'your.email@mail.com'
| """Module init code."""
__version__ = '0.0.0'
__author__ = 'Your Name'
__email__ = 'your.email@mail.com' |
"""
Hydropy
=======
Provides functions to work with hydrological processes and equations
"""
| """
Hydropy
=======
Provides functions to work with hydrological processes and equations
""" |
class Photo:
def __init__(self, lid, tags_list, orientation):
"""
Constructor
:param lid: Photo identifier
:param tags_list: List of tags
:param orientation: Orientation. "H" for horizontal or "V" for vertical
"""
self.id = lid
self... | class Photo:
def __init__(self, lid, tags_list, orientation):
"""
Constructor
:param lid: Photo identifier
:param tags_list: List of tags
:param orientation: Orientation. "H" for horizontal or "V" for vertical
"""
self.id = lid
self.tags_li... |
'''
Test HTTP/2 with h2spec
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version... | """
Test HTTP/2 with h2spec
"""
Test.Summary = '\nTest HTTP/2 with httpspec\n'
Test.SkipUnless(Condition.HasProgram('h2spec', 'h2spec need to be installed on system for this test to work'))
Test.ContinueOnFail = True
httpbin = Test.MakeHttpBinServer('httpbin')
ts = Test.MakeATSProcess('ts', enable_tls=True, enable_cach... |
# Dependency injection:
# Technique where one object (or static method) supplies the dependencies of another object.
# The objective is to decouple objects to the extent that no client code has to be changed
# simply because an object it depends on needs to be changed to a different one.
# Dependency injection is one f... | class Shape(object):
def __new__(cls, *args, **kwargs):
if cls is Shape:
(description, args) = (args[0], args[1:])
if description == "It's flat":
new_cls = Line
else:
raise value_error('Invalid description: {}.'.format(description))
... |
"""
235. Lowest Common Ancestor of a Binary Search Tree
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
... | """
235. Lowest Common Ancestor of a Binary Search Tree
"""
class Solution(object):
def lowest_common_ancestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
minn = min(p.val, q.val)
maxx = max(p.... |
def conv(s):
if s[0] == 'a': v = '1'
elif s[0] == 'b': v = '2'
elif s[0] == 'c': v = '3'
elif s[0] == 'd': v = '4'
elif s[0] == 'e': v = '5'
elif s[0] == 'f': v = '6'
elif s[0] == 'g': v = '7'
elif s[0] == 'h': v = '8'
v += s[1]
return v
e = str(input()).split()
a = conv(e[0])
b... | def conv(s):
if s[0] == 'a':
v = '1'
elif s[0] == 'b':
v = '2'
elif s[0] == 'c':
v = '3'
elif s[0] == 'd':
v = '4'
elif s[0] == 'e':
v = '5'
elif s[0] == 'f':
v = '6'
elif s[0] == 'g':
v = '7'
elif s[0] == 'h':
v = '8'
v... |
#!/usr/bin/env python
domain_home = os.environ['DOMAIN_HOME']
node_manager_name = os.environ['NODE_MANAGER_NAME']
component_name = os.environ['COMPONENT_NAME']
component_admin_listen_address = os.environ['COMPONENT_ADMIN_LISTEN_ADDRESS']
component_admin_listen_port = os.environ['COMPONENT_ADMIN_LISTEN_PORT']
component... | domain_home = os.environ['DOMAIN_HOME']
node_manager_name = os.environ['NODE_MANAGER_NAME']
component_name = os.environ['COMPONENT_NAME']
component_admin_listen_address = os.environ['COMPONENT_ADMIN_LISTEN_ADDRESS']
component_admin_listen_port = os.environ['COMPONENT_ADMIN_LISTEN_PORT']
component_listen_address = os.en... |
"""
@generated
cargo-raze generated Bazel file.
DO NOT EDIT! Replaced on runs of cargo-raze
"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # buildifier: disable=load
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # buildifier: disable=load
load("@bazel_tools//too... | """
@generated
cargo-raze generated Bazel file.
DO NOT EDIT! Replaced on runs of cargo-raze
"""
load('@bazel_tools//tools/build_defs/repo:git.bzl', 'new_git_repository')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
def rules_rust_u... |
#Exercise: Try to make a function that accepts a function of only positional arguments and returns a function that takes the same number of positional arguments and, given they are all iterators, attempts every combination of one arguments from each iterator.
#Skills: Partial application, Iteration
papplycomboreverse ... | papplycomboreverse = lambda fun, xiter: lambda *args: [fun(*args, x) for x in xiter]
def combo(fun):
def returnfun(*args):
currfun = fun
for arg in reversed(args):
currfun = papplycomboreverse(currfun, arg)
return currfun()
return returnfun |
class Node:
"""
This object is a generic node, the basic component of a Graph.
Fields:
data -- the data this node will contain. This data can be any format.
"""
def __init__(self, data):
self.data = data
| class Node:
"""
This object is a generic node, the basic component of a Graph.
Fields:
data -- the data this node will contain. This data can be any format.
"""
def __init__(self, data):
self.data = data |
"""
Global tuple to avoid make a new one each time a method is called
"""
my_tuple = ("London", 123, 18.2)
def city_tuple_declaration():
city = ("Rome", "London", "Tokyo")
return city
def tuple_get_element(index: int):
try:
element = my_tuple[index]
print(element)
except IndexError:
... | """
Global tuple to avoid make a new one each time a method is called
"""
my_tuple = ('London', 123, 18.2)
def city_tuple_declaration():
city = ('Rome', 'London', 'Tokyo')
return city
def tuple_get_element(index: int):
try:
element = my_tuple[index]
print(element)
except IndexError:
... |
# https://leetcode.com/problems/mirror-reflection
class Solution:
def mirrorReflection(self, p, q):
if q == 0:
return 0
i = 0
val = 0
while True:
val += q
i += 1
if (i % 2 == 0) and (val % p == 0):
return 2
... | class Solution:
def mirror_reflection(self, p, q):
if q == 0:
return 0
i = 0
val = 0
while True:
val += q
i += 1
if i % 2 == 0 and val % p == 0:
return 2
elif i % 2 == 1 and val % (2 * p) == 0:
... |
"""
The `~certbot_dns_cfproxy.dns_cfproxy` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the CFProxy API.
Examples
--------
.. code-block:: bash
:caption: To acquire a certificate for ``example.com``
certbo... | """
The `~certbot_dns_cfproxy.dns_cfproxy` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the CFProxy API.
Examples
--------
.. code-block:: bash
:caption: To acquire a certificate for ``example.com``
certbo... |
a, b = map(int, input().split())
if a+b >= 10:
print("error")
else:
print(a+b)
| (a, b) = map(int, input().split())
if a + b >= 10:
print('error')
else:
print(a + b) |
__version__ = [1, 0, 2]
__versionstr__ = '.'.join([str(i) for i in __version__])
if __name__ == '__main__':
print(__versionstr__) | __version__ = [1, 0, 2]
__versionstr__ = '.'.join([str(i) for i in __version__])
if __name__ == '__main__':
print(__versionstr__) |
flat_x = x.flatten()
flat_y = y.flatten()
flat_z = z.flatten()
size = flat_x.shape[0]
filename = 'landscapeData.h'
open(filename, 'w').close()
f = open(filename, 'a')
f.write('#include "LinearMath/btScalar.h"\n#define Landscape01VtxCount 4\n#define Landscape01IdxCount 4\nbtScalar Landscape01Vtx[] = {\n')
for i in r... | flat_x = x.flatten()
flat_y = y.flatten()
flat_z = z.flatten()
size = flat_x.shape[0]
filename = 'landscapeData.h'
open(filename, 'w').close()
f = open(filename, 'a')
f.write('#include "LinearMath/btScalar.h"\n#define Landscape01VtxCount 4\n#define Landscape01IdxCount 4\nbtScalar Landscape01Vtx[] = {\n')
for i in range... |
# coding=utf-8
"""Russian Peasant Multiplication algorithm Python implementation."""
def russ_peasant(a, b):
res = 0
while b > 0:
if b & 1:
res += a
a <<= 1
b >>= 1
return res
if __name__ == '__main__':
for x in range(10):
for y in range(10):
p... | """Russian Peasant Multiplication algorithm Python implementation."""
def russ_peasant(a, b):
res = 0
while b > 0:
if b & 1:
res += a
a <<= 1
b >>= 1
return res
if __name__ == '__main__':
for x in range(10):
for y in range(10):
print(x, y, x * y, ... |
"""
QuickBot wiring config.
Specifies which pins are used for motor control, IR sensors and wheel encoders.
"""
# Motor pins: (dir1_pin, dir2_pin, pwd_pin)
RIGHT_MOTOR_PINS = 'P8_12', 'P8_10', 'P9_14'
LEFT_MOTOR_PINS = 'P8_14', 'P8_16', 'P9_16'
# IR sensors (clock-wise, starting with the rear left sensor):
# rear-l... | """
QuickBot wiring config.
Specifies which pins are used for motor control, IR sensors and wheel encoders.
"""
right_motor_pins = ('P8_12', 'P8_10', 'P9_14')
left_motor_pins = ('P8_14', 'P8_16', 'P9_16')
ir_pins = ('P9_38', 'P9_40', 'P9_36', 'P9_35', 'P9_33')
enc_pins = ('P9_39', 'P9_37') |
# Illustrates combining exception / error handling
# with file access
print('Start')
try:
with open('myfile2.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line, end='')
except FileNotFoundError as err:
print('oops')
print(err)
print('Done')
| print('Start')
try:
with open('myfile2.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line, end='')
except FileNotFoundError as err:
print('oops')
print(err)
print('Done') |
disable_gtk_binaries = True
def gtk_dependent_cc_library(**kwargs):
if not disable_gtk_binaries:
native.cc_library(**kwargs)
def gtk_dependent_cc_binary(**kwargs):
if not disable_gtk_binaries:
native.cc_binary(**kwargs)
| disable_gtk_binaries = True
def gtk_dependent_cc_library(**kwargs):
if not disable_gtk_binaries:
native.cc_library(**kwargs)
def gtk_dependent_cc_binary(**kwargs):
if not disable_gtk_binaries:
native.cc_binary(**kwargs) |
# Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.
# Make sure your procedure has a return statement.
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
def... | def bigger(a, b):
if a > b:
return a
else:
return b
def biggest(a, b, c):
return bigger(a, bigger(b, c))
def median(a, b, c):
if b >= a and a >= c or (c >= a and a >= b):
return a
if a >= b and b >= c or (c >= b and b >= a):
return b
if a >= c and c >= b or (b >... |
#!/usr/local/bin/python3
def main():
# Test suite
return
if __name__ == '__main__':
main()
| def main():
return
if __name__ == '__main__':
main() |
test = int(input())
while test > 0 :
n,k = map(int,input().split())
p = list(map(int,input().split()))
original = 0
later = 0
for i in p :
if i > k :
later += k
original += i
else :
later += i
original += i
print(orig... | test = int(input())
while test > 0:
(n, k) = map(int, input().split())
p = list(map(int, input().split()))
original = 0
later = 0
for i in p:
if i > k:
later += k
original += i
else:
later += i
original += i
print(original - later)
... |
def main():
# Arithmetic operators
a = 7
b = 2
print(f'{a} + {b} = {a+b}')
print(f'{a} - {b} = {a-b}')
print(f'{a} * {b} = {a*b}')
print(f'{a} / {b} = {a/b}')
print(f'{a} // {b} = {a//b}')
print(f'{a} % {b} = {a%b}')
print(f'{a} ^ {b} = {a**b}')
# Bitwise ... | def main():
a = 7
b = 2
print(f'{a} + {b} = {a + b}')
print(f'{a} - {b} = {a - b}')
print(f'{a} * {b} = {a * b}')
print(f'{a} / {b} = {a / b}')
print(f'{a} // {b} = {a // b}')
print(f'{a} % {b} = {a % b}')
print(f'{a} ^ {b} = {a ** b}')
print(f'{a} & {b} = {a & b}')
print(f'{... |
class Employee:
#Initializaing
def __init__(self):
print('Employee created ')
#Deleting (Calling destructor)
def __del__(self):
print('Destructor called,Employee deleted')
obj=Employee()
del obj | class Employee:
def __init__(self):
print('Employee created ')
def __del__(self):
print('Destructor called,Employee deleted')
obj = employee()
del obj |
""" Hvad-specific exceptions
Part of hvad public API.
"""
__all__ = ('WrongManager', )
class WrongManager(Exception):
""" Raised when attempting to introspect translated fields from
shared models without going through hvad. The most likely cause
for this being accessing translated fields from
... | """ Hvad-specific exceptions
Part of hvad public API.
"""
__all__ = ('WrongManager',)
class Wrongmanager(Exception):
""" Raised when attempting to introspect translated fields from
shared models without going through hvad. The most likely cause
for this being accessing translated fields from
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.