content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def find_tree(row, index):
if index > len(row):
row = row * ((index // len(row)) + 1)
if row[index] == '#':
return 1
return 0
if __name__ == '__main__':
with open('input.txt') as f:
data = [r.strip() for r in f.readlines()]
indices = range(0, len(data) * 3, 3)
tree_cou... | def find_tree(row, index):
if index > len(row):
row = row * (index // len(row) + 1)
if row[index] == '#':
return 1
return 0
if __name__ == '__main__':
with open('input.txt') as f:
data = [r.strip() for r in f.readlines()]
indices = range(0, len(data) * 3, 3)
tree_count = ... |
class BufferToLines(object):
def __init__(self):
self._acc_buff = ""
self._last_line = ""
self._in_middle_of_line = False
def add(self, buff):
self._acc_buff += buff.decode()
self._in_middle_of_line = False if self._acc_buff[-1] == '\n' else True
def lines(self):
... | class Buffertolines(object):
def __init__(self):
self._acc_buff = ''
self._last_line = ''
self._in_middle_of_line = False
def add(self, buff):
self._acc_buff += buff.decode()
self._in_middle_of_line = False if self._acc_buff[-1] == '\n' else True
def lines(self):
... |
"""Contains name, version, and description."""
NAME = "saltant-py"
VERSION = "0.4.0"
DESCRIPTION = "saltant SDK for Python"
| """Contains name, version, and description."""
name = 'saltant-py'
version = '0.4.0'
description = 'saltant SDK for Python' |
"""
Tema: Funciones decoradoras.
Curso: Curso de python, video 74.
Plataforma: Youtube.
Profesor: Juan diaz - Pildoras informaticas.
Alumno: @edinsonrequena.
"""
def funcion_decoradora(funcion_como_parametro):
def funcion_interior(*args, **kwargs):
print('Codigo que se ejecutara antes de llamar a la fu... | """
Tema: Funciones decoradoras.
Curso: Curso de python, video 74.
Plataforma: Youtube.
Profesor: Juan diaz - Pildoras informaticas.
Alumno: @edinsonrequena.
"""
def funcion_decoradora(funcion_como_parametro):
def funcion_interior(*args, **kwargs):
print('Codigo que se ejecutara antes de llamar a la fun... |
GET_ACTION_LIST = 'get_action_list'
EXECUTE_ACTION = 'execute_action'
GET_FIELD_OPTIONS = 'get_field_options'
GET_ELEMENT_STATUS = 'get_element_status'
message_handlers = {}
def add_handler(message_name, func):
message_handlers[message_name] = func
def get_handler(message_name):
return message_handlers.ge... | get_action_list = 'get_action_list'
execute_action = 'execute_action'
get_field_options = 'get_field_options'
get_element_status = 'get_element_status'
message_handlers = {}
def add_handler(message_name, func):
message_handlers[message_name] = func
def get_handler(message_name):
return message_handlers.get(me... |
"""
Parameters for etl & mondrian
"""
Patient = {
"resourceType" : "Patient",
"QI": {"resourceType" : 0, "birthDate" : 1, "address" : 1, "gender" : 0,
"ord_latitude" : 1, "ord_logitude" : 1, "version" : 0},
"CATEGORICAL": { "resourceType" : 1, "birthDate" : 0, "address" : 1, "gender" : 1, ... | """
Parameters for etl & mondrian
"""
patient = {'resourceType': 'Patient', 'QI': {'resourceType': 0, 'birthDate': 1, 'address': 1, 'gender': 0, 'ord_latitude': 1, 'ord_logitude': 1, 'version': 0}, 'CATEGORICAL': {'resourceType': 1, 'birthDate': 0, 'address': 1, 'gender': 1, 'ord_latitude': 0, 'ord_logitude': 0, 'versi... |
# Write a program that asks the number of kilometers a car has driven and the number of days it has been hired.
# Calculate the price to pay, knowing that the car costs US$ 60 per day and US$ 0.15 per km driven.
k = float(input('Enter how many kilometers the car has traveled: '))
d = float(input('Enter how many days t... | k = float(input('Enter how many kilometers the car has traveled: '))
d = float(input('Enter how many days the car has been rented: '))
t = k * 0.15 + d * 60
print('The total rental of the car is {}US${:.2f}{}'.format('\x1b[1;31;40m', t, '\x1b[m')) |
#!/usr/bin/env python
## =============================================================================
jsonStr = """[{"DT":"\/Date(1495333623000-0700)\/",
"ST":"\/Date(1495337144000)\/",
"Trend":8,
"Value":245,
"WT":"\/Date(1495326471000)\/"},
... | json_str = '[{"DT":"\\/Date(1495333623000-0700)\\/",\n "ST":"\\/Date(1495337144000)\\/",\n "Trend":8,\n "Value":245,\n "WT":"\\/Date(1495326471000)\\/"},\n\n {"DT":"\\/Date(1519423410000-0700)\\/",\n "ST":"\\/Date(1519423939000)\\/",\n ... |
class BaseMemory(object):
def __init__(self,
max_num=20000,
key_num=2000,
sampling_policy='random',
updating_policy='random', ):
super(BaseMemory, self).__init__()
self.max_num = max_num
self.key_num = key_num
self.s... | class Basememory(object):
def __init__(self, max_num=20000, key_num=2000, sampling_policy='random', updating_policy='random'):
super(BaseMemory, self).__init__()
self.max_num = max_num
self.key_num = key_num
self.sampling_policy = sampling_policy
self.updating_policy = updat... |
commands = input().split(" ")
my_list = []
team_a_count = 11
team_b_count = 11
condition = False
for i in commands:
if i not in my_list:
my_list.append(i)
if "A" in i:
team_a_count -= 1
if "B" in i:
team_b_count -= 1
if team_a_count < 7 or team_b_count < 7:
... | commands = input().split(' ')
my_list = []
team_a_count = 11
team_b_count = 11
condition = False
for i in commands:
if i not in my_list:
my_list.append(i)
if 'A' in i:
team_a_count -= 1
if 'B' in i:
team_b_count -= 1
if team_a_count < 7 or team_b_count < 7:
... |
""" Utilities. """
def init_params(model, scip_limits, scip_params):
"""
:param model: scip.Model(), model instantiation
:param scip_limits: dict, specifying SCIP parameter limits
:param scip_params: dict, specifying SCIP parameter setting
:return: -
Initialize SCIP parameters for the mode... | """ Utilities. """
def init_params(model, scip_limits, scip_params):
"""
:param model: scip.Model(), model instantiation
:param scip_limits: dict, specifying SCIP parameter limits
:param scip_params: dict, specifying SCIP parameter setting
:return: -
Initialize SCIP parameters for the model... |
class ActivePlan(object):
def __init__(self, join_observer_list, on_next, on_completed):
self.join_observer_list = join_observer_list
self.on_next = on_next
self.on_completed = on_completed
self.join_observers = {}
for join_observer in self.join_observer_list:
sel... | class Activeplan(object):
def __init__(self, join_observer_list, on_next, on_completed):
self.join_observer_list = join_observer_list
self.on_next = on_next
self.on_completed = on_completed
self.join_observers = {}
for join_observer in self.join_observer_list:
se... |
"""
Datos de entrada
Temperatura = t = float
Datos de salida
Deporte = d = str
"""
# Entradas
t=float(input(" Digite temperatura "))
# Caja Negra
deporte= ''
if(t>85 and t< 120):
deporte= "Natacion "
elif(t>70 and t<= 85 ):
deporte= "Tenis "
elif(t>32 and t<= 70 ):
deporte = "Golf "
elif(t>10 and t<=... | """
Datos de entrada
Temperatura = t = float
Datos de salida
Deporte = d = str
"""
t = float(input(' Digite temperatura '))
deporte = ''
if t > 85 and t < 120:
deporte = 'Natacion '
elif t > 70 and t <= 85:
deporte = 'Tenis '
elif t > 32 and t <= 70:
deporte = 'Golf '
elif t > 10 and t <= 32:
deporte... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Title : Lists
Subdomain : Basic Data Types
Author : Vincent Celis
Created : 19 July 2018
https://www.hackerrank.com/challenges/python-lists/problem
"""
methods = {
'insert': lambda *args: args[0].insert(int(args[1]), int(args[2])),
'... | """
Title : Lists
Subdomain : Basic Data Types
Author : Vincent Celis
Created : 19 July 2018
https://www.hackerrank.com/challenges/python-lists/problem
"""
methods = {'insert': lambda *args: args[0].insert(int(args[1]), int(args[2])), 'print': lambda *args: print(args[0]), 'remove': lambda *ar... |
COINS = (
(25, 'Quarters'),
(10, 'Dimes'),
(5, 'Nickels'),
(1, 'Pennies')
)
def loose_change(cents):
change = {'Pennies': 0, 'Nickels': 0, 'Dimes': 0, 'Quarters': 0}
cents = int(cents)
if cents <= 0:
return change
for coin_value, coin_name in COINS:
q, r = divmod(cents,... | coins = ((25, 'Quarters'), (10, 'Dimes'), (5, 'Nickels'), (1, 'Pennies'))
def loose_change(cents):
change = {'Pennies': 0, 'Nickels': 0, 'Dimes': 0, 'Quarters': 0}
cents = int(cents)
if cents <= 0:
return change
for (coin_value, coin_name) in COINS:
(q, r) = divmod(cents, coin_value)
... |
"""
time: n^3
space: n
"""
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp = [True] + [False] * len(s)
for i in range(1, len(s)+1):
for w in wordDict:
if s[:i].endswith(w):
dp[i] |= dp[i-len(w)]
return dp[-1]
"""
t... | """
time: n^3
space: n
"""
class Solution:
def word_break(self, s: str, wordDict: List[str]) -> bool:
dp = [True] + [False] * len(s)
for i in range(1, len(s) + 1):
for w in wordDict:
if s[:i].endswith(w):
dp[i] |= dp[i - len(w)]
return dp[-1]... |
class Alert:
def __init__(self, name):
self.name = name
self.enabled = False
def load(self, values):
for k, v in values.items():
if str(k).startswith('_') or k == 'name' or k not in vars(self):
continue # !cover
setattr(self, k, v)
# self.__dict__.update(**values)
def get_save_obj(self):
ret =... | class Alert:
def __init__(self, name):
self.name = name
self.enabled = False
def load(self, values):
for (k, v) in values.items():
if str(k).startswith('_') or k == 'name' or k not in vars(self):
continue
setattr(self, k, v)
def get_save_obj... |
'''input
97
89
20000
25899
10
5
8
10
97
89
8634
17266
97
89
8633
8633
100
100
101
200
1
1
1
1
1
1
20000
20000
100
100
20000
20000
12
8
25
48
2
3
8
12
2
2
2
2
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem A
if __name__ == '__... | """input
97
89
20000
25899
10
5
8
10
97
89
8634
17266
97
89
8633
8633
100
100
101
200
1
1
1
1
1
1
20000
20000
100
100
20000
20000
12
8
25
48
2
3
8
12
2
2
2
2
"""
if __name__ == '__main__':
a = int(input())
b = int(input())
n = int(input())
for i in range(n, 30000 + 1):
if i % a == 0 a... |
def count_largest_group(n: int) -> int:
hash_ = {}
for i in range(1, n + 1):
num = i
count = 0
while num >= 10:
count += num % 10
num //= 10
count += num
if count in hash_:
hash_[count] += 1
else:
has... | def count_largest_group(n: int) -> int:
hash_ = {}
for i in range(1, n + 1):
num = i
count = 0
while num >= 10:
count += num % 10
num //= 10
count += num
if count in hash_:
hash_[count] += 1
else:
hash_[count] = 1
... |
code=r"""function whos_f()
%Static variables
%persistent l %cellFile counter
%persistent m %cellFunc counter
%persistent cellFile
%persistent cellFunc
%initialize counter k
%if isempty(l)
% l = 1;
% m = 1;
%end
%Get info about caller, filename
ST = dbstack();
... | code = "function whos_f()\n %Static variables\n %persistent l %cellFile counter\n %persistent m %cellFunc counter\n %persistent cellFile\n %persistent cellFunc\n\n %initialize counter k\n %if isempty(l)\n % l = 1;\n % m = 1;\n %end\n\n %Get info about caller, filename\n ST = db... |
# -*- coding: utf-8 -*-
"""
pylite
~~~~~~~~~
:copyright: (c) 2014 by Dariush Abbasi.
:license: MIT, see LICENSE for more details.
"""
__version__ = "0.1.0"
| """
pylite
~~~~~~~~~
:copyright: (c) 2014 by Dariush Abbasi.
:license: MIT, see LICENSE for more details.
"""
__version__ = '0.1.0' |
"""Answer to Question 3 goes here.
Author: Dylan Blanchard, Sloan Anderson, and Stephen Johnson
Class: CSI-480-01
Assignment: PA 5 -- Supervised Learning
Due Date: Nov 30, 2018 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to... | """Answer to Question 3 goes here.
Author: Dylan Blanchard, Sloan Anderson, and Stephen Johnson
Class: CSI-480-01
Assignment: PA 5 -- Supervised Learning
Due Date: Nov 30, 2018 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to... |
"""Card Games - Exercism Python Exercises"""
def get_rounds(number):
"""
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return [number, number + 1, number + 2]
def concatenate_rounds(rounds_1, rounds_2):
"""
:param rounds_1: list -... | """Card Games - Exercism Python Exercises"""
def get_rounds(number):
"""
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return [number, number + 1, number + 2]
def concatenate_rounds(rounds_1, rounds_2):
"""
:param rounds_1: list - f... |
#Accept a list of words and return length of longest word.
def long_word(word_list):
word_len=[]
for word in word_list:
word_len.append((len(word),word))
word_len.sort()
return word_len[-1][0], word_len[-1][1]
word=long_word(["hai","everyone","bye"])
print("\nThe longest word is: ",wor... | def long_word(word_list):
word_len = []
for word in word_list:
word_len.append((len(word), word))
word_len.sort()
return (word_len[-1][0], word_len[-1][1])
word = long_word(['hai', 'everyone', 'bye'])
print('\nThe longest word is: ', word[1])
print("\nand the length of '", word[1], "' is: ", wor... |
# 5-5 Problems
print(all([1, 2, abs(-3)-3]))
print(chr(ord('a')) == 'a')
x = [1, -2, 3, -5, 8, -3]
print(list(filter(lambda val: val > 0, x)))
x = hex(234)
print(int(x, 16))
x = [1, 2, 3, 4]
print(list(map(lambda a: a * 3, x)))
x = [-8, 2, 7, 5, -3, 5, 0, 1]
print(max(x) + min(x))
x = 17 / 3
pri... | print(all([1, 2, abs(-3) - 3]))
print(chr(ord('a')) == 'a')
x = [1, -2, 3, -5, 8, -3]
print(list(filter(lambda val: val > 0, x)))
x = hex(234)
print(int(x, 16))
x = [1, 2, 3, 4]
print(list(map(lambda a: a * 3, x)))
x = [-8, 2, 7, 5, -3, 5, 0, 1]
print(max(x) + min(x))
x = 17 / 3
print(round(x, 4)) |
"""https://code.google.com/codejam/contest/10284486/dashboard#s=p1&a=1"""
def main():
T = int(input())
for i in range(1, T + 1):
N, K, P = (int(s) for s in input().split())
A = []
B = []
C = []
for _ in range(K):
a, b, c = (int(s) for s in input().split())
... | """https://code.google.com/codejam/contest/10284486/dashboard#s=p1&a=1"""
def main():
t = int(input())
for i in range(1, T + 1):
(n, k, p) = (int(s) for s in input().split())
a = []
b = []
c = []
for _ in range(K):
(a, b, c) = (int(s) for s in input().split()... |
def get_max_profits(stock_prices):
if len(stock_prices) < 2:
raise ValueError("Getting a profit requires at least two prices")
min_price = stock_prices[0]
max_profit = stock_prices[1] - stock_prices[0]
for current_time in range(1, len(stock_prices)):
print(current_time, "currenttime")
... | def get_max_profits(stock_prices):
if len(stock_prices) < 2:
raise value_error('Getting a profit requires at least two prices')
min_price = stock_prices[0]
max_profit = stock_prices[1] - stock_prices[0]
for current_time in range(1, len(stock_prices)):
print(current_time, 'currenttime')
... |
"""
Leetcode #1185
"""
class Solution:
# if we know that 1/1/1971 was Friday
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
isLeapYear = lambda x: 1 if x % 400 == 0 or (x % 4 == 0 and x % 100 != 0) else 0
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
d... | """
Leetcode #1185
"""
class Solution:
def day_of_the_week(self, day: int, month: int, year: int) -> str:
is_leap_year = lambda x: 1 if x % 400 == 0 or (x % 4 == 0 and x % 100 != 0) else 0
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = ['Sunday', 'Monday', 'Tuesday', ... |
# https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
PLAINTEXT = 'ATTACKATDAWN'
KEY = 'LEMON'
def vigenere_cipher_func(key, message):
message = message.lower()
key = key.lower()
cipher_message = ''
key_value = 0
for char in message:
if ord(char) >= 97 and ord(char) < 134:
mi... | plaintext = 'ATTACKATDAWN'
key = 'LEMON'
def vigenere_cipher_func(key, message):
message = message.lower()
key = key.lower()
cipher_message = ''
key_value = 0
for char in message:
if ord(char) >= 97 and ord(char) < 134:
mi = ord(char) - 97
ki = ord(key[key_value % le... |
#
# PySNMP MIB module SVRNTCLU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SVRNTCLU-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:04:39 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,... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_range_constraint, value_size_constraint, constraints_intersection) ... |
"""
Placeholder test file.
We'll add a bunch of tests here in later versions.
"""
def test_add():
"""Placeholder test."""
pass
| """
Placeholder test file.
We'll add a bunch of tests here in later versions.
"""
def test_add():
"""Placeholder test."""
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 30 22:35:24 2021
@author: aboisvert
"""
#%% Part 1
"""
As the submarine drops below the surface of the ocean, it automatically performs a sonar sweep of the nearby sea floor. On a small screen, the sonar sweep report (your puzzle input) appears: ea... | """
Created on Tue Nov 30 22:35:24 2021
@author: aboisvert
"""
"\nAs the submarine drops below the surface of the ocean, it automatically performs a sonar sweep of the nearby sea floor. On a small screen, the sonar sweep report (your puzzle input) appears: each line is a measurement of the sea floor depth as the sweep... |
def iteritems(dictonary):
pass
class StringIO(object):
pass
| def iteritems(dictonary):
pass
class Stringio(object):
pass |
def dfs(node, parent, visited, tin, low, adj:list, timer,res):
visited[node] = 1
timer += 1
tin[node] = low[node] = timer
for it in adj[node]:
if(it == parent):
continue
if(visited[it] == 0):
dfs(it, node, visited, tin, low, adj, timer,res)
low... | def dfs(node, parent, visited, tin, low, adj: list, timer, res):
visited[node] = 1
timer += 1
tin[node] = low[node] = timer
for it in adj[node]:
if it == parent:
continue
if visited[it] == 0:
dfs(it, node, visited, tin, low, adj, timer, res)
low[node] ... |
r= int(input())
pi= 3.14159
sphere= (4/3)* pi* pow(r,3)
print("VOLUME = %.3f" %sphere)
| r = int(input())
pi = 3.14159
sphere = 4 / 3 * pi * pow(r, 3)
print('VOLUME = %.3f' % sphere) |
class CoreConstraintConstants:
core_constraint_slots = (
"table", "constraint_name", "constraint_definition",
"UNIQUE", "PRIMARY_KEY", "FOREIGN_KEY", "REFERENCES",
"CHECK", "DEFAULT", "FOR"
)
core_constraint_default_values = {
"table": None,
"constraint_name": None,
... | class Coreconstraintconstants:
core_constraint_slots = ('table', 'constraint_name', 'constraint_definition', 'UNIQUE', 'PRIMARY_KEY', 'FOREIGN_KEY', 'REFERENCES', 'CHECK', 'DEFAULT', 'FOR')
core_constraint_default_values = {'table': None, 'constraint_name': None, 'constraint_definition': '', 'UNIQUE': (), 'PRIM... |
# -*- coding: utf-8 -*-
COMMIT_AUTHOR_NAME = 'Mimiron'
COMMIT_AUTHOR_EMAIL = ''
| commit_author_name = 'Mimiron'
commit_author_email = '' |
class LookupBindingPropertiesAttribute(Attribute,_Attribute):
"""
Specifies the properties that support lookup-based binding. This class cannot be inherited.
LookupBindingPropertiesAttribute()
LookupBindingPropertiesAttribute(dataSource: str,displayMember: str,valueMember: str,lookupMember: str)
"""
d... | class Lookupbindingpropertiesattribute(Attribute, _Attribute):
"""
Specifies the properties that support lookup-based binding. This class cannot be inherited.
LookupBindingPropertiesAttribute()
LookupBindingPropertiesAttribute(dataSource: str,displayMember: str,valueMember: str,lookupMember: str)
"""
... |
#
# PySNMP MIB module IP-FORWARD-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/IP-FORWARD-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:17:45 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
class InvalidSignatureError(Exception):
""" User signature is not valid."""
class BadRequestError(Exception):
""" Indicates a malformed request or missing parameters."""
| class Invalidsignatureerror(Exception):
""" User signature is not valid."""
class Badrequesterror(Exception):
""" Indicates a malformed request or missing parameters.""" |
# Declare any variables (as constants) that are or could be used anywhere in the application
# TODO: Determine what a good fingerprint length is
FINGERPRINT_LENGTH = 40
| fingerprint_length = 40 |
def multi(a,b):
return a*b
if __name__ == '__main__':
print(multi(2,3))
| def multi(a, b):
return a * b
if __name__ == '__main__':
print(multi(2, 3)) |
class LayerShape:
def __init__(self, *dims):
self.dims = dims
if len(dims) == 1:
self.channels = dims[0]
elif len(dims) == 2:
self.channels = dims[0]
self.height = dims[1]
elif len(dims) == 3:
self.channels = dims[0]
self.he... | class Layershape:
def __init__(self, *dims):
self.dims = dims
if len(dims) == 1:
self.channels = dims[0]
elif len(dims) == 2:
self.channels = dims[0]
self.height = dims[1]
elif len(dims) == 3:
self.channels = dims[0]
self.h... |
# Time: O(Log n) We performed a Binary Search
# Space: O(1)
class Solution:
def findMin(self, nums):
if len(nums) == 1:
return nums[0]
left = 0
right = len(nums) - 1
if nums[0] < nums[right]:
return nums[0]
while left <= right:
m... | class Solution:
def find_min(self, nums):
if len(nums) == 1:
return nums[0]
left = 0
right = len(nums) - 1
if nums[0] < nums[right]:
return nums[0]
while left <= right:
mid = (right + left) // 2
mid_val = nums[mid]
... |
def foo_task():
print('Foo task is running...')
print('Foo task completed.')
return True
def sum_task(arg_1: int, arg_2: int):
print('Sum task is running...')
result = arg_1 + arg_2
print('Sum task completed.')
return result
| def foo_task():
print('Foo task is running...')
print('Foo task completed.')
return True
def sum_task(arg_1: int, arg_2: int):
print('Sum task is running...')
result = arg_1 + arg_2
print('Sum task completed.')
return result |
#!/usr/bin/env python3
# Tax calculator
# This program currently
# only works with the hungarian tax
def calcTax(cost, country='hungary'):
countries = {'hungary' : 27}
if country in countries.keys():
tax = (cost / 100) * countries[country]
else:
return "Country can't be found"
retur... | def calc_tax(cost, country='hungary'):
countries = {'hungary': 27}
if country in countries.keys():
tax = cost / 100 * countries[country]
else:
return "Country can't be found"
return tax
def main():
tax = calc_tax(int(input('What was the cost of your purchase? ')), input('Which count... |
"""
Write code to add, search and remove items from an unsorted linked list.
"""
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
def add(self, cargo):
_next = self.head
self.head = Node(cargo, _next)
self.length += 1
def search(self, value):... | """
Write code to add, search and remove items from an unsorted linked list.
"""
class Linkedlist:
def __init__(self):
self.length = 0
self.head = None
def add(self, cargo):
_next = self.head
self.head = node(cargo, _next)
self.length += 1
def search(self, value):... |
def boarding_pass_row(seq):
assert len(seq) == 7
# FBFBBFF
seqb = seq.replace('F', '0').replace('B', '1')
return int(seqb, 2)
def boarding_pass_col(seq):
assert len(seq) == 3
seqb = seq.replace('R', '1').replace('L', '0')
return int(seqb, 2)
def row_id(seq):
row, col = boarding_pass_row(seq[:7]), boardin... | def boarding_pass_row(seq):
assert len(seq) == 7
seqb = seq.replace('F', '0').replace('B', '1')
return int(seqb, 2)
def boarding_pass_col(seq):
assert len(seq) == 3
seqb = seq.replace('R', '1').replace('L', '0')
return int(seqb, 2)
def row_id(seq):
(row, col) = (boarding_pass_row(seq[:7]),... |
'''
Details about this Python package.
'''
__version__ = '1.1.0'
__title__ = 'example-python'
__author__ = 'Mahathir Almashor'
__author_email__ = 'mahathir.almashor@data61.csiro.au'
__description__ = 'Example Python repository for Cyber Security Cooperative Research Centre'
__url__ = 'https://github.com/ma-al/example-... | """
Details about this Python package.
"""
__version__ = '1.1.0'
__title__ = 'example-python'
__author__ = 'Mahathir Almashor'
__author_email__ = 'mahathir.almashor@data61.csiro.au'
__description__ = 'Example Python repository for Cyber Security Cooperative Research Centre'
__url__ = 'https://github.com/ma-al/example-p... |
# Create query to get call counts by complaint_type
query = """
SELECT complaint_type,
COUNT(*)
FROM hpd311calls
GROUP BY complaint_type;
"""
# Create data frame of call counts by issue
calls_by_issue = pd.read_sql(query, engine)
# Graph the number of calls for each housing issue
calls_by_issue.plot.barh(x... | query = '\nSELECT complaint_type, \n COUNT(*)\n FROM hpd311calls\n GROUP BY complaint_type;\n'
calls_by_issue = pd.read_sql(query, engine)
calls_by_issue.plot.barh(x='complaint_type')
plt.show() |
with open("day13.in") as f:
lines = f.read().splitlines()
dots = set()
for i, line in enumerate(lines):
if line == "":
break
x, y = line.split(",")
dots.add((int(x), int(y)))
# folds
for line in lines[i+1:]:
_, _, fold = line.split(" ")
axis, num = fold.split("=")
num = int(num... | with open('day13.in') as f:
lines = f.read().splitlines()
dots = set()
for (i, line) in enumerate(lines):
if line == '':
break
(x, y) = line.split(',')
dots.add((int(x), int(y)))
for line in lines[i + 1:]:
(_, _, fold) = line.split(' ')
(axis, num) = fold.split('=')
num = int(num)
... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( num ) :
series = [ 1 , 3 , 2 , - 1 , - 3 , - 2 ] ;
series_index = 0 ;
result = 0 ;
for i in range (... | def f_gold(num):
series = [1, 3, 2, -1, -3, -2]
series_index = 0
result = 0
for i in range(len(num) - 1, -1, -1):
digit = ord(num[i]) - 48
result += digit * series[series_index]
series_index = (series_index + 1) % 6
result %= 7
if result < 0:
result = (result ... |
VALUE_INITIALIZED = 0
def test_owner_address(box, accounts):
# verify that accounts[0] is contract owner
assert accounts[0].address == box.owner()
def test_value_after_contract_creation(box, accounts):
# verify initialized value of box
assert VALUE_INITIALIZED == box.retrieve()
| value_initialized = 0
def test_owner_address(box, accounts):
assert accounts[0].address == box.owner()
def test_value_after_contract_creation(box, accounts):
assert VALUE_INITIALIZED == box.retrieve() |
"""Module that implements mocking Vega type coercing functions."""
type_coercing_functions = ['toBoolean', 'toDate', 'toNumber', 'toString']
error_message = ' is a mocking function that is not supposed to be called directly'
def toBoolean(value):
"""Coerce the input value to a string. None values and empty stri... | """Module that implements mocking Vega type coercing functions."""
type_coercing_functions = ['toBoolean', 'toDate', 'toNumber', 'toString']
error_message = ' is a mocking function that is not supposed to be called directly'
def to_boolean(value):
"""Coerce the input value to a string. None values and empty string... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
result = []
self.dfs_rec(ro... | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
result = []
self.dfs_rec(... |
# This file creates custom rules to make tests can easily run under
# certain environment(like inside a docker).
#
# For example:
#
# run_under_test(
# name = "test_under_docker",
# under = "//tools/docker:zookeper",
# command = "//sometest",
# data = [
# ],
# args = [
# "--gtest_filter=abc",
# ]
# )
... | def _run_under_impl(ctx):
bin_dir = ctx.configuration.bin_dir
build_directory = str(bin_dir)[:-len('[derived]')] + '/'
under = ctx.executable.under
under_args = ctx.attr.under_args
command = ctx.executable.command
exe = ctx.outputs.executable
ctx.file_action(output=exe, content='#!/bin/bash\... |
# x = n^2 + an + b; |a| < 1000 and |b| < 1000
# b has to be odd, positive and prime as we are testing consecutive values for n
# a has to be negative otherwise the difference between consecutive x's will be huge!
def is_prime(num) :
if (num <= 1) :
return False
if (num <= 3) :
return True... | def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i = i + 6
return True
def max_prod(max_val_a, max... |
linz = '---' * 30
# This is the Procedual way of creating a GUI
'''import tkinter
def main():
#creates the main window
main_window = tkinter.Tk()
# Enters the Tkinter main loop
tkinter.mainloop()
# Calls the main function
main()
print(linz)'''
linz = '---' * 30
# This is the Module way of creating a... | linz = '---' * 30
'import tkinter\ndef main():\n #creates the main window\n main_window = tkinter.Tk()\n\n # Enters the Tkinter main loop\n tkinter.mainloop()\n\n# Calls the main function\nmain()\nprint(linz)'
linz = '---' * 30
'import tkinter\n\nclass MYHGUI:\n def init(self):\n self.main_window ... |
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
nlist = [[i,j,k] for i in range(0, x+1) for j in range(0, y+1) for k in range(0, z+1) if (i+j+k) > n or (i+j+k)< n]
print(nlist) | if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
nlist = [[i, j, k] for i in range(0, x + 1) for j in range(0, y + 1) for k in range(0, z + 1) if i + j + k > n or i + j + k < n]
print(nlist) |
"""
Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.
str.isalnum()
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
>>> print 'ab123'.isalnum()
True
>>> print 'a... | """
Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.
str.isalnum()
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
>>> print 'ab123'.isalnum()
True
>>> print 'a... |
# :coding: utf-8
# :copyright: Copyright (c) 2021 strack
class StrackError(RuntimeError):
""" Custom error class. """
def __init__(self, arg):
self.args = arg
| class Strackerror(RuntimeError):
""" Custom error class. """
def __init__(self, arg):
self.args = arg |
##Collect data:
'''
#SMI: 2021/10/30
SAF: 308214 Standard Beamline 12-ID proposal: (CFN, 307961)
create proposal: proposal_id( '2021_3', '307961_Dinca' ) #create the proposal id and folder
%run -i /home/xf12id/.ipython/profile_collection/startup/users/30-user-Dinca2021C2B.py
RE( shopen() ) # to... | """
#SMI: 2021/10/30
SAF: 308214 Standard Beamline 12-ID proposal: (CFN, 307961)
create proposal: proposal_id( '2021_3', '307961_Dinca' ) #create the proposal id and folder
%run -i /home/xf12id/.ipython/profile_collection/startup/users/30-user-Dinca2021C2B.py
RE( shopen() ) # to open the beam and... |
# 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 isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not roo... | class Solution(object):
def is_symmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return False
def dfs(leftNode, rightNode):
if leftNode == None and rightNode == None:
return True
elif le... |
class Arithmetic:
def __init__(self):
self.value1 = 0
self.value2 = 0
def Accept(self, no1, no2):
self.value1 = no1
self.value2 = no2
def Addition(self):
result = self.value1 + self.value2
print("Addition is = ", result)
def Subtraction(sel... | class Arithmetic:
def __init__(self):
self.value1 = 0
self.value2 = 0
def accept(self, no1, no2):
self.value1 = no1
self.value2 = no2
def addition(self):
result = self.value1 + self.value2
print('Addition is = ', result)
def subtraction(self):
... |
input = """####.#.##.###.#.#.##.#..###.#..#.#.#..##....#.###...##..###.##.#.#.#.##...##..#..#....#.#.##..#...##
.##...##.##.######.#.#.##...#.#.#.#.#...#.##.#..#.#.####...#....#....###.#.#.#####....#.#.##.#.#.##.
###.##..#..#####.......#.########...#.####.###....###.###...#...####.######.#..#####.#.###....####..
....#.... | input = '####.#.##.###.#.#.##.#..###.#..#.#.#..##....#.###...##..###.##.#.#.#.##...##..#..#....#.#.##..#...##\n.##...##.##.######.#.#.##...#.#.#.#.#...#.##.#..#.#.####...#....#....###.#.#.#####....#.#.##.#.#.##.\n###.##..#..#####.......#.########...#.####.###....###.###...#...####.######.#..#####.#.###....####..\n....#... |
class Config(object) :
#DETECTRON_URL = 'http://localhost/predictions'
DETECTRON_URL = 'https://master-ainized-detectron2-gkswjdzz.endpoint.ainize.ai/predictions'
#STANFORDNLP_URL = 'http://localhost:81/analyze'
STANFORDNLP_URL = 'https://master-ainized-stanfordnlp-gkswjdzz.endpoint.ainize.ai/analyze'
| class Config(object):
detectron_url = 'https://master-ainized-detectron2-gkswjdzz.endpoint.ainize.ai/predictions'
stanfordnlp_url = 'https://master-ainized-stanfordnlp-gkswjdzz.endpoint.ainize.ai/analyze' |
"""
From Kapil Sharma's lecture 11 Jun 2020
Given the head of a sll and a node, return its index (position).
Assume that indexing starts at 0.
Return -1 if index is not found.
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def find_index(head, node):
# Edge case... | """
From Kapil Sharma's lecture 11 Jun 2020
Given the head of a sll and a node, return its index (position).
Assume that indexing starts at 0.
Return -1 if index is not found.
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def find_index(head, node):
if head == N... |
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
def main():
n, a, b = list(map(int, input().split()))
position = 0
for i in range(n):
s, d = list(map(str, input().split()))
if int(d) < a:
d = a
elif int(d) > b:
d = b
else:
d = d
... | def main():
(n, a, b) = list(map(int, input().split()))
position = 0
for i in range(n):
(s, d) = list(map(str, input().split()))
if int(d) < a:
d = a
elif int(d) > b:
d = b
else:
d = d
if s == 'West':
d = -1 * int(d)
... |
"""
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], targe... | """
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], targe... |
class CFG:
# Disease:
_TARGET_R0 = 1.4 # before Test and Trace and Isolation
DAYS_BEFORE_INFECTIOUS = 4 # t0
DAYS_INFECTIOUS_TO_SYMPTOMS = 2 # t1
DAYS_OF_SYMPTOMS = 5 # t2
PROB_SYMPTOMATIC = 0.6 # pS probability that an infected person develops actionable symptoms
... | class Cfg:
_target_r0 = 1.4
days_before_infectious = 4
days_infectious_to_symptoms = 2
days_of_symptoms = 5
prob_symptomatic = 0.6
prob_isolate_if_symptoms = 0.75
prob_isolate_if_traced = 0.3
prob_isolate_if_testpos = 0.3
prob_get_test_if_traced = 0.75
prob_apply_for_test_if_symp... |
getMappingUsageMetrics = [
{
"names": [
"TotalBandwidth",
"TotalHits",
"HitRatio"
],
"totals": [
"0.0",
"0",
"0.0"
],
"type": "TOTALS"
}
]
| get_mapping_usage_metrics = [{'names': ['TotalBandwidth', 'TotalHits', 'HitRatio'], 'totals': ['0.0', '0', '0.0'], 'type': 'TOTALS'}] |
class Solution:
def reverse(self, x: int) -> int:
l = 0
val = 0
flag = 1
if x == 0:
return x
else:
if x>0:
val = x
l = len(str(val))
else:
val = -1*x
l = len(str(val))
... | class Solution:
def reverse(self, x: int) -> int:
l = 0
val = 0
flag = 1
if x == 0:
return x
else:
if x > 0:
val = x
l = len(str(val))
else:
val = -1 * x
l = len(str(val))
... |
class Solution:
def oddCells(self, n: int, m: int, indices: list) -> int:
row_operation = [False] * n
col_operation = [False] * m
for index in indices:
row_id, col_id = index
row_operation[row_id] = not row_operation[row_id]
col_operation[col_id] = not co... | class Solution:
def odd_cells(self, n: int, m: int, indices: list) -> int:
row_operation = [False] * n
col_operation = [False] * m
for index in indices:
(row_id, col_id) = index
row_operation[row_id] = not row_operation[row_id]
col_operation[col_id] = not... |
"""
http://stackoverflow.com/questions/312443/#312464
"""
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i : i + n]
| """
http://stackoverflow.com/questions/312443/#312464
"""
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n] |
# FindControlUnderMouse() returns an existing control, not a new one,
# so create this one by hand.
f = Function(ExistingControlHandle, 'FindControlUnderMouse',
(Point, 'inWhere', InMode),
(WindowRef, 'inWindow', InMode),
(SInt16, 'outPart', OutMode),
)
functions.append(f)
f = Function(ControlHandle, 'as_C... | f = function(ExistingControlHandle, 'FindControlUnderMouse', (Point, 'inWhere', InMode), (WindowRef, 'inWindow', InMode), (SInt16, 'outPart', OutMode))
functions.append(f)
f = function(ControlHandle, 'as_Control', (Handle, 'h', InMode))
functions.append(f)
f = method(Handle, 'as_Resource', (ControlHandle, 'ctl', InMode... |
print("Premier programme")
nom = input("Donnez votre nom : ")
print("Bonjour %s, comment vas-tu? " % nom)
| print('Premier programme')
nom = input('Donnez votre nom : ')
print('Bonjour %s, comment vas-tu? ' % nom) |
def read_data(filename="data/input1.data"):
with open(filename) as f:
return f.read()
def rot(l, i):
offset = len(l) // 2
pos = (i+offset) % len(l)
return l[pos] if l[pos] == l[i] else 0
if __name__ == "__main__":
captcha = [int(x) for x in read_data()]
captcha.append(captcha[0])
... | def read_data(filename='data/input1.data'):
with open(filename) as f:
return f.read()
def rot(l, i):
offset = len(l) // 2
pos = (i + offset) % len(l)
return l[pos] if l[pos] == l[i] else 0
if __name__ == '__main__':
captcha = [int(x) for x in read_data()]
captcha.append(captcha[0])
... |
"""
appthwack.tests
~~~~~~~~~~~~~~~
Package which contains tests for the AppThwack client.
"""
__author__ = 'Andrew Hawker <andrew@appthwack.com>'
| """
appthwack.tests
~~~~~~~~~~~~~~~
Package which contains tests for the AppThwack client.
"""
__author__ = 'Andrew Hawker <andrew@appthwack.com>' |
#################### version 1 #################################################
a = list(range(10))
# print(a, id(a))
res_1 = list(a)
# print(res_1, id(res_1))
for i in a:
if i in (3, 5):
print(">>>", i, id(i))
res_1 = list(filter(lambda x: x != i, res_1))
# print(type(res_1), id(res_1))... | a = list(range(10))
res_1 = list(a)
for i in a:
if i in (3, 5):
print('>>>', i, id(i))
res_1 = list(filter(lambda x: x != i, res_1))
print(list(res_1))
b = list(range(10))
res_2 = list(b)
for i in b:
if i in {3, 5}:
print('>>>', i, id(i))
res_2 = filter(lambda x: x != i, res_2)
... |
"""Given an integer, write a function to determine if it is a power of two."""
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
num = 1
while num < n:
num *= 2
if n / ... | """Given an integer, write a function to determine if it is a power of two."""
class Solution(object):
def is_power_of_two(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
num = 1
while num < n:
num *= 2
if n... |
def add_native_methods(clazz):
def initPbuffer__long__long__boolean__int__int__(a0, a1, a2, a3, a4, a5):
raise NotImplementedError()
clazz.initPbuffer__long__long__boolean__int__int__ = initPbuffer__long__long__boolean__int__int__
| def add_native_methods(clazz):
def init_pbuffer__long__long__boolean__int__int__(a0, a1, a2, a3, a4, a5):
raise not_implemented_error()
clazz.initPbuffer__long__long__boolean__int__int__ = initPbuffer__long__long__boolean__int__int__ |
class CompressString(object):
def compress(self, string):
if string is None or not string:
return string
result = ''
prev_char = string[0]
count = 0
for char in string:
if char == prev_char:
count += 1
else:
... | class Compressstring(object):
def compress(self, string):
if string is None or not string:
return string
result = ''
prev_char = string[0]
count = 0
for char in string:
if char == prev_char:
count += 1
else:
... |
class Solution:
def findErrorNums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
record = [0] * (len(nums) + 1)
for num in nums:
record[num] += 1
dup, miss = 0, 0
for idx, val in enumerate(record):
if val ... | class Solution:
def find_error_nums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
record = [0] * (len(nums) + 1)
for num in nums:
record[num] += 1
(dup, miss) = (0, 0)
for (idx, val) in enumerate(record):
if val ... |
def solution(a):
answer = 0
left_min = 1000000001
left_zero = []
reverse_a = a[::-1]
right_zero = []
right_min = 1000000001
for i in range(len(a)):
left_min = min(a[i], left_min)
if left_min == a[i]:
left_zero.append(1)
else:
left_zero.append... | def solution(a):
answer = 0
left_min = 1000000001
left_zero = []
reverse_a = a[::-1]
right_zero = []
right_min = 1000000001
for i in range(len(a)):
left_min = min(a[i], left_min)
if left_min == a[i]:
left_zero.append(1)
else:
left_zero.append(0... |
data = (
((-0.195090, 0.980785), (0.000000, 1.000000)),
((-0.382683, 0.923880), (-0.195090, 0.980785)),
((-0.555570, 0.831470), (-0.382683, 0.923880)),
((-0.707107, 0.707107), (-0.555570, 0.831470)),
((-0.831470, 0.555570), (-0.707107, 0.707107)),
((-0.923880, 0.382683), (-0.831470, 0.555570)),
((-0.980785, 0.195090), ... | data = (((-0.19509, 0.980785), (0.0, 1.0)), ((-0.382683, 0.92388), (-0.19509, 0.980785)), ((-0.55557, 0.83147), (-0.382683, 0.92388)), ((-0.707107, 0.707107), (-0.55557, 0.83147)), ((-0.83147, 0.55557), (-0.707107, 0.707107)), ((-0.92388, 0.382683), (-0.83147, 0.55557)), ((-0.980785, 0.19509), (-0.92388, 0.382683)), ((... |
sum = float(input())
counter_of_coins = 0
sum = int(sum*100)
counter_of_coins += sum // 200
sum = sum % 200
counter_of_coins += sum // 100
sum = sum % 100
counter_of_coins += sum // 50
sum = sum % 50
counter_of_coins += sum // 20
sum = sum % 20
counter_of_coins += sum // 10
sum = sum % 10
counter_of_coins += sum // 5
... | sum = float(input())
counter_of_coins = 0
sum = int(sum * 100)
counter_of_coins += sum // 200
sum = sum % 200
counter_of_coins += sum // 100
sum = sum % 100
counter_of_coins += sum // 50
sum = sum % 50
counter_of_coins += sum // 20
sum = sum % 20
counter_of_coins += sum // 10
sum = sum % 10
counter_of_coins += sum // 5... |
def validate_string(s):
is_alpha_numeric = False
is_alpha = False
is_digits = False
is_lowercase = False
is_uppercase = False
for letter in s:
if letter.isalnum():
is_alpha_numeric = True
if letter.isalpha():
is_alpha = True
if letter.isdigit():... | def validate_string(s):
is_alpha_numeric = False
is_alpha = False
is_digits = False
is_lowercase = False
is_uppercase = False
for letter in s:
if letter.isalnum():
is_alpha_numeric = True
if letter.isalpha():
is_alpha = True
if letter.isdigit():
... |
"""
Exceptions
==========
"""
class AuditEventException(BaseException):
pass
| """
Exceptions
==========
"""
class Auditeventexception(BaseException):
pass |
class TestScheduleJobFileData:
test_job_connection = {
"Name": "TestIntegrationConnection",
"ConnectorTypeName": "POSTGRESQL",
"Host": "localhost",
"Port": 5432,
"Sid": "",
"DatabaseName": "test_pdi_integration",
"User": "postgres",
"Password": "123456... | class Testschedulejobfiledata:
test_job_connection = {'Name': 'TestIntegrationConnection', 'ConnectorTypeName': 'POSTGRESQL', 'Host': 'localhost', 'Port': 5432, 'Sid': '', 'DatabaseName': 'test_pdi_integration', 'User': 'postgres', 'Password': '123456'}
test_file_connection = {'Name': 'TestIntegrationConnection... |
# -*- coding: utf-8 -*-
"""
Label mapping.
Created on Tue May 15 22:00:00 2018
Author: Prasun Roy | CVPRU-ISICAL (http://www.isical.ac.in/~cvpr)
GitHub: https://github.com/prasunroy/air-writing
"""
# English numerals
map2ascii_en_numbers = {
0: 48,
1: 49,
2: 50,
3: 51,
4: 52,
... | """
Label mapping.
Created on Tue May 15 22:00:00 2018
Author: Prasun Roy | CVPRU-ISICAL (http://www.isical.ac.in/~cvpr)
GitHub: https://github.com/prasunroy/air-writing
"""
map2ascii_en_numbers = {0: 48, 1: 49, 2: 50, 3: 51, 4: 52, 5: 53, 6: 54, 7: 55, 8: 56, 9: 57}
map2unicode_bn_numbers = {0: '০', 1: '১', 2: '২', 3... |
def func(a, b=5, c=10):
print('a equals {}, b equals {}, and c equals {}'.format(a, b, c))
func(3, 7)
func(25, c=24)
func(c=50, a=100)
| def func(a, b=5, c=10):
print('a equals {}, b equals {}, and c equals {}'.format(a, b, c))
func(3, 7)
func(25, c=24)
func(c=50, a=100) |
# encoding: utf-8
# module termios
# from /usr/lib/python3.5/lib-dynload/termios.cpython-35m-x86_64-linux-gnu.so
# by generator 1.145
"""
This module provides an interface to the Posix calls for tty I/O control.
For a complete description of these calls, see the Posix or Unix manual
pages. It is only available for thos... | """
This module provides an interface to the Posix calls for tty I/O control.
For a complete description of these calls, see the Posix or Unix manual
pages. It is only available for those Unix versions that support Posix
termios style tty I/O control.
All functions in this module take a file descriptor fd as their fir... |
def isPrime(number):
if number > 1:
for i in range(2, number):
if (number % i) == 0:
return False
else:
return True
else:
return False
inputFile = open('test.txt')
lines = inputFile.readlines()
inputFile.close()
pyramid = []
for i in lines:
pr... | def is_prime(number):
if number > 1:
for i in range(2, number):
if number % i == 0:
return False
else:
return True
else:
return False
input_file = open('test.txt')
lines = inputFile.readlines()
inputFile.close()
pyramid = []
for i in lines:
pri... |
def verify(output):
scopes = False
fail = False
for line in output.split('\n'):
if scopes:
if line.startswith(' '):
name,size = [x.strip() for x in line.split('-')]
if size != '0':
print("unfreed memory in scope",name,":",size)
... | def verify(output):
scopes = False
fail = False
for line in output.split('\n'):
if scopes:
if line.startswith(' '):
(name, size) = [x.strip() for x in line.split('-')]
if size != '0':
print('unfreed memory in scope', name, ':', size)
... |
#!/usr/bin/env python
# coding: utf-8
def write_tweet_tfile(file_to_populate, text):
file_handler = open(file_to_populate,"a+")
file_handler.writelines(text)
file_handler.close()
def strip_token(myword, chars_token):
return myword.strip(chars_token)
| def write_tweet_tfile(file_to_populate, text):
file_handler = open(file_to_populate, 'a+')
file_handler.writelines(text)
file_handler.close()
def strip_token(myword, chars_token):
return myword.strip(chars_token) |
class Person:
def __init__(self, name, email):
self.name = name
self.email = email
self.all_my_emails = []
def send_email(self, to_user, message):
print(f"send from {self.name} with email {self.email}")
print(f"sending to {to_user} message {message}")
return Tr... | class Person:
def __init__(self, name, email):
self.name = name
self.email = email
self.all_my_emails = []
def send_email(self, to_user, message):
print(f'send from {self.name} with email {self.email}')
print(f'sending to {to_user} message {message}')
return Tru... |
###################################
# SIMPLETICKET CONFIGURATION FILE #
###################################
###############################################
# Flask Development Environment Configuration #
###############################################
# This is not used when using the WSGI mod for apache.
# interface... | interface_ip = '0.0.0.0'
interface_port = '80'
require_login = True
language = 'en_EN'
site_name = 'SimpleTicket Development Instance'
secret_key = 'm-_2hz7kJL-oOHtwKkI5ew'
create_admin_file = '_CREATE_ADMIN_ALLOWED'
timeformat = '%H:%M:%S, %d.%m.%Y' |
N = int(input())
while True:
S = [[] for k in range(N)]
S_len = [0 for k in range(N)]
bigger_len = 0
for k in range(N):
S[k] = input().split()
S_len[k] = sum([len(w) for w in S[k]]) + len(S[k]) - 1
if S_len[k] > bigger_len:
bigger_len = S_len[k]
for k in range(N):
print(' ' * (bigger_len - S_len[k])... | n = int(input())
while True:
s = [[] for k in range(N)]
s_len = [0 for k in range(N)]
bigger_len = 0
for k in range(N):
S[k] = input().split()
S_len[k] = sum([len(w) for w in S[k]]) + len(S[k]) - 1
if S_len[k] > bigger_len:
bigger_len = S_len[k]
for k in range(N):... |
def Final_Product(Check_list):
Prod = 1
for ele in Check_list:
Prod *= ele
return Prod
def Product_Matrix(Test_list):
Semi_Result = Final_Product(
[element for ele in Test_list for element in ele])
return Semi_Result
Test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
... | def final__product(Check_list):
prod = 1
for ele in Check_list:
prod *= ele
return Prod
def product__matrix(Test_list):
semi__result = final__product([element for ele in Test_list for element in ele])
return Semi_Result
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
print(product__matrix(... |
"""Utility functions"""
class BraceMessage(object):
"""Helper class that can be used to construct log messages with
the new {}-string formatting syntax.
NOTE: When using this helper class, one pays no signigicant
performance penalty since the actual formatting only happens when
(and if) the logge... | """Utility functions"""
class Bracemessage(object):
"""Helper class that can be used to construct log messages with
the new {}-string formatting syntax.
NOTE: When using this helper class, one pays no signigicant
performance penalty since the actual formatting only happens when
(and if) the logged... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.