content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
def isPalindrome(string):
if len(string) <= 1:
return True
else:
return string[0] == string[-1] and isPalindrome(string[1:-1])
userInput = input("Please enter a sequence to check if it is an palindrome: ")
answer = isPalindrome(userInput)
print("Is '" + userInput + "' an palindrome? " + str(answer)) | def is_palindrome(string):
if len(string) <= 1:
return True
else:
return string[0] == string[-1] and is_palindrome(string[1:-1])
user_input = input('Please enter a sequence to check if it is an palindrome: ')
answer = is_palindrome(userInput)
print("Is '" + userInput + "' an palindrome? " + str(answer)) |
N = int(input())
A = [int(n) for n in input().split()]
Aset = set(A)
m = (10**9+7)
o = {}
ans = []
for a in A:
o.setdefault(a, 0)
o[a] += 1
for i in range(len(Aset)-1):
for j in range(i+1, len(Aset)):
ans.append((A[i]^A[j])*o[A[i]]*o[A[j]])
print(sum(ans)/m)
| n = int(input())
a = [int(n) for n in input().split()]
aset = set(A)
m = 10 ** 9 + 7
o = {}
ans = []
for a in A:
o.setdefault(a, 0)
o[a] += 1
for i in range(len(Aset) - 1):
for j in range(i + 1, len(Aset)):
ans.append((A[i] ^ A[j]) * o[A[i]] * o[A[j]])
print(sum(ans) / m) |
# DOWNLOADER_MIDDLEWARES = {}
# DOWNLOADER_MIDDLEWARES.update({
# 'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware': None,
# 'scrapy_httpcache.downloadermiddlewares.httpcache.AsyncHttpCacheMiddleware': 900,
# })
HTTPCACHE_STORAGE = 'scrapy_httpcache.extensions.httpcache_storage.MongoDBCacheStorage'
HTTPCACHE_MONGODB_HOST = '127.0.0.1'
HTTPCACHE_MONGODB_PORT = 27017
HTTPCACHE_MONGODB_USERNAME = None
HTTPCACHE_MONGODB_PASSWORD = None
HTTPCACHE_MONGODB_AUTH_DB = None
HTTPCACHE_MONGODB_DB = 'cache_storage'
HTTPCACHE_MONGODB_COLL = 'cache'
HTTPCACHE_MONGODB_COLL_INDEX = [[('fingerprint', 1)]]
HTTPCACHE_MONGODB_CONNECTION_POOL_KWARGS = {}
BANNED_STORAGE = 'scrapy_httpcache.extensions.banned_storage.MongoBannedStorage'
BANNED_MONGODB_COLL = 'banned'
BANNED_MONGODB_COLL_INDEX = [[('fingerprint', 1)]]
REQUEST_ERROR_STORAGE = 'scrapy_httpcache.extensions.request_error_storage.MongoRequestErrorStorage'
REQUEST_ERROR_MONGODB_COLL = 'request_error'
REQUEST_ERROR_MONGODB_COLL_INDEX = [[('fingerprint', 1)]]
| httpcache_storage = 'scrapy_httpcache.extensions.httpcache_storage.MongoDBCacheStorage'
httpcache_mongodb_host = '127.0.0.1'
httpcache_mongodb_port = 27017
httpcache_mongodb_username = None
httpcache_mongodb_password = None
httpcache_mongodb_auth_db = None
httpcache_mongodb_db = 'cache_storage'
httpcache_mongodb_coll = 'cache'
httpcache_mongodb_coll_index = [[('fingerprint', 1)]]
httpcache_mongodb_connection_pool_kwargs = {}
banned_storage = 'scrapy_httpcache.extensions.banned_storage.MongoBannedStorage'
banned_mongodb_coll = 'banned'
banned_mongodb_coll_index = [[('fingerprint', 1)]]
request_error_storage = 'scrapy_httpcache.extensions.request_error_storage.MongoRequestErrorStorage'
request_error_mongodb_coll = 'request_error'
request_error_mongodb_coll_index = [[('fingerprint', 1)]] |
def flatten(aList):
myList = []
for el in aList:
if isinstance(el, list) or isinstance(el, tuple):
myList.extend(flatten(el))
else:
myList.append(el)
return myList
| def flatten(aList):
my_list = []
for el in aList:
if isinstance(el, list) or isinstance(el, tuple):
myList.extend(flatten(el))
else:
myList.append(el)
return myList |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def zlib():
if "zlib" not in native.existing_rules():
http_archive(
name = "zlib",
build_file = "//third_party/zlib:zlib.BUILD",
sha256 = "91844808532e5ce316b3c010929493c0244f3d37593afd6de04f71821d5136d9",
strip_prefix = "zlib-1.2.12",
url = "https://zlib.net/zlib-1.2.12.tar.gz",
)
| load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def zlib():
if 'zlib' not in native.existing_rules():
http_archive(name='zlib', build_file='//third_party/zlib:zlib.BUILD', sha256='91844808532e5ce316b3c010929493c0244f3d37593afd6de04f71821d5136d9', strip_prefix='zlib-1.2.12', url='https://zlib.net/zlib-1.2.12.tar.gz') |
class Sampler(object):
def __init__(self):
self._params = None
self._dim = None
self._iteration = 0
def setParameters(self, params):
self._params = params
self._dim = params.getStochasticDim()
def nextSamples(self, *args, **kws):
raise NotImplementedError()
def learnData(self, *args, **kws):
raise NotImplementedError()
def hasMoreSamples(self):
raise NotImplementedError()
| class Sampler(object):
def __init__(self):
self._params = None
self._dim = None
self._iteration = 0
def set_parameters(self, params):
self._params = params
self._dim = params.getStochasticDim()
def next_samples(self, *args, **kws):
raise not_implemented_error()
def learn_data(self, *args, **kws):
raise not_implemented_error()
def has_more_samples(self):
raise not_implemented_error() |
#
def calcula_investimento(inv, mes, tipo):
# seleciona tipo de investimento
# CDB
if tipo == 'CDB':
for i in range(1, mes + 1):
inv = inv * 1.013
if i % 6 == 0:
inv = inv * 1.012
# LCI
elif tipo == 'LCI':
inv = inv*1.016**(mes)
'''for i in range(1, mes + 1):
inv = inv * 1.016'''
# LCA
else:
for i in range(1, mes + 1):
inv = inv * 1.0145
if i % 4 == 0:
inv = inv * 1.01
return inv | def calcula_investimento(inv, mes, tipo):
if tipo == 'CDB':
for i in range(1, mes + 1):
inv = inv * 1.013
if i % 6 == 0:
inv = inv * 1.012
elif tipo == 'LCI':
inv = inv * 1.016 ** mes
'for i in range(1, mes + 1):\n inv = inv * 1.016'
else:
for i in range(1, mes + 1):
inv = inv * 1.0145
if i % 4 == 0:
inv = inv * 1.01
return inv |
#!/usr/bin/env python3
def collatz(x):
if x <= 0:
raise ValueError("Collatz has become 0")
if (x % 2) == 0:
return x/2
else:
return 3*x+1
if __name__ == "__main__":
number = 10
print("Ausgangszahl: ", number)
iteration = 0
while True:
number = collatz(number)
iteration += 1
print("Iteration ", iteration, ": ", number)
input("")
| def collatz(x):
if x <= 0:
raise value_error('Collatz has become 0')
if x % 2 == 0:
return x / 2
else:
return 3 * x + 1
if __name__ == '__main__':
number = 10
print('Ausgangszahl: ', number)
iteration = 0
while True:
number = collatz(number)
iteration += 1
print('Iteration ', iteration, ': ', number)
input('') |
'''
256 definitions cause LOAD_NAME and LOAD_CONST to both require EXTENDED_ARGS.
Generated with: `for i in range(0, 0xff, 0x10): print(*[f'x{j:02x}=0x{j:02x}' for j in range(i, i+0x10)], sep='; ')`
'''
x00=0x00; x01=0x01; x02=0x02; x03=0x03; x04=0x04; x05=0x05; x06=0x06; x07=0x07; x08=0x08; x09=0x09; x0a=0x0a; x0b=0x0b; x0c=0x0c; x0d=0x0d; x0e=0x0e; x0f=0x0f
x10=0x10; x11=0x11; x12=0x12; x13=0x13; x14=0x14; x15=0x15; x16=0x16; x17=0x17; x18=0x18; x19=0x19; x1a=0x1a; x1b=0x1b; x1c=0x1c; x1d=0x1d; x1e=0x1e; x1f=0x1f
x20=0x20; x21=0x21; x22=0x22; x23=0x23; x24=0x24; x25=0x25; x26=0x26; x27=0x27; x28=0x28; x29=0x29; x2a=0x2a; x2b=0x2b; x2c=0x2c; x2d=0x2d; x2e=0x2e; x2f=0x2f
x30=0x30; x31=0x31; x32=0x32; x33=0x33; x34=0x34; x35=0x35; x36=0x36; x37=0x37; x38=0x38; x39=0x39; x3a=0x3a; x3b=0x3b; x3c=0x3c; x3d=0x3d; x3e=0x3e; x3f=0x3f
x40=0x40; x41=0x41; x42=0x42; x43=0x43; x44=0x44; x45=0x45; x46=0x46; x47=0x47; x48=0x48; x49=0x49; x4a=0x4a; x4b=0x4b; x4c=0x4c; x4d=0x4d; x4e=0x4e; x4f=0x4f
x50=0x50; x51=0x51; x52=0x52; x53=0x53; x54=0x54; x55=0x55; x56=0x56; x57=0x57; x58=0x58; x59=0x59; x5a=0x5a; x5b=0x5b; x5c=0x5c; x5d=0x5d; x5e=0x5e; x5f=0x5f
x60=0x60; x61=0x61; x62=0x62; x63=0x63; x64=0x64; x65=0x65; x66=0x66; x67=0x67; x68=0x68; x69=0x69; x6a=0x6a; x6b=0x6b; x6c=0x6c; x6d=0x6d; x6e=0x6e; x6f=0x6f
x70=0x70; x71=0x71; x72=0x72; x73=0x73; x74=0x74; x75=0x75; x76=0x76; x77=0x77; x78=0x78; x79=0x79; x7a=0x7a; x7b=0x7b; x7c=0x7c; x7d=0x7d; x7e=0x7e; x7f=0x7f
x80=0x80; x81=0x81; x82=0x82; x83=0x83; x84=0x84; x85=0x85; x86=0x86; x87=0x87; x88=0x88; x89=0x89; x8a=0x8a; x8b=0x8b; x8c=0x8c; x8d=0x8d; x8e=0x8e; x8f=0x8f
x90=0x90; x91=0x91; x92=0x92; x93=0x93; x94=0x94; x95=0x95; x96=0x96; x97=0x97; x98=0x98; x99=0x99; x9a=0x9a; x9b=0x9b; x9c=0x9c; x9d=0x9d; x9e=0x9e; x9f=0x9f
xa0=0xa0; xa1=0xa1; xa2=0xa2; xa3=0xa3; xa4=0xa4; xa5=0xa5; xa6=0xa6; xa7=0xa7; xa8=0xa8; xa9=0xa9; xaa=0xaa; xab=0xab; xac=0xac; xad=0xad; xae=0xae; xaf=0xaf
xb0=0xb0; xb1=0xb1; xb2=0xb2; xb3=0xb3; xb4=0xb4; xb5=0xb5; xb6=0xb6; xb7=0xb7; xb8=0xb8; xb9=0xb9; xba=0xba; xbb=0xbb; xbc=0xbc; xbd=0xbd; xbe=0xbe; xbf=0xbf
xc0=0xc0; xc1=0xc1; xc2=0xc2; xc3=0xc3; xc4=0xc4; xc5=0xc5; xc6=0xc6; xc7=0xc7; xc8=0xc8; xc9=0xc9; xca=0xca; xcb=0xcb; xcc=0xcc; xcd=0xcd; xce=0xce; xcf=0xcf
xd0=0xd0; xd1=0xd1; xd2=0xd2; xd3=0xd3; xd4=0xd4; xd5=0xd5; xd6=0xd6; xd7=0xd7; xd8=0xd8; xd9=0xd9; xda=0xda; xdb=0xdb; xdc=0xdc; xdd=0xdd; xde=0xde; xdf=0xdf
xe0=0xe0; xe1=0xe1; xe2=0xe2; xe3=0xe3; xe4=0xe4; xe5=0xe5; xe6=0xe6; xe7=0xe7; xe8=0xe8; xe9=0xe9; xea=0xea; xeb=0xeb; xec=0xec; xed=0xed; xee=0xee; xef=0xef
xf0=0xf0; xf1=0xf1; xf2=0xf2; xf3=0xf3; xf4=0xf4; xf5=0xf5; xf6=0xf6; xf7=0xf7; xf8=0xf8; xf9=0xf9; xfa=0xfa; xfb=0xfb; xfc=0xfc; xfd=0xfd; xfe=0xfe; xff=0xff
cond = False
for i in range(2):
if i:
continue
def main(): pass
if __name__ == '__main__': main()
| """
256 definitions cause LOAD_NAME and LOAD_CONST to both require EXTENDED_ARGS.
Generated with: `for i in range(0, 0xff, 0x10): print(*[f'x{j:02x}=0x{j:02x}' for j in range(i, i+0x10)], sep='; ')`
"""
x00 = 0
x01 = 1
x02 = 2
x03 = 3
x04 = 4
x05 = 5
x06 = 6
x07 = 7
x08 = 8
x09 = 9
x0a = 10
x0b = 11
x0c = 12
x0d = 13
x0e = 14
x0f = 15
x10 = 16
x11 = 17
x12 = 18
x13 = 19
x14 = 20
x15 = 21
x16 = 22
x17 = 23
x18 = 24
x19 = 25
x1a = 26
x1b = 27
x1c = 28
x1d = 29
x1e = 30
x1f = 31
x20 = 32
x21 = 33
x22 = 34
x23 = 35
x24 = 36
x25 = 37
x26 = 38
x27 = 39
x28 = 40
x29 = 41
x2a = 42
x2b = 43
x2c = 44
x2d = 45
x2e = 46
x2f = 47
x30 = 48
x31 = 49
x32 = 50
x33 = 51
x34 = 52
x35 = 53
x36 = 54
x37 = 55
x38 = 56
x39 = 57
x3a = 58
x3b = 59
x3c = 60
x3d = 61
x3e = 62
x3f = 63
x40 = 64
x41 = 65
x42 = 66
x43 = 67
x44 = 68
x45 = 69
x46 = 70
x47 = 71
x48 = 72
x49 = 73
x4a = 74
x4b = 75
x4c = 76
x4d = 77
x4e = 78
x4f = 79
x50 = 80
x51 = 81
x52 = 82
x53 = 83
x54 = 84
x55 = 85
x56 = 86
x57 = 87
x58 = 88
x59 = 89
x5a = 90
x5b = 91
x5c = 92
x5d = 93
x5e = 94
x5f = 95
x60 = 96
x61 = 97
x62 = 98
x63 = 99
x64 = 100
x65 = 101
x66 = 102
x67 = 103
x68 = 104
x69 = 105
x6a = 106
x6b = 107
x6c = 108
x6d = 109
x6e = 110
x6f = 111
x70 = 112
x71 = 113
x72 = 114
x73 = 115
x74 = 116
x75 = 117
x76 = 118
x77 = 119
x78 = 120
x79 = 121
x7a = 122
x7b = 123
x7c = 124
x7d = 125
x7e = 126
x7f = 127
x80 = 128
x81 = 129
x82 = 130
x83 = 131
x84 = 132
x85 = 133
x86 = 134
x87 = 135
x88 = 136
x89 = 137
x8a = 138
x8b = 139
x8c = 140
x8d = 141
x8e = 142
x8f = 143
x90 = 144
x91 = 145
x92 = 146
x93 = 147
x94 = 148
x95 = 149
x96 = 150
x97 = 151
x98 = 152
x99 = 153
x9a = 154
x9b = 155
x9c = 156
x9d = 157
x9e = 158
x9f = 159
xa0 = 160
xa1 = 161
xa2 = 162
xa3 = 163
xa4 = 164
xa5 = 165
xa6 = 166
xa7 = 167
xa8 = 168
xa9 = 169
xaa = 170
xab = 171
xac = 172
xad = 173
xae = 174
xaf = 175
xb0 = 176
xb1 = 177
xb2 = 178
xb3 = 179
xb4 = 180
xb5 = 181
xb6 = 182
xb7 = 183
xb8 = 184
xb9 = 185
xba = 186
xbb = 187
xbc = 188
xbd = 189
xbe = 190
xbf = 191
xc0 = 192
xc1 = 193
xc2 = 194
xc3 = 195
xc4 = 196
xc5 = 197
xc6 = 198
xc7 = 199
xc8 = 200
xc9 = 201
xca = 202
xcb = 203
xcc = 204
xcd = 205
xce = 206
xcf = 207
xd0 = 208
xd1 = 209
xd2 = 210
xd3 = 211
xd4 = 212
xd5 = 213
xd6 = 214
xd7 = 215
xd8 = 216
xd9 = 217
xda = 218
xdb = 219
xdc = 220
xdd = 221
xde = 222
xdf = 223
xe0 = 224
xe1 = 225
xe2 = 226
xe3 = 227
xe4 = 228
xe5 = 229
xe6 = 230
xe7 = 231
xe8 = 232
xe9 = 233
xea = 234
xeb = 235
xec = 236
xed = 237
xee = 238
xef = 239
xf0 = 240
xf1 = 241
xf2 = 242
xf3 = 243
xf4 = 244
xf5 = 245
xf6 = 246
xf7 = 247
xf8 = 248
xf9 = 249
xfa = 250
xfb = 251
xfc = 252
xfd = 253
xfe = 254
xff = 255
cond = False
for i in range(2):
if i:
continue
def main():
pass
if __name__ == '__main__':
main() |
# This function tells a user whether or not a number is prime
def isPrime(number):
# this will tell us if the number is prime, set to True automatically
# We will set to False if the number is divisible by any number less than it
number_is_prime = True
# loop over all numbers less than the input number
for i in range(2, number):
# calculate the remainder
remainder = number % i
# if the remainder is 0, then the number is not prime by definition!
if remainder == 0:
number_is_prime = False
# return result to the user
return number_is_prime
| def is_prime(number):
number_is_prime = True
for i in range(2, number):
remainder = number % i
if remainder == 0:
number_is_prime = False
return number_is_prime |
class Solution:
def longestCommonSubstring(self, a, b):
matrix = [[0 for _ in range(len(b))] for _ in range((len(a)))]
z = 0
ret = []
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
if i == 0 or j == 0:
matrix[i][j] = 1
else:
matrix[i][j] = matrix[i - 1][j - 1] + 1
if matrix[i][j] > z:
z = matrix[i][j]
ret = [a[i - z + 1: i + 1]]
elif matrix[i][j] == z:
ret.append(a[i - z + 1: i + 1])
else:
matrix[i][j] = 0
return ret
sol = Solution()
a = 'caba'
b = 'caba'
res = sol.longestCommonSubstring(a, b)
print(res)
a = 'wallacetambemsechamafelipecujosobrenomeficafranciscoecardosotambem'
b = 'euwallacefelipefranciscocardososoucientista'
res = sol.longestCommonSubstring(a, b)
print(res)
| class Solution:
def longest_common_substring(self, a, b):
matrix = [[0 for _ in range(len(b))] for _ in range(len(a))]
z = 0
ret = []
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
if i == 0 or j == 0:
matrix[i][j] = 1
else:
matrix[i][j] = matrix[i - 1][j - 1] + 1
if matrix[i][j] > z:
z = matrix[i][j]
ret = [a[i - z + 1:i + 1]]
elif matrix[i][j] == z:
ret.append(a[i - z + 1:i + 1])
else:
matrix[i][j] = 0
return ret
sol = solution()
a = 'caba'
b = 'caba'
res = sol.longestCommonSubstring(a, b)
print(res)
a = 'wallacetambemsechamafelipecujosobrenomeficafranciscoecardosotambem'
b = 'euwallacefelipefranciscocardososoucientista'
res = sol.longestCommonSubstring(a, b)
print(res) |
# Copyright (c) 2020 The Khronos Group Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def _split_counter_from_name(str):
if len(str) > 0 and not str[-1].isdigit():
return str, None
i = len(str)
while i > 0:
if not str[i-1].isdigit():
return str[:i], int(str[i:])
i -= 1
return None, int(str)
def generate_tensor_names_from_op_type(graph, keep_io_names=False):
used_names = set()
if keep_io_names:
used_names.update(tensor.name for tensor in graph.inputs if tensor.name is not None)
used_names.update(tensor.name for tensor in graph.outputs if tensor.name is not None)
op_counts = {}
for op in graph.operations:
for tensor in op.outputs:
if keep_io_names and tensor.name is not None and (tensor in graph.inputs or tensor in graph.outputs):
continue
idx = op_counts.get(op.type, 0) + 1
while op.type + str(idx) in used_names:
idx += 1
op_counts[op.type] = idx
tensor.name = op.type + str(idx)
for tensor in graph.tensors:
if tensor.producer is None:
tensor.name = None
def generate_missing_tensor_names_from_op_type(graph):
counters = {}
for tensor in graph.tensors:
if tensor.name is not None:
name, count = _split_counter_from_name(tensor.name)
if name is not None and count is not None:
counters[name] = max(counters.get(name, 0), count)
for tensor in graph.tensors:
if tensor.name is None and tensor.producer is not None:
op = tensor.producer
idx = counters.get(op.type, 0) + 1
counters[op.type] = idx
tensor.name = op.type + str(idx)
def generate_op_names_from_op_type(graph):
op_counts = {}
for op in graph.operations:
idx = op_counts.get(op.type, 0) + 1
op_counts[op.type] = idx
op.name = op.type + str(idx)
def replace_tensor_in_graph_inputs(graph, old_tensor, new_tensor):
graph.inputs = [new_tensor if t is old_tensor else t for t in graph.inputs]
def replace_tensor_in_graph_outputs(graph, old_tensor, new_tensor):
graph.outputs = [new_tensor if t is old_tensor else t for t in graph.outputs]
def replace_tensor_in_consumers(graph, old_tensor, new_tensor):
for consumer in list(old_tensor.consumers): # copy list to avoid changes during iteration
sequence = tuple if isinstance(consumer.inputs, tuple) else list
consumer.inputs = sequence(new_tensor if t is old_tensor else t for t in consumer.inputs)
replace_tensor_in_graph_outputs(graph, old_tensor, new_tensor)
def replace_tensor_in_producers(graph, old_tensor, new_tensor):
for producer in list(old_tensor.producers): # copy list to avoid changes during iteration
sequence = tuple if isinstance(producer.outputs, tuple) else list
producer.outputs = sequence(new_tensor if t is old_tensor else t for t in producer.outputs)
replace_tensor_in_graph_inputs(graph, old_tensor, new_tensor)
def bypass_and_remove(graph, op, remove_input_not_output=False):
assert len(op.outputs) == 1 and len(op.inputs) == 1
op_input = op.input
op_output = op.output
graph.remove_operation(op, unlink=True)
if remove_input_not_output:
replace_tensor_in_consumers(graph, op_input, op_output)
replace_tensor_in_producers(graph, op_input, op_output)
graph.remove_tensor(op_input)
else:
replace_tensor_in_consumers(graph, op_output, op_input)
replace_tensor_in_producers(graph, op_output, op_input)
graph.remove_tensor(op_output)
def replace_chain(graph, types, func, allow_forks=False):
def _match_type(type, template):
return type in template if isinstance(template, set) else type == template
def _match_link(op, template, is_last):
return _match_type(op.type, template) and (len(op.outputs) == 1 or is_last)
def _match_chain(op, types, allow_forks):
if not _match_link(op, types[0], is_last=len(types) == 1):
return None
chain = [op]
tensor = op.output
for idx, type in enumerate(types[1:]):
is_last = idx + 1 == len(types) - 1
if not allow_forks and len(tensor.consumers) > 1:
return None
op = next((consumer for consumer in tensor.consumers if _match_link(consumer, type, is_last)), None)
if op is None:
return None
chain.append(op)
if not is_last:
tensor = op.output
return chain
changed = False
i = 0
while i < len(graph.operations):
count = len(graph.operations)
chain = _match_chain(graph.operations[i], types, allow_forks)
if chain is not None and func(*chain) is not False:
k = i
while graph.operations[k] is not chain[-1]:
k += 1
for j in range(count, len(graph.operations)):
graph.move_operation(j, k)
k += 1
offs = len(chain) - 1
while offs > 0 and len(chain[offs - 1].output.consumers) == 1:
offs -= 1
interns = [op.output for op in chain[offs:-1]]
graph.remove_operations(chain[offs:], unlink=True)
graph.remove_tensors(interns)
changed = True
else:
i += 1
return changed
def remove_unreachable(graph):
visited = {tensor.producer for tensor in graph.outputs}
queue = list(visited)
k = 0
while k < len(queue):
op = queue[k]
k += 1
for tensor in op.inputs:
if tensor.producer is not None and tensor.producer not in visited and \
(tensor not in graph.inputs or len(tensor.producer.inputs) == 0):
visited.add(tensor.producer)
queue.append(tensor.producer)
graph.remove_operations({op for op in graph.operations if op not in visited}, unlink=True)
graph.remove_tensors({tensor for tensor in graph.tensors
if len(tensor.producers) == 0 and len(tensor.consumers) == 0
and tensor not in graph.inputs and tensor not in graph.outputs})
| def _split_counter_from_name(str):
if len(str) > 0 and (not str[-1].isdigit()):
return (str, None)
i = len(str)
while i > 0:
if not str[i - 1].isdigit():
return (str[:i], int(str[i:]))
i -= 1
return (None, int(str))
def generate_tensor_names_from_op_type(graph, keep_io_names=False):
used_names = set()
if keep_io_names:
used_names.update((tensor.name for tensor in graph.inputs if tensor.name is not None))
used_names.update((tensor.name for tensor in graph.outputs if tensor.name is not None))
op_counts = {}
for op in graph.operations:
for tensor in op.outputs:
if keep_io_names and tensor.name is not None and (tensor in graph.inputs or tensor in graph.outputs):
continue
idx = op_counts.get(op.type, 0) + 1
while op.type + str(idx) in used_names:
idx += 1
op_counts[op.type] = idx
tensor.name = op.type + str(idx)
for tensor in graph.tensors:
if tensor.producer is None:
tensor.name = None
def generate_missing_tensor_names_from_op_type(graph):
counters = {}
for tensor in graph.tensors:
if tensor.name is not None:
(name, count) = _split_counter_from_name(tensor.name)
if name is not None and count is not None:
counters[name] = max(counters.get(name, 0), count)
for tensor in graph.tensors:
if tensor.name is None and tensor.producer is not None:
op = tensor.producer
idx = counters.get(op.type, 0) + 1
counters[op.type] = idx
tensor.name = op.type + str(idx)
def generate_op_names_from_op_type(graph):
op_counts = {}
for op in graph.operations:
idx = op_counts.get(op.type, 0) + 1
op_counts[op.type] = idx
op.name = op.type + str(idx)
def replace_tensor_in_graph_inputs(graph, old_tensor, new_tensor):
graph.inputs = [new_tensor if t is old_tensor else t for t in graph.inputs]
def replace_tensor_in_graph_outputs(graph, old_tensor, new_tensor):
graph.outputs = [new_tensor if t is old_tensor else t for t in graph.outputs]
def replace_tensor_in_consumers(graph, old_tensor, new_tensor):
for consumer in list(old_tensor.consumers):
sequence = tuple if isinstance(consumer.inputs, tuple) else list
consumer.inputs = sequence((new_tensor if t is old_tensor else t for t in consumer.inputs))
replace_tensor_in_graph_outputs(graph, old_tensor, new_tensor)
def replace_tensor_in_producers(graph, old_tensor, new_tensor):
for producer in list(old_tensor.producers):
sequence = tuple if isinstance(producer.outputs, tuple) else list
producer.outputs = sequence((new_tensor if t is old_tensor else t for t in producer.outputs))
replace_tensor_in_graph_inputs(graph, old_tensor, new_tensor)
def bypass_and_remove(graph, op, remove_input_not_output=False):
assert len(op.outputs) == 1 and len(op.inputs) == 1
op_input = op.input
op_output = op.output
graph.remove_operation(op, unlink=True)
if remove_input_not_output:
replace_tensor_in_consumers(graph, op_input, op_output)
replace_tensor_in_producers(graph, op_input, op_output)
graph.remove_tensor(op_input)
else:
replace_tensor_in_consumers(graph, op_output, op_input)
replace_tensor_in_producers(graph, op_output, op_input)
graph.remove_tensor(op_output)
def replace_chain(graph, types, func, allow_forks=False):
def _match_type(type, template):
return type in template if isinstance(template, set) else type == template
def _match_link(op, template, is_last):
return _match_type(op.type, template) and (len(op.outputs) == 1 or is_last)
def _match_chain(op, types, allow_forks):
if not _match_link(op, types[0], is_last=len(types) == 1):
return None
chain = [op]
tensor = op.output
for (idx, type) in enumerate(types[1:]):
is_last = idx + 1 == len(types) - 1
if not allow_forks and len(tensor.consumers) > 1:
return None
op = next((consumer for consumer in tensor.consumers if _match_link(consumer, type, is_last)), None)
if op is None:
return None
chain.append(op)
if not is_last:
tensor = op.output
return chain
changed = False
i = 0
while i < len(graph.operations):
count = len(graph.operations)
chain = _match_chain(graph.operations[i], types, allow_forks)
if chain is not None and func(*chain) is not False:
k = i
while graph.operations[k] is not chain[-1]:
k += 1
for j in range(count, len(graph.operations)):
graph.move_operation(j, k)
k += 1
offs = len(chain) - 1
while offs > 0 and len(chain[offs - 1].output.consumers) == 1:
offs -= 1
interns = [op.output for op in chain[offs:-1]]
graph.remove_operations(chain[offs:], unlink=True)
graph.remove_tensors(interns)
changed = True
else:
i += 1
return changed
def remove_unreachable(graph):
visited = {tensor.producer for tensor in graph.outputs}
queue = list(visited)
k = 0
while k < len(queue):
op = queue[k]
k += 1
for tensor in op.inputs:
if tensor.producer is not None and tensor.producer not in visited and (tensor not in graph.inputs or len(tensor.producer.inputs) == 0):
visited.add(tensor.producer)
queue.append(tensor.producer)
graph.remove_operations({op for op in graph.operations if op not in visited}, unlink=True)
graph.remove_tensors({tensor for tensor in graph.tensors if len(tensor.producers) == 0 and len(tensor.consumers) == 0 and (tensor not in graph.inputs) and (tensor not in graph.outputs)}) |
sigla = input('Digite uma das siglas: SP / RJ / MG: ')
if sigla == 'RJ' or sigla == 'rj':
print('Carioca')
elif sigla == 'SP' or sigla == 'sp':
print('Paulista')
elif sigla == 'MG' or sigla == 'mg':
print('Mineiro')
else:
print('Outro estado') | sigla = input('Digite uma das siglas: SP / RJ / MG: ')
if sigla == 'RJ' or sigla == 'rj':
print('Carioca')
elif sigla == 'SP' or sigla == 'sp':
print('Paulista')
elif sigla == 'MG' or sigla == 'mg':
print('Mineiro')
else:
print('Outro estado') |
# Copyright (c) 2019 Ezybaas by Bhavik Shah.
# CTO @ Susthitsoft Technologies Private Limited.
# All rights reserved.
# Please see the LICENSE.txt included as part of this package.
# EZYBAAS RELEASE CONFIG
EZYBAAS_RELEASE_NAME = 'EzyBaaS'
EZYBAAS_RELEASE_AUTHOR = 'Bhavik Shah CTO @ SusthitSoft Technologies'
EZYBAAS_RELEASE_VERSION = '0.1.4'
EZYBAAS_RELEASE_DATE = '2019-07-20'
EZYBAAS_RELEASE_NOTES = 'https://github.com/bhavik1st/ezybaas'
EZYBAAS_RELEASE_STANDALONE = True
EZYBAAS_RELEASE_LICENSE = 'https://github.com/bhavik1st/ezybaas'
EZYBAAS_SWAGGER_ENABLED = True
# EZYBAAS OPERATIONAL CONFIG
BAAS_NAME = 'ezybaas'
SERIALIZERS_FILE_NAME = 'api'
VIEWS_FILE_NAME = 'api'
URLS_FILE_NAME = 'urls'
MODELS_FILE_NAME = 'models'
TESTS_FILE_NAME = 'tests'
| ezybaas_release_name = 'EzyBaaS'
ezybaas_release_author = 'Bhavik Shah CTO @ SusthitSoft Technologies'
ezybaas_release_version = '0.1.4'
ezybaas_release_date = '2019-07-20'
ezybaas_release_notes = 'https://github.com/bhavik1st/ezybaas'
ezybaas_release_standalone = True
ezybaas_release_license = 'https://github.com/bhavik1st/ezybaas'
ezybaas_swagger_enabled = True
baas_name = 'ezybaas'
serializers_file_name = 'api'
views_file_name = 'api'
urls_file_name = 'urls'
models_file_name = 'models'
tests_file_name = 'tests' |
#Oskar Svedlund
#TEINF-20
#2021-09-20
#For i For loop
for i in range(1,10):
for j in range(1,10):
print(i*j, end="\t")
print()
| for i in range(1, 10):
for j in range(1, 10):
print(i * j, end='\t')
print() |
#!/usr/bin/env python
'''
Copyright (C) 2019, WAFW00F Developers.
See the LICENSE file for copying permission.
'''
NAME = 'StackPath (StackPath)'
def is_waf(self):
schemes = [
self.matchContent(r"This website is using a security service to protect itself"),
self.matchContent(r'You performed an action that triggered the service and blocked your request')
]
if all(i for i in schemes):
return True
return False | """
Copyright (C) 2019, WAFW00F Developers.
See the LICENSE file for copying permission.
"""
name = 'StackPath (StackPath)'
def is_waf(self):
schemes = [self.matchContent('This website is using a security service to protect itself'), self.matchContent('You performed an action that triggered the service and blocked your request')]
if all((i for i in schemes)):
return True
return False |
content = '''
<script>
function createimagemodal(path,cap) {
var html = '<div id="modalWindow1" class="modal" data-keyboard="false" data-backdrop="static">\
<span class="close1" onclick=deletemodal("modalWindow1") data-dismiss="modal">×</span>\
<img class="modal-content" id="img01" style="max-height: -webkit-fill-available; width: auto;"></img>\
<div id="caption"></div>\
</div>';
$("#imagemodal").html(html);
$("#modalWindow1").modal();
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
modalImg.src = path;
captionText.innerHTML = cap;
}
</script>
'''
| content = '\n <script>\n function createimagemodal(path,cap) {\n var html = \'<div id="modalWindow1" class="modal" data-keyboard="false" data-backdrop="static"> <span class="close1" onclick=deletemodal("modalWindow1") data-dismiss="modal">×</span> <img class="modal-content" id="img01" style="max-height: -webkit-fill-available; width: auto;"></img> <div id="caption"></div> </div>\';\n $("#imagemodal").html(html);\n $("#modalWindow1").modal();\n var modalImg = document.getElementById("img01");\n var captionText = document.getElementById("caption");\n modalImg.src = path;\n captionText.innerHTML = cap;\n }\n </script>\n ' |
a = int(input('Digite o primeiro segmento '))
b = int(input('Digite o segundo segmento: '))
c = int(input('Digite o terceiro segmento '))
if (b - c) < a < (b + c) and (a - c) < b < (a + c) and (a - b) < c < (a + b):
print('Formam um triangulo')
else:
print('Nao formam um triangulo') | a = int(input('Digite o primeiro segmento '))
b = int(input('Digite o segundo segmento: '))
c = int(input('Digite o terceiro segmento '))
if b - c < a < b + c and a - c < b < a + c and (a - b < c < a + b):
print('Formam um triangulo')
else:
print('Nao formam um triangulo') |
SECTION_OFFSET_START = 0x0
SECTION_ADDRESS_START = 0x48
SECTION_SIZE_START = 0x90
BSS_START = 0xD8
BSS_SIZE = 0xDC
TEXT_SECTION_COUNT = 7
DATA_SECTION_COUNT = 11
SECTION_COUNT = TEXT_SECTION_COUNT + DATA_SECTION_COUNT
PATCH_SECTION = 3
ORIGINAL_DOL_END = 0x804DEC00
def word(data, offset):
return sum(data[offset + i] << (24 - i * 8) for i in range(4))
def word_to_bytes(word):
return bytes((word >> (24 - i * 8)) & 0xFF for i in range(4))
def get_dol_end(data):
def get_section_end(index):
address = word(data, SECTION_ADDRESS_START + index * 4)
size = word(data, SECTION_SIZE_START + index * 4)
return address + size
bss_end = word(data, BSS_START) + word(data, BSS_SIZE)
return max(bss_end, *(get_section_end(i) for i in range(SECTION_COUNT)))
def address_to_offset(data, value):
for i in range(0, SECTION_COUNT):
address = word(data, SECTION_ADDRESS_START + i * 4)
size = word(data, SECTION_SIZE_START + i * 4)
if address <= value < address + size:
offset = word(data, SECTION_OFFSET_START + i * 4)
return value - address + offset
def patch_load_imm32(data, address, reg, imm):
lis = 0x3C000000 | (reg << 21) | (imm >> 16)
ori = 0x60000000 | (reg << 21) | (reg << 16) | (imm & 0xFFFF)
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(lis)
data[offset+4:offset+8] = word_to_bytes(ori)
def patch_load_imm32_split(data, lis_addr, ori_addr, reg, imm):
lis = 0x3C000000 | (reg << 21) | (imm >> 16)
ori = 0x60000000 | (reg << 21) | (reg << 16) | (imm & 0xFFFF)
lis_offset = address_to_offset(data, lis_addr)
ori_offset = address_to_offset(data, ori_addr)
data[lis_offset:lis_offset+4] = word_to_bytes(lis)
data[ori_offset:ori_offset+4] = word_to_bytes(ori)
def patch_branch(data, address, target):
delta = target - address
if delta < 0:
# Two's complement
delta = ~(-delta) + 1
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(0x48000000 | (delta & 0x3FFFFFC))
def patch_stack_and_heap(data):
delta = get_dol_end(data) - ORIGINAL_DOL_END
print(f"DOL virtual size delta: 0x{delta:X} bytes")
patch_load_imm32(data, 0x80343094, 3, 0x804F0C00 + delta)
patch_load_imm32(data, 0x803430CC, 3, 0x804EEC00 + delta)
patch_load_imm32(data, 0x8034AC78, 0, 0x804EEC00 + delta)
patch_load_imm32_split(data, 0x8034AC80, 0x8034AC88, 0, 0x804DEC00 + delta)
patch_load_imm32_split(data, 0x802256D0, 0x802256D8, 3, 0x804DEC00 + delta)
patch_load_imm32_split(data, 0x8022570C, 0x80225714, 4, 0x804EEC00 + delta)
patch_load_imm32_split(data, 0x80225718, 0x80225720, 5, 0x804DEC00 + delta)
# Stack
patch_load_imm32(data, 0x80005340, 1, 0x804EEC00 + delta)
def apply_hooks(data):
hooks_offset = word(data, SECTION_OFFSET_START + PATCH_SECTION * 4)
hooks_address = word(data, SECTION_ADDRESS_START + PATCH_SECTION * 4)
hooks_size = word(data, SECTION_SIZE_START + PATCH_SECTION * 4)
for i in range(hooks_size // 8):
offset = hooks_offset + i * 8
original = word(data, offset)
hook = word(data, offset + 4)
# Replace the patch data with the overwritten instruction + branch back
# to the original
original_offset = address_to_offset(data, original)
data[offset:offset+4] = data[original_offset:original_offset+4]
patch_branch(data, hooks_address + i * 8 + 4, original + 4)
patch_branch(data, original, hook)
print(f"Hook {original:08X} -> {hook:08X}")
def apply_extra_patches(data):
with open("patches") as f:
while True:
line = f.readline()
if not line:
return
if line.find("#") != -1:
line = line[:line.find("#")]
if len(line.split()) == 0:
continue
address, word = [int(x, 16) for x in line.split()]
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(word)
print(f"Patch {address:08X} -> {word:08X}")
def main():
with open("bin/sys/main.dol", "rb") as f:
data = bytearray(f.read())
patch_stack_and_heap(data)
apply_hooks(data)
apply_extra_patches(data)
with open("bin/sys/main.dol", "wb") as f:
f.write(data)
if __name__ == "__main__":
main() | section_offset_start = 0
section_address_start = 72
section_size_start = 144
bss_start = 216
bss_size = 220
text_section_count = 7
data_section_count = 11
section_count = TEXT_SECTION_COUNT + DATA_SECTION_COUNT
patch_section = 3
original_dol_end = 2152590336
def word(data, offset):
return sum((data[offset + i] << 24 - i * 8 for i in range(4)))
def word_to_bytes(word):
return bytes((word >> 24 - i * 8 & 255 for i in range(4)))
def get_dol_end(data):
def get_section_end(index):
address = word(data, SECTION_ADDRESS_START + index * 4)
size = word(data, SECTION_SIZE_START + index * 4)
return address + size
bss_end = word(data, BSS_START) + word(data, BSS_SIZE)
return max(bss_end, *(get_section_end(i) for i in range(SECTION_COUNT)))
def address_to_offset(data, value):
for i in range(0, SECTION_COUNT):
address = word(data, SECTION_ADDRESS_START + i * 4)
size = word(data, SECTION_SIZE_START + i * 4)
if address <= value < address + size:
offset = word(data, SECTION_OFFSET_START + i * 4)
return value - address + offset
def patch_load_imm32(data, address, reg, imm):
lis = 1006632960 | reg << 21 | imm >> 16
ori = 1610612736 | reg << 21 | reg << 16 | imm & 65535
offset = address_to_offset(data, address)
data[offset:offset + 4] = word_to_bytes(lis)
data[offset + 4:offset + 8] = word_to_bytes(ori)
def patch_load_imm32_split(data, lis_addr, ori_addr, reg, imm):
lis = 1006632960 | reg << 21 | imm >> 16
ori = 1610612736 | reg << 21 | reg << 16 | imm & 65535
lis_offset = address_to_offset(data, lis_addr)
ori_offset = address_to_offset(data, ori_addr)
data[lis_offset:lis_offset + 4] = word_to_bytes(lis)
data[ori_offset:ori_offset + 4] = word_to_bytes(ori)
def patch_branch(data, address, target):
delta = target - address
if delta < 0:
delta = ~-delta + 1
offset = address_to_offset(data, address)
data[offset:offset + 4] = word_to_bytes(1207959552 | delta & 67108860)
def patch_stack_and_heap(data):
delta = get_dol_end(data) - ORIGINAL_DOL_END
print(f'DOL virtual size delta: 0x{delta:X} bytes')
patch_load_imm32(data, 2150903956, 3, 2152664064 + delta)
patch_load_imm32(data, 2150904012, 3, 2152655872 + delta)
patch_load_imm32(data, 2150935672, 0, 2152655872 + delta)
patch_load_imm32_split(data, 2150935680, 2150935688, 0, 2152590336 + delta)
patch_load_imm32_split(data, 2149734096, 2149734104, 3, 2152590336 + delta)
patch_load_imm32_split(data, 2149734156, 2149734164, 4, 2152655872 + delta)
patch_load_imm32_split(data, 2149734168, 2149734176, 5, 2152590336 + delta)
patch_load_imm32(data, 2147504960, 1, 2152655872 + delta)
def apply_hooks(data):
hooks_offset = word(data, SECTION_OFFSET_START + PATCH_SECTION * 4)
hooks_address = word(data, SECTION_ADDRESS_START + PATCH_SECTION * 4)
hooks_size = word(data, SECTION_SIZE_START + PATCH_SECTION * 4)
for i in range(hooks_size // 8):
offset = hooks_offset + i * 8
original = word(data, offset)
hook = word(data, offset + 4)
original_offset = address_to_offset(data, original)
data[offset:offset + 4] = data[original_offset:original_offset + 4]
patch_branch(data, hooks_address + i * 8 + 4, original + 4)
patch_branch(data, original, hook)
print(f'Hook {original:08X} -> {hook:08X}')
def apply_extra_patches(data):
with open('patches') as f:
while True:
line = f.readline()
if not line:
return
if line.find('#') != -1:
line = line[:line.find('#')]
if len(line.split()) == 0:
continue
(address, word) = [int(x, 16) for x in line.split()]
offset = address_to_offset(data, address)
data[offset:offset + 4] = word_to_bytes(word)
print(f'Patch {address:08X} -> {word:08X}')
def main():
with open('bin/sys/main.dol', 'rb') as f:
data = bytearray(f.read())
patch_stack_and_heap(data)
apply_hooks(data)
apply_extra_patches(data)
with open('bin/sys/main.dol', 'wb') as f:
f.write(data)
if __name__ == '__main__':
main() |
class MetaSingleton(type):
instance = {}
def __init__(cls, name, bases, attrs, **kwargs):
cls.__copy__ = lambda self: self
cls.__deepcopy__ = lambda self, memo: self
def __call__(cls, *args, **kwargs):
key = cls.__qualname__
if key not in cls.instance:
instance = super().__call__(*args, **kwargs)
cls.instance[key] = instance
else:
instance = cls.instance[key]
instance.__init__(*args, **kwargs)
return instance
class Singleton(metaclass=MetaSingleton):
def __init__(self, *args, **kwargs):
pass
def singleton(name):
cls = type(name, (Singleton,), {})
return cls()
| class Metasingleton(type):
instance = {}
def __init__(cls, name, bases, attrs, **kwargs):
cls.__copy__ = lambda self: self
cls.__deepcopy__ = lambda self, memo: self
def __call__(cls, *args, **kwargs):
key = cls.__qualname__
if key not in cls.instance:
instance = super().__call__(*args, **kwargs)
cls.instance[key] = instance
else:
instance = cls.instance[key]
instance.__init__(*args, **kwargs)
return instance
class Singleton(metaclass=MetaSingleton):
def __init__(self, *args, **kwargs):
pass
def singleton(name):
cls = type(name, (Singleton,), {})
return cls() |
#
# This file contains the Python code from Program 15.10 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm15_10.txt
#
class HeapSorter(Sorter):
def __init__(self):
super(HeapSorter, self).__init__()
def percolateDown(self, i, length):
while 2 * i <= length:
j = 2 * i
if j < length and self._array[j + 1] \
> self._array[j]:
j = j + 1
if self._array[i] \
>= self._array[j]:
break
self.swap(i, j)
i = j
# ...
| class Heapsorter(Sorter):
def __init__(self):
super(HeapSorter, self).__init__()
def percolate_down(self, i, length):
while 2 * i <= length:
j = 2 * i
if j < length and self._array[j + 1] > self._array[j]:
j = j + 1
if self._array[i] >= self._array[j]:
break
self.swap(i, j)
i = j |
'''
@name -> insertTopStreams
@param (dbConnection) -> db connection object
@param (cursor) -> db cursor object
@param (time) -> a list of 5 integers that means [year, month, day, hour, minute]
@param (topStreams) -> list of 20 dictionary objects
'''
def insertTopStreams(dbConnection, cursor, time, topStreams):
# multidimensional list
# list order: [channel_id, display_name, language, game, created_at, followers, views, viewers, preview_template]
items = []
for stream in topStreams:
item = []
item.append(str(stream['channel']['_id']))
item.append(str(stream['channel']['display_name']))
item.append(str(stream['channel']['language']))
item.append(str(stream['game']))
item.append(str(stream['created_at']))
item.append(str(stream['channel']['followers']))
item.append(str(stream['channel']['views']))
item.append(str(stream['viewers']))
item.append(str(stream['preview']['template']))
items.append(item)
query = 'INSERT INTO top_streams (custom_timestamp, stream_01, stream_02, stream_03, stream_04, stream_05, stream_06, stream_07, stream_08, stream_09, stream_10, stream_11, stream_12, stream_13, stream_14, stream_15, stream_16, stream_17, stream_18, stream_19, stream_20) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
cursor.execute(
query,
[
time,
items[0], items[1], items[2], items[3], items[4],
items[5], items[6], items[7], items[8], items[9],
items[10], items[11], items[12], items[13], items[14],
items[15], items[16], items[17], items[18], items[19]
]
)
dbConnection.commit() | """
@name -> insertTopStreams
@param (dbConnection) -> db connection object
@param (cursor) -> db cursor object
@param (time) -> a list of 5 integers that means [year, month, day, hour, minute]
@param (topStreams) -> list of 20 dictionary objects
"""
def insert_top_streams(dbConnection, cursor, time, topStreams):
items = []
for stream in topStreams:
item = []
item.append(str(stream['channel']['_id']))
item.append(str(stream['channel']['display_name']))
item.append(str(stream['channel']['language']))
item.append(str(stream['game']))
item.append(str(stream['created_at']))
item.append(str(stream['channel']['followers']))
item.append(str(stream['channel']['views']))
item.append(str(stream['viewers']))
item.append(str(stream['preview']['template']))
items.append(item)
query = 'INSERT INTO top_streams (custom_timestamp, stream_01, stream_02, stream_03, stream_04, stream_05, stream_06, stream_07, stream_08, stream_09, stream_10, stream_11, stream_12, stream_13, stream_14, stream_15, stream_16, stream_17, stream_18, stream_19, stream_20) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
cursor.execute(query, [time, items[0], items[1], items[2], items[3], items[4], items[5], items[6], items[7], items[8], items[9], items[10], items[11], items[12], items[13], items[14], items[15], items[16], items[17], items[18], items[19]])
dbConnection.commit() |
class BinaryIndexedTree:
def __init__(self, n):
self.sums = [0] * (n + 1)
def update(self, i, delta):
while i < len(self.sums):
self.sums[i] += delta
# add low bit
i += (i & -i)
def prefix_sum(self, i):
ret = 0
while i:
ret += self.sums[i]
i -= (i & -i)
return ret
| class Binaryindexedtree:
def __init__(self, n):
self.sums = [0] * (n + 1)
def update(self, i, delta):
while i < len(self.sums):
self.sums[i] += delta
i += i & -i
def prefix_sum(self, i):
ret = 0
while i:
ret += self.sums[i]
i -= i & -i
return ret |
#stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner.
#In stack, a new element is added at one end and an element is removed from that end only.
stack = []
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack')
print(stack)
# pop() function to pop element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
| stack = []
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack')
print(stack)
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack) |
student = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
a = [1, 2, 6, 7, 13, 15, 11]
b = [3, 4, 6, 8, 12, 13]
c = [6, 7, 8, 9, 14, 15]
t1 = []
t2 = []
t3 = []
t4 = []
for i in range(len(student)):
if student[i] in a and student[i] in b:
t1.append(student[i])
if student[i] in a and student[i] not in b or student[i] in b and student[i] not in a:
t2.append(student[i])
if student[i] not in a and student[i] not in b:
t3.append(student[i])
if student[i] in a and student[i] in c and student[i] not in b:
t4.append(student[i])
print("List of student who play both cricket and badminton :", t1)
print("List of student who play either cricket or badminton but not both:", t2)
print("No. of students who play neither cricket nor badminton :", len(t3))
print("No. of students who play cricket and football but not badminton :", len(t4))
| student = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
a = [1, 2, 6, 7, 13, 15, 11]
b = [3, 4, 6, 8, 12, 13]
c = [6, 7, 8, 9, 14, 15]
t1 = []
t2 = []
t3 = []
t4 = []
for i in range(len(student)):
if student[i] in a and student[i] in b:
t1.append(student[i])
if student[i] in a and student[i] not in b or (student[i] in b and student[i] not in a):
t2.append(student[i])
if student[i] not in a and student[i] not in b:
t3.append(student[i])
if student[i] in a and student[i] in c and (student[i] not in b):
t4.append(student[i])
print('List of student who play both cricket and badminton :', t1)
print('List of student who play either cricket or badminton but not both:', t2)
print('No. of students who play neither cricket nor badminton :', len(t3))
print('No. of students who play cricket and football but not badminton :', len(t4)) |
async def setupAddSelfrole(plugin, ctx, name, role, roles):
role_id = role.id
name = name.lower()
if role_id in [roles[x] for x in roles] or name in roles:
return await ctx.send(plugin.t(ctx.guild, "already_selfrole", _emote="WARN"))
if role.position >= ctx.guild.me.top_role.position:
return await ctx.send(plugin.t(ctx.guild, "role_too_high", _emote="WARN"))
if role == ctx.guild.default_role:
return await ctx.send(plugin.t(ctx.guild, "default_role_forbidden", _emote="WARN"))
roles[name] = str(role_id)
plugin.db.configs.update(ctx.guild.id, "selfroles", roles)
await ctx.send(plugin.t(ctx.guild, "selfrole_added", _emote="YES", role=role.name, name=name, prefix=plugin.bot.get_guild_prefix(ctx.guild))) | async def setupAddSelfrole(plugin, ctx, name, role, roles):
role_id = role.id
name = name.lower()
if role_id in [roles[x] for x in roles] or name in roles:
return await ctx.send(plugin.t(ctx.guild, 'already_selfrole', _emote='WARN'))
if role.position >= ctx.guild.me.top_role.position:
return await ctx.send(plugin.t(ctx.guild, 'role_too_high', _emote='WARN'))
if role == ctx.guild.default_role:
return await ctx.send(plugin.t(ctx.guild, 'default_role_forbidden', _emote='WARN'))
roles[name] = str(role_id)
plugin.db.configs.update(ctx.guild.id, 'selfroles', roles)
await ctx.send(plugin.t(ctx.guild, 'selfrole_added', _emote='YES', role=role.name, name=name, prefix=plugin.bot.get_guild_prefix(ctx.guild))) |
'''
LANGUAGE: Python
AUTHOR: Weiyi
GITHUB: https://github.com/weiyi-m
'''
print("Hello World!")
| """
LANGUAGE: Python
AUTHOR: Weiyi
GITHUB: https://github.com/weiyi-m
"""
print('Hello World!') |
hours = 40
pay_rate = 400
no_weeks = 4
monthly_pay = hours * pay_rate *no_weeks
print(monthly_pay)
| hours = 40
pay_rate = 400
no_weeks = 4
monthly_pay = hours * pay_rate * no_weeks
print(monthly_pay) |
def is_leap(year):
leap = False
# Write your logic here
# thought process
#if year%4==0:
# return True
#elif year%100==0:
# return False
#elif year%400==0:
# return True
# Optimized, Python 3
return ((year%4==0)and(year%100!=0)or(year%400==0))
| def is_leap(year):
leap = False
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 |
'''
1. Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number
Input : [1, 0, -1, 0, -2, 2], 0)
Output : [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
2. Write a Python program to compute and return the square root of a given 'integer'.
Input : 16
Output : 4
Note : The returned value will be an 'integer'
3. Write a Python program to find the single number in a list that doesn't occur twice
Input : [5, 3, 4, 3, 4]
Output : 5
'''
| """
1. Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number
Input : [1, 0, -1, 0, -2, 2], 0)
Output : [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
2. Write a Python program to compute and return the square root of a given 'integer'.
Input : 16
Output : 4
Note : The returned value will be an 'integer'
3. Write a Python program to find the single number in a list that doesn't occur twice
Input : [5, 3, 4, 3, 4]
Output : 5
""" |
def main():
for i in range(10):
print(f"The square of {i} is {square(i)}")
return
def square(n):
return n**2
if __name__ == '__main__':
main()
| def main():
for i in range(10):
print(f'The square of {i} is {square(i)}')
return
def square(n):
return n ** 2
if __name__ == '__main__':
main() |
'''
Created on 11 aug. 2011
.. codeauthor:: wauping <w.auping (at) student (dot) tudelft (dot) nl>
jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
To be able to debug the Vensim model, a few steps are needed:
1. The case that gave a bug, needs to be saved in a text file. The entire
case description should be on a single line.
2. Reform and clean your model ( In the Vensim menu: Model, Reform and
Clean). Choose
* Equation Order: Alphabetical by group (not really necessary)
* Equation Format: Terse
3. Save your model as text (File, Save as..., Save as Type: Text Format
Models
4. Run this script
5. If the print in the end is not set([]), but set([array]), the array
gives the values that where not found and changed
5. Run your new model (for example 'new text.mdl')
6. Vensim tells you about your critical mistake
'''
fileSpecifyingError = ""
pathToExistingModel = r"C:\workspace\EMA-workbench\models\salinization\Verzilting_aanpassingen incorrect.mdl"
pathToNewModel = r"C:\workspace\EMA-workbench\models\salinization\Verzilting_aanpassingen correct.mdl"
newModel = open(pathToNewModel, 'w')
# line = open(fileSpecifyingError).read()
line = 'rainfall : 0.154705633188; adaptation time from non irrigated agriculture : 0.915157119079; salt effect multiplier : 1.11965969891; adaptation time to non irrigated agriculture : 0.48434342934; adaptation time to irrigated agriculture : 0.330990830832; water shortage multiplier : 0.984356102036; delay time salt seepage : 6.0; adaptation time : 6.90258192256; births multiplier : 1.14344734715; diffusion lookup : [(0, 8.0), (10, 8.0), (20, 8.0), (30, 8.0), (40, 7.9999999999999005), (50, 4.0), (60, 9.982194802803703e-14), (70, 1.2455526635140464e-27), (80, 1.5541686655435471e-41), (90, 1.9392517969836692e-55)]; salinity effect multiplier : 1.10500381093; technological developments in irrigation : 0.0117979353255; adaptation time from irrigated agriculture : 1.58060947607; food shortage multiplier : 0.955325345996; deaths multiplier : 0.875605669911; '
# we assume the case specification was copied from the logger
splitOne = line.split(';')
variable = {}
for n in range(len(splitOne) - 1):
splitTwo = splitOne[n].split(':')
variableElement = splitTwo[0]
# Delete the spaces and other rubish on the sides of the variable name
variableElement = variableElement.lstrip()
variableElement = variableElement.lstrip("'")
variableElement = variableElement.rstrip()
variableElement = variableElement.rstrip("'")
print(variableElement)
valueElement = splitTwo[1]
valueElement = valueElement.lstrip()
valueElement = valueElement.rstrip()
variable[variableElement] = valueElement
print(variable)
# This generates a new (text-formatted) model
changeNextLine = False
settedValues = []
for line in open(pathToExistingModel):
if line.find("=") != -1:
elements = line.split("=")
value = elements[0]
value = value.strip()
if value in variable:
elements[1] = variable.get(value)
line = elements[0] + " = " + elements[1]
settedValues.append(value)
newModel.write(line)
notSet = set(variable.keys()) - set(settedValues)
print(notSet)
| """
Created on 11 aug. 2011
.. codeauthor:: wauping <w.auping (at) student (dot) tudelft (dot) nl>
jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
To be able to debug the Vensim model, a few steps are needed:
1. The case that gave a bug, needs to be saved in a text file. The entire
case description should be on a single line.
2. Reform and clean your model ( In the Vensim menu: Model, Reform and
Clean). Choose
* Equation Order: Alphabetical by group (not really necessary)
* Equation Format: Terse
3. Save your model as text (File, Save as..., Save as Type: Text Format
Models
4. Run this script
5. If the print in the end is not set([]), but set([array]), the array
gives the values that where not found and changed
5. Run your new model (for example 'new text.mdl')
6. Vensim tells you about your critical mistake
"""
file_specifying_error = ''
path_to_existing_model = 'C:\\workspace\\EMA-workbench\\models\\salinization\\Verzilting_aanpassingen incorrect.mdl'
path_to_new_model = 'C:\\workspace\\EMA-workbench\\models\\salinization\\Verzilting_aanpassingen correct.mdl'
new_model = open(pathToNewModel, 'w')
line = 'rainfall : 0.154705633188; adaptation time from non irrigated agriculture : 0.915157119079; salt effect multiplier : 1.11965969891; adaptation time to non irrigated agriculture : 0.48434342934; adaptation time to irrigated agriculture : 0.330990830832; water shortage multiplier : 0.984356102036; delay time salt seepage : 6.0; adaptation time : 6.90258192256; births multiplier : 1.14344734715; diffusion lookup : [(0, 8.0), (10, 8.0), (20, 8.0), (30, 8.0), (40, 7.9999999999999005), (50, 4.0), (60, 9.982194802803703e-14), (70, 1.2455526635140464e-27), (80, 1.5541686655435471e-41), (90, 1.9392517969836692e-55)]; salinity effect multiplier : 1.10500381093; technological developments in irrigation : 0.0117979353255; adaptation time from irrigated agriculture : 1.58060947607; food shortage multiplier : 0.955325345996; deaths multiplier : 0.875605669911; '
split_one = line.split(';')
variable = {}
for n in range(len(splitOne) - 1):
split_two = splitOne[n].split(':')
variable_element = splitTwo[0]
variable_element = variableElement.lstrip()
variable_element = variableElement.lstrip("'")
variable_element = variableElement.rstrip()
variable_element = variableElement.rstrip("'")
print(variableElement)
value_element = splitTwo[1]
value_element = valueElement.lstrip()
value_element = valueElement.rstrip()
variable[variableElement] = valueElement
print(variable)
change_next_line = False
setted_values = []
for line in open(pathToExistingModel):
if line.find('=') != -1:
elements = line.split('=')
value = elements[0]
value = value.strip()
if value in variable:
elements[1] = variable.get(value)
line = elements[0] + ' = ' + elements[1]
settedValues.append(value)
newModel.write(line)
not_set = set(variable.keys()) - set(settedValues)
print(notSet) |
game = {
'leds': (
# GPIO05 - Pin 29
5,
# GPIO12 - Pin 32
12,
# GPIO17 - Pin 11
17,
# GPIO22 - Pin 15
22,
# GPIO25 - Pin 22
25
),
'switches': (
# GPIO06 - Pin 31
6,
# GPIO13 - Pin 33
13,
# GPIO19 - Pin 35
19,
# GPIO23 - Pin 16
23,
# GPIO24 - Pin 18
24
),
'countdown': 5,
'game_time': 60,
'score_increment': 1
}
| game = {'leds': (5, 12, 17, 22, 25), 'switches': (6, 13, 19, 23, 24), 'countdown': 5, 'game_time': 60, 'score_increment': 1} |
# Databricks notebook source
# MAGIC %run ./_utility-methods $lesson="3.1"
# COMMAND ----------
DA.cleanup()
DA.init(create_db=False)
install_dtavod_datasets(reinstall=False)
print()
copy_source_dataset(f"{DA.working_dir_prefix}/source/dtavod/flights/departuredelays.csv", f"{DA.paths.working_dir}/flights/departuredelays.csv", "csv", "flights")
DA.conclude_setup()
| DA.cleanup()
DA.init(create_db=False)
install_dtavod_datasets(reinstall=False)
print()
copy_source_dataset(f'{DA.working_dir_prefix}/source/dtavod/flights/departuredelays.csv', f'{DA.paths.working_dir}/flights/departuredelays.csv', 'csv', 'flights')
DA.conclude_setup() |
class CNConfig:
interp_factor = 0.075
sigma = 0.2
lambda_= 0.01
output_sigma_factor=1./16
padding=1
cn_type = 'pyECO'
| class Cnconfig:
interp_factor = 0.075
sigma = 0.2
lambda_ = 0.01
output_sigma_factor = 1.0 / 16
padding = 1
cn_type = 'pyECO' |
sortname = {
'bubblesort': f'Bubble Sort O(n\N{SUPERSCRIPT TWO})', 'insertionsort': f'Insertion Sort O(n\N{SUPERSCRIPT TWO})',
'selectionsort': f'Selection Sort O(n\N{SUPERSCRIPT TWO})', 'mergesort': 'Merge Sort O(n log n)',
'quicksort': 'Quick Sort O(n log n)', 'heapsort': 'Heap Sort O(n log n)'
} | sortname = {'bubblesort': f'Bubble Sort O(n²)', 'insertionsort': f'Insertion Sort O(n²)', 'selectionsort': f'Selection Sort O(n²)', 'mergesort': 'Merge Sort O(n log n)', 'quicksort': 'Quick Sort O(n log n)', 'heapsort': 'Heap Sort O(n log n)'} |
class Cons():
def __init__(self, data, nxt):
self.data = data
self.nxt = nxt
Nil = None
def new(*elems):
if len(elems) == 0:
return Nil
else:
return Cons(elems[0], new(*elems[1:]))
def printls(xs):
i = xs
while i != Nil:
print(i.data)
i = i.nxt
| class Cons:
def __init__(self, data, nxt):
self.data = data
self.nxt = nxt
nil = None
def new(*elems):
if len(elems) == 0:
return Nil
else:
return cons(elems[0], new(*elems[1:]))
def printls(xs):
i = xs
while i != Nil:
print(i.data)
i = i.nxt |
names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
print(names[2])
print(names[-1])
print(names[2:])
# prints from third to end
print(names[2:4])
# prints third to fourth, does not include last one
names[0] = 'Jon'
# Find largest number in list
numbers = [1, 34, 34, 12312, 123, 23, 903, 341093, 34]
max_number = numbers[0]
for item in numbers:
if item > max_number:
max_number = item
print(f"The largest number is {max_number}.")
# 2D Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# matrix[0][1] = 20
# print(matrix[0][1])
# for row in matrix:
# for item in row:
# print(item)
# List Methods
numbers = [5, 2, 1, 7, 4, 5, 5, 5]
numbers.append(20)
numbers.insert(0, 10)
# removes first mention of 5
numbers.remove(5)
# clears entire list
# numbers.clear()
# removes last item
numbers.pop()
print(numbers)
# finds index of first occurence of item
print(numbers.index(5))
# safer version, if not found returns false
print(50 in numbers)
print(numbers.count(5))
numbers.sort()
numbers.reverse()
print(numbers)
numbers2 = numbers.copy()
numbers2.append(10)
print(numbers2)
# Write a program to remove the duplicates in a list
list1 = [1, 3, 5, 5, 7, 9, 9, 9, 1]
checked_number = 0
check_count = 0
for item in list1:
checked_number = item
check_count = 0
for number in list1:
if checked_number == number:
check_count += 1
if check_count > 1:
list1.remove(checked_number)
print(list1)
#Solution
numbers = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number) | names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
print(names[2])
print(names[-1])
print(names[2:])
print(names[2:4])
names[0] = 'Jon'
numbers = [1, 34, 34, 12312, 123, 23, 903, 341093, 34]
max_number = numbers[0]
for item in numbers:
if item > max_number:
max_number = item
print(f'The largest number is {max_number}.')
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
numbers = [5, 2, 1, 7, 4, 5, 5, 5]
numbers.append(20)
numbers.insert(0, 10)
numbers.remove(5)
numbers.pop()
print(numbers)
print(numbers.index(5))
print(50 in numbers)
print(numbers.count(5))
numbers.sort()
numbers.reverse()
print(numbers)
numbers2 = numbers.copy()
numbers2.append(10)
print(numbers2)
list1 = [1, 3, 5, 5, 7, 9, 9, 9, 1]
checked_number = 0
check_count = 0
for item in list1:
checked_number = item
check_count = 0
for number in list1:
if checked_number == number:
check_count += 1
if check_count > 1:
list1.remove(checked_number)
print(list1)
numbers = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number) |
n = int(input("n: "))
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
while (n <= 0 or n >= 100000) or (a <= 0 or a >= 100000) or (b <= 0 or b >= 100000) or (c <= 0 or c >= 100000):
print("All numbers should be positive between 0 and 100 000!")
n = int(input("n: "))
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
n+=1
line = [None] * n # None-> empty; 1-> first person dot; 2-> second person dot
#populate the line with dots
i = 0
while i <= (n-1)/a:
line[i*a] = 1
i+=1
i = 0
line[n - 1] = 2
while i <= (n-1)/b:
line[(n - 1) - (i * b)] = 2
i+=1
painted_red_segment_length = 0
i = 0
#calcualte the length of the painted segment
while i < n:
if i == 0:
if (line[i] != line[i + 1]) and (line[i] != None) and (line[i + 1] != None):
painted_red_segment_length += 1
i+=1
elif i == n-1:
if (line[i] != line[i - 1]) and (line[i] != None) and (line[i - 1] != None):
painted_red_segment_length += 1
else:
if (line[i] != line[i - 1]) and (line[i] != None) and (line[i - 1] != None):
painted_red_segment_length += 1
if (line[i] != line[i + 1]) and (line[i] != None) and (line[i + 1] != None):
painted_red_segment_length += 1
i+=1
i+=1
#calculate the length of the segment that is not painted
result = (n-1) - painted_red_segment_length
print("result: " + str(result)) | n = int(input('n: '))
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
while (n <= 0 or n >= 100000) or (a <= 0 or a >= 100000) or (b <= 0 or b >= 100000) or (c <= 0 or c >= 100000):
print('All numbers should be positive between 0 and 100 000!')
n = int(input('n: '))
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
n += 1
line = [None] * n
i = 0
while i <= (n - 1) / a:
line[i * a] = 1
i += 1
i = 0
line[n - 1] = 2
while i <= (n - 1) / b:
line[n - 1 - i * b] = 2
i += 1
painted_red_segment_length = 0
i = 0
while i < n:
if i == 0:
if line[i] != line[i + 1] and line[i] != None and (line[i + 1] != None):
painted_red_segment_length += 1
i += 1
elif i == n - 1:
if line[i] != line[i - 1] and line[i] != None and (line[i - 1] != None):
painted_red_segment_length += 1
else:
if line[i] != line[i - 1] and line[i] != None and (line[i - 1] != None):
painted_red_segment_length += 1
if line[i] != line[i + 1] and line[i] != None and (line[i + 1] != None):
painted_red_segment_length += 1
i += 1
i += 1
result = n - 1 - painted_red_segment_length
print('result: ' + str(result)) |
def write_empty_line(handle):
handle.write('\n')
def write_title(handle, title, marker = ''):
if marker == '':
line = '{0}\n'.format(title)
else:
line = '{0} {1}\n'.format(marker, title)
handle.write(line)
def write_notes(handle, task):
def is_task_with_notes(task):
result = False
for note in task['notes']:
if note.strip() != '':
result = True
break
return result
if is_task_with_notes(task):
notes = '\n'.join(task['notes'])
handle.write(notes)
write_empty_line(handle) | def write_empty_line(handle):
handle.write('\n')
def write_title(handle, title, marker=''):
if marker == '':
line = '{0}\n'.format(title)
else:
line = '{0} {1}\n'.format(marker, title)
handle.write(line)
def write_notes(handle, task):
def is_task_with_notes(task):
result = False
for note in task['notes']:
if note.strip() != '':
result = True
break
return result
if is_task_with_notes(task):
notes = '\n'.join(task['notes'])
handle.write(notes)
write_empty_line(handle) |
def goodSegement1(badList,l,r):
sortedBadList = sorted(badList)
current =sortedBadList[0]
maxVal = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
maxIndex = i+1
# first value
if i == 0 and l<=current<=r:
val = current - l
prev = l
print("first index value")
print("prev, current : ",prev,current)
if(val>maxVal):
maxVal = val
print("1. (s,e)",l,current)
# other middle values
elif l<=current<=r:
prev = sortedBadList[i-1]
val = current - prev
print("prev, current : ",prev,current)
if(val>maxVal):
maxVal = val
print("2. (s,e)",prev,current)
# last value
if maxIndex == len(sortedBadList) and l<=current<=r:
print("last index value")
next = r
val = next - current
if(val>maxVal):
maxVal = val
print("3. (s,e)",current,next)
print("maxVal:",maxVal-1)
pass
goodSegement1([2,5,8,10,3],1,12)
goodSegement1([37,7,22,15,49,60],3,48)
| def good_segement1(badList, l, r):
sorted_bad_list = sorted(badList)
current = sortedBadList[0]
max_val = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
max_index = i + 1
if i == 0 and l <= current <= r:
val = current - l
prev = l
print('first index value')
print('prev, current : ', prev, current)
if val > maxVal:
max_val = val
print('1. (s,e)', l, current)
elif l <= current <= r:
prev = sortedBadList[i - 1]
val = current - prev
print('prev, current : ', prev, current)
if val > maxVal:
max_val = val
print('2. (s,e)', prev, current)
if maxIndex == len(sortedBadList) and l <= current <= r:
print('last index value')
next = r
val = next - current
if val > maxVal:
max_val = val
print('3. (s,e)', current, next)
print('maxVal:', maxVal - 1)
pass
good_segement1([2, 5, 8, 10, 3], 1, 12)
good_segement1([37, 7, 22, 15, 49, 60], 3, 48) |
l, r = map(int, input().split())
mod = 10 ** 9 + 7
def f(x):
if x == 0:
return 0
res = 1
cnt = 2
f = 1
b_s = 2
e_s = 4
b_f = 3
e_f = 9
x -= 1
while x > 0:
if f:
res += cnt * (b_s + e_s) // 2
b_s = e_s + 2
e_s = e_s + 2 * (4 * cnt)
else:
res += cnt * (b_f + e_f) // 2
b_f = e_f + 2
e_f = e_f + 2 * (4 * cnt)
x -= cnt
if x < 0:
if f:
b_s -= 2
res -= abs(x) * (b_s + b_s - abs(x + 1) * 2) // 2
else:
b_f -= 2
res -= abs(x) * (b_f + b_f - abs(x + 1) * 2) // 2
cnt *= 2
f = 1 - f
return res
print((f(r) - f(l - 1)) % mod)
| (l, r) = map(int, input().split())
mod = 10 ** 9 + 7
def f(x):
if x == 0:
return 0
res = 1
cnt = 2
f = 1
b_s = 2
e_s = 4
b_f = 3
e_f = 9
x -= 1
while x > 0:
if f:
res += cnt * (b_s + e_s) // 2
b_s = e_s + 2
e_s = e_s + 2 * (4 * cnt)
else:
res += cnt * (b_f + e_f) // 2
b_f = e_f + 2
e_f = e_f + 2 * (4 * cnt)
x -= cnt
if x < 0:
if f:
b_s -= 2
res -= abs(x) * (b_s + b_s - abs(x + 1) * 2) // 2
else:
b_f -= 2
res -= abs(x) * (b_f + b_f - abs(x + 1) * 2) // 2
cnt *= 2
f = 1 - f
return res
print((f(r) - f(l - 1)) % mod) |
def sum_doubles():
numbers = open('1.txt').readline()
numbers = numbers + numbers[0]
total = 0
for i in range(len(numbers) - 1):
a = int(numbers[i])
b = int(numbers[i+1])
if a == b:
total += a
return total
# print(sum_doubles()) # 1341
def sum_halfway(numbers):
total = 0
delta = int(len(numbers) / 2)
for i in range(len(numbers) - 1):
bi = (i + delta) % len(numbers)
a = int(numbers[i])
b = int(numbers[bi])
if a == b:
total += a
return total
print(sum_halfway(open('1.txt').readline())) # 1348
# print(sum_halfway("12131415"))
| def sum_doubles():
numbers = open('1.txt').readline()
numbers = numbers + numbers[0]
total = 0
for i in range(len(numbers) - 1):
a = int(numbers[i])
b = int(numbers[i + 1])
if a == b:
total += a
return total
def sum_halfway(numbers):
total = 0
delta = int(len(numbers) / 2)
for i in range(len(numbers) - 1):
bi = (i + delta) % len(numbers)
a = int(numbers[i])
b = int(numbers[bi])
if a == b:
total += a
return total
print(sum_halfway(open('1.txt').readline())) |
def reader():
...
| def reader():
... |
def C(x=None, ls=('$', 'A', 'C', 'G', 'T')):
x = "ATATATTAG" if not x else x
x += "$"
dictir = {i: sum([x.count(j) for j in ls[:ls.index(i)]]) for i in ls}
return dictir
def BWT(x, suffix):
x = "ATATATTAG" if not x else x
x += "$"
return ''.join([x[i - 2] for i in suffix])
def suffix_arr(x="ATATATTAG"):
x = x + '$' if '$' not in x else x
shifts = [x]
for i in range(1, len(x)):
shifts.append(x[i:] + x[:i])
shifts.sort()
suffix_arr = [len(shift) - shift.index('$') for shift in shifts]
return shifts, suffix_arr
def main():
x = 'ATATATTAG'
S = [10, 8, 1, 3, 5, 9, 7, 2, 4, 6]
print(C())
print(BWT(x, S))
if __name__ == '__main__':
main()
| def c(x=None, ls=('$', 'A', 'C', 'G', 'T')):
x = 'ATATATTAG' if not x else x
x += '$'
dictir = {i: sum([x.count(j) for j in ls[:ls.index(i)]]) for i in ls}
return dictir
def bwt(x, suffix):
x = 'ATATATTAG' if not x else x
x += '$'
return ''.join([x[i - 2] for i in suffix])
def suffix_arr(x='ATATATTAG'):
x = x + '$' if '$' not in x else x
shifts = [x]
for i in range(1, len(x)):
shifts.append(x[i:] + x[:i])
shifts.sort()
suffix_arr = [len(shift) - shift.index('$') for shift in shifts]
return (shifts, suffix_arr)
def main():
x = 'ATATATTAG'
s = [10, 8, 1, 3, 5, 9, 7, 2, 4, 6]
print(c())
print(bwt(x, S))
if __name__ == '__main__':
main() |
CONTEXT = {'cell_line': 'Cell Line',
'cellline': 'Cell Line',
'cell_type': 'Cell Type',
'celltype': 'Cell Type',
'tissue': 'Tissue',
'interactome': 'Interactome'
}
HIDDEN_FOLDER = '.contnext'
ZENODO_URL = 'https://zenodo.org/record/5831786/files/data.zip?download=1' | context = {'cell_line': 'Cell Line', 'cellline': 'Cell Line', 'cell_type': 'Cell Type', 'celltype': 'Cell Type', 'tissue': 'Tissue', 'interactome': 'Interactome'}
hidden_folder = '.contnext'
zenodo_url = 'https://zenodo.org/record/5831786/files/data.zip?download=1' |
def diag_diff(matriza):
first_diag = second_diag = 0
razmer = len(matriza)
for i in range(razmer):
first_diag += matriza[i][i]
second_diag += matriza[i][razmer - i - 1]
return first_diag - second_diag
| def diag_diff(matriza):
first_diag = second_diag = 0
razmer = len(matriza)
for i in range(razmer):
first_diag += matriza[i][i]
second_diag += matriza[i][razmer - i - 1]
return first_diag - second_diag |
description = 'STRESS-SPEC setup with Eulerian cradle'
group = 'basic'
includes = [
'standard', 'sampletable',
]
sysconfig = dict(
datasinks = ['caresssink'],
)
devices = dict(
chis = device('nicos.devices.generic.Axis',
description = 'Simulated CHIS axis',
motor = device('nicos.devices.generic.VirtualMotor',
fmtstr = '%.2f',
unit = 'deg',
abslimits = (-180, 180),
visibility = (),
speed = 2,
),
precision = 0.001,
),
phis = device('nicos.devices.generic.Axis',
description = 'Simulated PHIS axis',
motor = device('nicos.devices.generic.VirtualMotor',
fmtstr = '%.2f',
unit = 'deg',
abslimits = (-720, 720),
visibility = (),
speed = 2,
),
precision = 0.001,
),
)
startupcode = '''
SetDetectors(adet)
'''
| description = 'STRESS-SPEC setup with Eulerian cradle'
group = 'basic'
includes = ['standard', 'sampletable']
sysconfig = dict(datasinks=['caresssink'])
devices = dict(chis=device('nicos.devices.generic.Axis', description='Simulated CHIS axis', motor=device('nicos.devices.generic.VirtualMotor', fmtstr='%.2f', unit='deg', abslimits=(-180, 180), visibility=(), speed=2), precision=0.001), phis=device('nicos.devices.generic.Axis', description='Simulated PHIS axis', motor=device('nicos.devices.generic.VirtualMotor', fmtstr='%.2f', unit='deg', abslimits=(-720, 720), visibility=(), speed=2), precision=0.001))
startupcode = '\nSetDetectors(adet)\n' |
# Copyright (C) 2017 Ming-Shing Chen
def gf2_mul( a , b ):
return a&b
# gf4 := gf2[x]/x^2+x+1
# 4 and , 3 xor
def gf4_mul( a , b ):
a0 = a&1
a1 = (a>>1)&1
b0 = b&1
b1 = (b>>1)&1
ab0 = a0&b0
ab1 = (a1&b0)^(a0&b1)
ab2 = a1&b1
ab0 ^= ab2
ab1 ^= ab2
ab0 ^= (ab1<<1)
return ab0
# gf16 := gf4[y]/y^2+y+x
# gf16 mul: xor: 18 ,and: 12
def gf16_mul( a , b ):
a0 = a&3
a1 = (a>>2)&3
b0 = b&3
b1 = (b>>2)&3
a0b0 = gf4_mul( a0 , b0 )
a1b1 = gf4_mul( a1 , b1 )
a0a1xb0b1_a0b0 = gf4_mul( a0^a1 , b0^b1 ) ^ a0b0
rd0 = gf4_mul( 2 , a1b1 )
a0b0 ^= rd0
return a0b0|(a0a1xb0b1_a0b0<<2)
# gf256 := gf16[x]/x^2 + x + 0x8
def gf256_mul( a , b ):
a0 = a&15
a1 = (a>>4)&15
b0 = b&15
b1 = (b>>4)&15
ab0 = gf16_mul( a0 , b0 )
ab1 = gf16_mul( a1 , b0 ) ^ gf16_mul( a0 , b1 )
ab2 = gf16_mul( a1 , b1 )
ab0 ^= gf16_mul( ab2 , 8 )
ab1 ^= ab2
ab0 ^= (ab1<<4)
return ab0
#382 bit operations
def gf216_mul( a , b ):
a0 = a&0xff
a1 = (a>>8)&0xff
b0 = b&0xff
b1 = (b>>8)&0xff
a0b0 = gf256_mul( a0 , b0 )
a1b1 = gf256_mul( a1 , b1 )
#a0b1_a1b0 = gf16_mul( a0^a1 , b0^b1 ) ^ a0b0 ^ a1b1 ^a1b1
a0b1_a1b0 = gf256_mul( a0^a1 , b0^b1 ) ^ a0b0
rd0 = gf256_mul( a1b1 , 0x80 )
return (a0b1_a1b0<<8)|(rd0^a0b0)
#gf65536 := gf256[x]/x^2 + x + 0x80
def gf65536_mul( a , b ):
a0 = a&0xff;
a1 = (a>>8)&0xff;
b0 = b&0xff;
b1 = (b>>8)&0xff;
ab0 = gf256_mul( a0 , b0 );
ab2 = gf256_mul( a1 , b1 );
ab1 = gf256_mul( a0^a1 , b0^b1 )^ab0;
return (ab1<<8)^(ab0^gf256_mul(ab2,0x80));
#gf832 := gf65536[x]/x^2 + x + 0x8000
def gf832_mul( a , b ):
a0 = a&0xffff;
a1 = (a>>16)&0xffff;
b0 = b&0xffff;
b1 = (b>>16)&0xffff;
ab0 = gf65536_mul( a0 , b0 );
ab2 = gf65536_mul( a1 , b1 );
ab1 = gf65536_mul( a0^a1 , b0^b1 )^ab0;
return (ab1<<16)^(ab0^gf65536_mul(ab2,0x8000));
def gf832_inv(a) :
r = a
for i in range(2,32):
r = gf832_mul(r,r)
r = gf832_mul(r,a)
return gf832_mul(r,r)
| def gf2_mul(a, b):
return a & b
def gf4_mul(a, b):
a0 = a & 1
a1 = a >> 1 & 1
b0 = b & 1
b1 = b >> 1 & 1
ab0 = a0 & b0
ab1 = a1 & b0 ^ a0 & b1
ab2 = a1 & b1
ab0 ^= ab2
ab1 ^= ab2
ab0 ^= ab1 << 1
return ab0
def gf16_mul(a, b):
a0 = a & 3
a1 = a >> 2 & 3
b0 = b & 3
b1 = b >> 2 & 3
a0b0 = gf4_mul(a0, b0)
a1b1 = gf4_mul(a1, b1)
a0a1xb0b1_a0b0 = gf4_mul(a0 ^ a1, b0 ^ b1) ^ a0b0
rd0 = gf4_mul(2, a1b1)
a0b0 ^= rd0
return a0b0 | a0a1xb0b1_a0b0 << 2
def gf256_mul(a, b):
a0 = a & 15
a1 = a >> 4 & 15
b0 = b & 15
b1 = b >> 4 & 15
ab0 = gf16_mul(a0, b0)
ab1 = gf16_mul(a1, b0) ^ gf16_mul(a0, b1)
ab2 = gf16_mul(a1, b1)
ab0 ^= gf16_mul(ab2, 8)
ab1 ^= ab2
ab0 ^= ab1 << 4
return ab0
def gf216_mul(a, b):
a0 = a & 255
a1 = a >> 8 & 255
b0 = b & 255
b1 = b >> 8 & 255
a0b0 = gf256_mul(a0, b0)
a1b1 = gf256_mul(a1, b1)
a0b1_a1b0 = gf256_mul(a0 ^ a1, b0 ^ b1) ^ a0b0
rd0 = gf256_mul(a1b1, 128)
return a0b1_a1b0 << 8 | rd0 ^ a0b0
def gf65536_mul(a, b):
a0 = a & 255
a1 = a >> 8 & 255
b0 = b & 255
b1 = b >> 8 & 255
ab0 = gf256_mul(a0, b0)
ab2 = gf256_mul(a1, b1)
ab1 = gf256_mul(a0 ^ a1, b0 ^ b1) ^ ab0
return ab1 << 8 ^ (ab0 ^ gf256_mul(ab2, 128))
def gf832_mul(a, b):
a0 = a & 65535
a1 = a >> 16 & 65535
b0 = b & 65535
b1 = b >> 16 & 65535
ab0 = gf65536_mul(a0, b0)
ab2 = gf65536_mul(a1, b1)
ab1 = gf65536_mul(a0 ^ a1, b0 ^ b1) ^ ab0
return ab1 << 16 ^ (ab0 ^ gf65536_mul(ab2, 32768))
def gf832_inv(a):
r = a
for i in range(2, 32):
r = gf832_mul(r, r)
r = gf832_mul(r, a)
return gf832_mul(r, r) |
#Dictionary and Class usage and examples
#cleaning up the input values
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return(mins + '.' + secs)
#reading in the coaches data
def get_coach_data(filename):
try:
with open(filename) as f:
data=f.readline()
return(data.strip().split(','))
except IOError as ioerr:
print('File Error' + str(ioerr))
return(None)
#function call to read in sarah's data
sarah = get_coach_data('sarah2.txt')
'''
#function call to read in sarah's data
sarah = get_coach_data('sarah2.txt')
#(sarah_name, sarah_dob) = sarah.pop(0),sarah.pop(0)
print(sarah_name + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
'''
#shortcoming of this code is that it's only written for Sarah, you would still need to alter
#print statements for each runner, easy with 4 runners, difficult with 4000 runners.
#the three pieces of data about sarah are all disjointed or independent of each other
#Enter the Dictionary (Key/Value Pairs), aka mapping a hash or an associative array
#Keys: Name/DOB/Times Values: sarah's data
#can you have an unlimited number of keys?
#The order the data is added to the dict isn't maintained, but the key/value association is maintained
runnersDict={}
runnersDict['name'] = sarah.pop(0)
runnersDict['dob'] = sarah.pop(0)
runnersDict['times'] = sarah
print(runnersDict['name'] + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
| def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return mins + '.' + secs
def get_coach_data(filename):
try:
with open(filename) as f:
data = f.readline()
return data.strip().split(',')
except IOError as ioerr:
print('File Error' + str(ioerr))
return None
sarah = get_coach_data('sarah2.txt')
' \n#function call to read in sarah\'s data \nsarah = get_coach_data(\'sarah2.txt\')\n\n#(sarah_name, sarah_dob) = sarah.pop(0),sarah.pop(0)\n\nprint(sarah_name + "\'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))\n'
runners_dict = {}
runnersDict['name'] = sarah.pop(0)
runnersDict['dob'] = sarah.pop(0)
runnersDict['times'] = sarah
print(runnersDict['name'] + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3])) |
a1 = 1
a2 = 2
an = a1 + a2
sum_ = a2
print(a1, ',', a2, end=", ")
for n in range(100):
an = a1 + a2
if an > 4000000:
print('\n=== DONE ===')
break
if an % 2 == 0:
sum_ += an
print(an, end=", ")
a1 = a2
a2 = an
print("Even term sum =", sum_) | a1 = 1
a2 = 2
an = a1 + a2
sum_ = a2
print(a1, ',', a2, end=', ')
for n in range(100):
an = a1 + a2
if an > 4000000:
print('\n=== DONE ===')
break
if an % 2 == 0:
sum_ += an
print(an, end=', ')
a1 = a2
a2 = an
print('Even term sum =', sum_) |
# Difficulty Level: Easy
# Question: Filter the dictionary by removing all items with a value of greater
# than 1.
# d = {"a": 1, "b": 2, "c": 3}
# Expected output:
# {'a': 1}
# Hint 1: Use dictionary comprehension.
# Hint 2: Inside the dictionary comprehension access dictionary items with
# d.items() if you are on Python 3, or dict.iteritems() if you are on Python 2
# Program
# Solution 1
d = {"a": 1, "b": 2, "c": 3}
print({ i:j for i,j in d.items() if j <= 1})
# Solution 2
d = {"a": 1, "b": 2, "c": 3}
d = dict((key, value) for key, value in d.items() if value <= 1)
print(d)
# Output
# shubhamvaishnav:python-bootcamp$ python3 21_dictionary_filtering.py
# {'a': 1}
| d = {'a': 1, 'b': 2, 'c': 3}
print({i: j for (i, j) in d.items() if j <= 1})
d = {'a': 1, 'b': 2, 'c': 3}
d = dict(((key, value) for (key, value) in d.items() if value <= 1))
print(d) |
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return factorial(n-1) * n
example = int(input())
print(factorial(example)) | def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return factorial(n - 1) * n
example = int(input())
print(factorial(example)) |
'''
Created on Mar 9, 2019
@author: hzhang0418
'''
| """
Created on Mar 9, 2019
@author: hzhang0418
""" |
r=open('all.protein.faa','r')
w=open('context.processed.all.protein.faa','w')
start = True
mem = ""
for line in r:
if '>' in line and not start:
list_char = list(mem.replace('\n',''))
list_context = []
list_context_length_before = 1
list_context_length_after = 1
for i in range(len(list_char)):
tmp=""
for j in range(i-list_context_length_before,i+list_context_length_after+1):
if j < 0 or j>=len(list_char):
tmp=tmp+'-'
else:
tmp=tmp+list_char[j]
list_context.append(tmp)
w.write (" ".join(list_context)+"\n")
mem = ""
else:
if not start:
mem=mem+line
start = False
r.close()
w.close() | r = open('all.protein.faa', 'r')
w = open('context.processed.all.protein.faa', 'w')
start = True
mem = ''
for line in r:
if '>' in line and (not start):
list_char = list(mem.replace('\n', ''))
list_context = []
list_context_length_before = 1
list_context_length_after = 1
for i in range(len(list_char)):
tmp = ''
for j in range(i - list_context_length_before, i + list_context_length_after + 1):
if j < 0 or j >= len(list_char):
tmp = tmp + '-'
else:
tmp = tmp + list_char[j]
list_context.append(tmp)
w.write(' '.join(list_context) + '\n')
mem = ''
else:
if not start:
mem = mem + line
start = False
r.close()
w.close() |
number = int(input())
dots = ((3 * number) - 1) // 2
print('.' * dots + 'x' + '.' * dots)
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
ex = number
dots = ((3 * number) - ((ex * 2) + 1)) // 2
for i in range(1, (number // 2) + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, (number // 2) + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = ((3 * number) - 1) // 2
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
ex = number
dots = ((3 * number) - ((ex * 2) + 1)) // 2
for i in range(1, (number // 2) + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, (number // 2) + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = ((3 * number) - 1) // 2
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
print('.' * dots + 'x' + '.' * dots) | number = int(input())
dots = (3 * number - 1) // 2
print('.' * dots + 'x' + '.' * dots)
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
ex = number
dots = (3 * number - (ex * 2 + 1)) // 2
for i in range(1, number // 2 + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, number // 2 + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = (3 * number - 1) // 2
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
ex = number
dots = (3 * number - (ex * 2 + 1)) // 2
for i in range(1, number // 2 + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, number // 2 + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = (3 * number - 1) // 2
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
print('.' * dots + 'x' + '.' * dots) |
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
pins = ['x' for _ in range(10)]
p = list(map(int, input().split()))
for pi in p:
pins[pi - 1] = '.'
if b > 0:
q = list(map(int, input().split()))
for qi in q:
pins[qi - 1] = 'o'
print(' '.join(map(str, pins[6:])))
print(' '.join(map(str, pins[3:6])))
print(' '.join(map(str, pins[1:3])))
print(' '.join(map(str, pins[0])))
if __name__ == '__main__':
main()
| def main():
(a, b) = map(int, input().split())
pins = ['x' for _ in range(10)]
p = list(map(int, input().split()))
for pi in p:
pins[pi - 1] = '.'
if b > 0:
q = list(map(int, input().split()))
for qi in q:
pins[qi - 1] = 'o'
print(' '.join(map(str, pins[6:])))
print(' '.join(map(str, pins[3:6])))
print(' '.join(map(str, pins[1:3])))
print(' '.join(map(str, pins[0])))
if __name__ == '__main__':
main() |
'''
Macros Calculator
MIT License
Copyright (c) 2018 Casey Chad Salvador
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. '''
## Variable
weight = float(input("Please enter your current weight: "))
## Create Protein Function
def protein(weight):
fitnessLvl0 = .5
fitnessLvl1 = .75
fitnessLvl2 = 1
fitnessLvl3 = 1.25
fitnessLvl = int(input("Please enter your fitness level (i.e. 1 = New to Training, 2 = In Shape, 3 = Competing, 4 = No Training): "))
if fitnessLvl == 4:
pro = fitnessLvl0 * weight
return pro
elif fitnessLvl == 1:
pro = fitnessLvl1 * weight
return pro
elif fitnessLvl == 2:
pro = fitnessLvl2 * weight
return pro
elif fitnessLvl == 3:
pro = fitnessLvl3 * weight
return pro
## Create Fat Function
def fat(weight):
fat1 = .3
fat2 = .35
fat3 = .4
fatLvl = int(input("Please enter your fat level (i.e. 1 = Love Carbs, 2 = Mix, 3 = Love Fat (nuts, peanut butter, etc): "))
if fatLvl == 1:
fats = fat1 * weight
return fats
elif fatLvl == 2:
fats = fat2 * weight
return fats
elif fatLvl == 3:
fats = fat3 * weight
return fats
## Create Calorie Function
def calories(weight):
cal1 = 14
cal2 = 15
cal3 = 16
calLvl = int(input("Please enter your activity level (i.e. 1 = Less Movement, 2 = Moderately Moving, 3 = Actively Moving): "))
if calLvl == 1:
cal = cal1 * weight
return cal
elif calLvl == 2:
cal = cal2 * weight
return cal
elif calLvl == 3:
cal = cal3 * weight
return cal
cals = calories(weight)
protein = round(protein(weight))
fat = round(fat(weight))
## Create New Physique
def physique(cals):
shred = 500
maintain = 0
gain = 500
phyLvl = input(str("Please enter your physique goal (i.e. shred, maintain, gain): "))
if phyLvl == "shred":
phy = cals - shred
return phy
elif phyLvl == "maintain":
phy = cals - maintain
return phy
elif phyLvl == "gain":
phy = cals + gain
return phy
phyCal= physique(cals)
## Create Caloric Intake Function
# 4 x 9 x 4 Rule Applies Here
def cal(phyCal):
calPro = protein * 4
calFat = fat * 9
sumProFat = calPro + calFat
carbCal = phyCal - sumProFat
return carbCal
carbCal = cal(phyCal)
## Create Carbs Function
def carbs(carbCal):
carb = carbCal / 4
return carb
carb = round(carbs(carbCal))
print("")
## Results
print("Macros")
print("Protein: " + str(protein) + "g")
print("Fat: " + str(fat) + "g")
print("Carbohydrate: " + str(carb) + "g")
print("Total Calories per day: " + str(round(phyCal)) + "cal") | """
Macros Calculator
MIT License
Copyright (c) 2018 Casey Chad Salvador
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. """
weight = float(input('Please enter your current weight: '))
def protein(weight):
fitness_lvl0 = 0.5
fitness_lvl1 = 0.75
fitness_lvl2 = 1
fitness_lvl3 = 1.25
fitness_lvl = int(input('Please enter your fitness level (i.e. 1 = New to Training, 2 = In Shape, 3 = Competing, 4 = No Training): '))
if fitnessLvl == 4:
pro = fitnessLvl0 * weight
return pro
elif fitnessLvl == 1:
pro = fitnessLvl1 * weight
return pro
elif fitnessLvl == 2:
pro = fitnessLvl2 * weight
return pro
elif fitnessLvl == 3:
pro = fitnessLvl3 * weight
return pro
def fat(weight):
fat1 = 0.3
fat2 = 0.35
fat3 = 0.4
fat_lvl = int(input('Please enter your fat level (i.e. 1 = Love Carbs, 2 = Mix, 3 = Love Fat (nuts, peanut butter, etc): '))
if fatLvl == 1:
fats = fat1 * weight
return fats
elif fatLvl == 2:
fats = fat2 * weight
return fats
elif fatLvl == 3:
fats = fat3 * weight
return fats
def calories(weight):
cal1 = 14
cal2 = 15
cal3 = 16
cal_lvl = int(input('Please enter your activity level (i.e. 1 = Less Movement, 2 = Moderately Moving, 3 = Actively Moving): '))
if calLvl == 1:
cal = cal1 * weight
return cal
elif calLvl == 2:
cal = cal2 * weight
return cal
elif calLvl == 3:
cal = cal3 * weight
return cal
cals = calories(weight)
protein = round(protein(weight))
fat = round(fat(weight))
def physique(cals):
shred = 500
maintain = 0
gain = 500
phy_lvl = input(str('Please enter your physique goal (i.e. shred, maintain, gain): '))
if phyLvl == 'shred':
phy = cals - shred
return phy
elif phyLvl == 'maintain':
phy = cals - maintain
return phy
elif phyLvl == 'gain':
phy = cals + gain
return phy
phy_cal = physique(cals)
def cal(phyCal):
cal_pro = protein * 4
cal_fat = fat * 9
sum_pro_fat = calPro + calFat
carb_cal = phyCal - sumProFat
return carbCal
carb_cal = cal(phyCal)
def carbs(carbCal):
carb = carbCal / 4
return carb
carb = round(carbs(carbCal))
print('')
print('Macros')
print('Protein: ' + str(protein) + 'g')
print('Fat: ' + str(fat) + 'g')
print('Carbohydrate: ' + str(carb) + 'g')
print('Total Calories per day: ' + str(round(phyCal)) + 'cal') |
JETBRAINS_IDES = {
'androidstudio': 'Android Studio',
'appcode': 'AppCode',
'datagrip': 'DataGrip',
'goland': 'GoLand',
'intellij': 'IntelliJ IDEA',
'pycharm': 'PyCharm',
'rubymine': 'RubyMine',
'webstorm': 'WebStorm'
}
JETBRAINS_IDE_NAMES = list(JETBRAINS_IDES.values())
| jetbrains_ides = {'androidstudio': 'Android Studio', 'appcode': 'AppCode', 'datagrip': 'DataGrip', 'goland': 'GoLand', 'intellij': 'IntelliJ IDEA', 'pycharm': 'PyCharm', 'rubymine': 'RubyMine', 'webstorm': 'WebStorm'}
jetbrains_ide_names = list(JETBRAINS_IDES.values()) |
mystr="Python is a multipurpose and simply learning langauge"
for i in mystr:
print(i,end=" ")
print()
print(mystr.find("simply"))
print(mystr[0:11]+ " programming")
| mystr = 'Python is a multipurpose and simply learning langauge'
for i in mystr:
print(i, end=' ')
print()
print(mystr.find('simply'))
print(mystr[0:11] + ' programming') |
T1, T2 = map(int, input().split())
n = 1000001
sieve = [True] * n
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True:
for j in range(i + i, n, i):
sieve[j] = False
for i in range(T1, T2 + 1):
if i == 1:
continue
if sieve[i]:
print(i) | (t1, t2) = map(int, input().split())
n = 1000001
sieve = [True] * n
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True:
for j in range(i + i, n, i):
sieve[j] = False
for i in range(T1, T2 + 1):
if i == 1:
continue
if sieve[i]:
print(i) |
#
# Copyright 2012 Sonya Huang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# file that records common things relevant to bea data
use_table_margins = [
"margins", # negative
"rail_margin", "truck_margin", "water_margin", "air_margin",
"pipe_margin", "gaspipe_margin",
"wholesale_margin", "retail_margin"]
FINAL_DEMAND = "f"
VALUE_ADDED = "v"
INTERMEDIATE_OUTPUT = "i"
fd_sectors = {
1972: {"pce": "910000", "imports": "950000", "exports": "940000"},
1977: {"pce": "910000", "imports": "950000", "exports": "940000"},
1982: {"pce": "910000", "imports": "950000", "exports": "940000"},
1987: {"pce": "910000", "imports": "950000", "exports": "940000"},
1992: {"pce": "910000", "imports": "950000", "exports": "940000"},
1997: {"pce": "F01000", "imports": "F05000", "exports": "F04000"},
2002: {"pce": "F01000", "imports": "F05000", "exports": "F04000"},
}
fd_sector_names = {
"total": "All final demand",
"pce": "Personal Consumption Expenditures",
"imports": "Imports",
"exports": "Exports",
}
fd_sector_criteria = {
1972: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
1977: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# based on similarity to 1987
1982: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# http://www.bea.gov/scb/pdf/national/inputout/1994/0494ied.pdf (p84)
1987: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# http://www.bea.gov/scb/account_articles/national/1197io/appxB.htm
1992: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
1997: "code LIKE 'F%'",
2002: "code LIKE 'F%'",
}
va_sector_criteria = {
1972: "code IN ('880000', '890000', '900000')",
1977: "code IN ('880000', '890000', '900000')",
1982: "code IN ('880000', '890000', '900000')",
# http://www.bea.gov/scb/pdf/national/inputout/1994/0494ied.pdf (p115)
1987: "code IN ('880000', '890000', '900000')",
# http://www.bea.gov/scb/account_articles/national/1197io/appxB.htm
1992: "SUBSTRING(code FROM 1 FOR 2) IN ('88', '89', '90')",
1997: "code LIKE 'V%'",
2002: "code LIKE 'V%'",
}
scrap_used_codes = {
1972: ("810000",),
1977: ("810001", "810002"),
1982: ("810001", "810002"),
1987: ("810001", "810002"),
1992: ("810001", "810002"),
1997: ("S00401", "S00402"),
2002: ("S00401", "S00402"),
}
tourism_adjustment_codes = {
1972: '830000',
1977: '830000',
1982: '830000',
1987: '830001',
1992: '830001',
1997: 'S00600',
2002: 'S00900',
}
nipa_groups = [
"Clothing and footwear",
"Financial services and insurance",
"Food and beverages purchased for off-premises consumption",
"Food services and accommodations",
"Furnishings and durable household equipment",
"Gasoline and other energy goods",
"Gross output of nonprofit institutions",
"Health care",
"Housing and utilities",
#"Less: Receipts from sales of goods and services by nonprofit institutions",
"Motor vehicles and parts",
"Other durable goods",
"Other nondurable goods",
"Other services",
"Recreational goods and vehicles",
"Recreation services",
"Transportation services",
]
short_nipa = {
"Clothing and footwear": "Apparel",
"Financial services and insurance": "Financial services",
"Food and beverages purchased for off-premises consumption": "Food products",
"Food services and accommodations": "Food services",
"Gasoline and other energy goods": "Gasoline",
"Other durable goods": "Other durables",
"Other nondurable goods": "Other nondurables",
"Transportation services": "Transport",
"Housing and utilities": "Utilities",
}
standard_sectors = {
1972: ('540200'),
1977: ('540200'),
1982: ('540200'),
1987: ('540200'),
1992: ('540200'),
1997: ('335222'),
2002: ('335222'),
}
| use_table_margins = ['margins', 'rail_margin', 'truck_margin', 'water_margin', 'air_margin', 'pipe_margin', 'gaspipe_margin', 'wholesale_margin', 'retail_margin']
final_demand = 'f'
value_added = 'v'
intermediate_output = 'i'
fd_sectors = {1972: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1977: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1982: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1987: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1992: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1997: {'pce': 'F01000', 'imports': 'F05000', 'exports': 'F04000'}, 2002: {'pce': 'F01000', 'imports': 'F05000', 'exports': 'F04000'}}
fd_sector_names = {'total': 'All final demand', 'pce': 'Personal Consumption Expenditures', 'imports': 'Imports', 'exports': 'Exports'}
fd_sector_criteria = {1972: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1977: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1982: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1987: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1992: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1997: "code LIKE 'F%'", 2002: "code LIKE 'F%'"}
va_sector_criteria = {1972: "code IN ('880000', '890000', '900000')", 1977: "code IN ('880000', '890000', '900000')", 1982: "code IN ('880000', '890000', '900000')", 1987: "code IN ('880000', '890000', '900000')", 1992: "SUBSTRING(code FROM 1 FOR 2) IN ('88', '89', '90')", 1997: "code LIKE 'V%'", 2002: "code LIKE 'V%'"}
scrap_used_codes = {1972: ('810000',), 1977: ('810001', '810002'), 1982: ('810001', '810002'), 1987: ('810001', '810002'), 1992: ('810001', '810002'), 1997: ('S00401', 'S00402'), 2002: ('S00401', 'S00402')}
tourism_adjustment_codes = {1972: '830000', 1977: '830000', 1982: '830000', 1987: '830001', 1992: '830001', 1997: 'S00600', 2002: 'S00900'}
nipa_groups = ['Clothing and footwear', 'Financial services and insurance', 'Food and beverages purchased for off-premises consumption', 'Food services and accommodations', 'Furnishings and durable household equipment', 'Gasoline and other energy goods', 'Gross output of nonprofit institutions', 'Health care', 'Housing and utilities', 'Motor vehicles and parts', 'Other durable goods', 'Other nondurable goods', 'Other services', 'Recreational goods and vehicles', 'Recreation services', 'Transportation services']
short_nipa = {'Clothing and footwear': 'Apparel', 'Financial services and insurance': 'Financial services', 'Food and beverages purchased for off-premises consumption': 'Food products', 'Food services and accommodations': 'Food services', 'Gasoline and other energy goods': 'Gasoline', 'Other durable goods': 'Other durables', 'Other nondurable goods': 'Other nondurables', 'Transportation services': 'Transport', 'Housing and utilities': 'Utilities'}
standard_sectors = {1972: '540200', 1977: '540200', 1982: '540200', 1987: '540200', 1992: '540200', 1997: '335222', 2002: '335222'} |
config_object = {
"org_id": "",
"client_id": "",
"tech_id": "",
"pathToKey": "",
"secret": "",
"date_limit": 0,
"token": "",
"tokenEndpoint": "https://ims-na1.adobelogin.com/ims/exchange/jwt"
}
header = {"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer ",
"x-api-key": ""
}
endpoints = {
"global": 'https://cja.adobe.io'
}
| config_object = {'org_id': '', 'client_id': '', 'tech_id': '', 'pathToKey': '', 'secret': '', 'date_limit': 0, 'token': '', 'tokenEndpoint': 'https://ims-na1.adobelogin.com/ims/exchange/jwt'}
header = {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ', 'x-api-key': ''}
endpoints = {'global': 'https://cja.adobe.io'} |
INITIAL_HPS = {
'image_classifier': [{
'image_block_1/block_type': 'vanilla',
'image_block_1/normalize': True,
'image_block_1/augment': False,
'image_block_1_vanilla/kernel_size': 3,
'image_block_1_vanilla/num_blocks': 1,
'image_block_1_vanilla/separable': False,
'image_block_1_vanilla/dropout_rate': 0.25,
'image_block_1_vanilla/filters_0_1': 32,
'image_block_1_vanilla/filters_0_2': 64,
'spatial_reduction_1/reduction_type': 'flatten',
'dense_block_1/num_layers': 1,
'dense_block_1/use_batchnorm': False,
'dense_block_1/dropout_rate': 0,
'dense_block_1/units_0': 128,
'classification_head_1/dropout_rate': 0.5,
'optimizer': 'adam'
}, {
'image_block_1/block_type': 'resnet',
'image_block_1/normalize': True,
'image_block_1/augment': True,
'image_block_1_resnet/version': 'v2',
'image_block_1_resnet/pooling': 'avg',
'image_block_1_resnet/conv3_depth': 4,
'image_block_1_resnet/conv4_depth': 6,
'dense_block_1/num_layers': 2,
'dense_block_1/use_batchnorm': False,
'dense_block_1/dropout_rate': 0,
'dense_block_1/units_0': 32,
'dense_block_1/units_1': 32,
'classification_head_1/dropout_rate': 0,
'optimizer': 'adam'
}],
}
| initial_hps = {'image_classifier': [{'image_block_1/block_type': 'vanilla', 'image_block_1/normalize': True, 'image_block_1/augment': False, 'image_block_1_vanilla/kernel_size': 3, 'image_block_1_vanilla/num_blocks': 1, 'image_block_1_vanilla/separable': False, 'image_block_1_vanilla/dropout_rate': 0.25, 'image_block_1_vanilla/filters_0_1': 32, 'image_block_1_vanilla/filters_0_2': 64, 'spatial_reduction_1/reduction_type': 'flatten', 'dense_block_1/num_layers': 1, 'dense_block_1/use_batchnorm': False, 'dense_block_1/dropout_rate': 0, 'dense_block_1/units_0': 128, 'classification_head_1/dropout_rate': 0.5, 'optimizer': 'adam'}, {'image_block_1/block_type': 'resnet', 'image_block_1/normalize': True, 'image_block_1/augment': True, 'image_block_1_resnet/version': 'v2', 'image_block_1_resnet/pooling': 'avg', 'image_block_1_resnet/conv3_depth': 4, 'image_block_1_resnet/conv4_depth': 6, 'dense_block_1/num_layers': 2, 'dense_block_1/use_batchnorm': False, 'dense_block_1/dropout_rate': 0, 'dense_block_1/units_0': 32, 'dense_block_1/units_1': 32, 'classification_head_1/dropout_rate': 0, 'optimizer': 'adam'}]} |
file = open('names.txt', 'w')
file.write('amirreza\n')
file.write('setayesh\n')
file.write('artin\n')
file.write('iliya\n')
file.write('mohammadjavad\n')
file.close() | file = open('names.txt', 'w')
file.write('amirreza\n')
file.write('setayesh\n')
file.write('artin\n')
file.write('iliya\n')
file.write('mohammadjavad\n')
file.close() |
CAPACITY = 10
class Heap:
def __init__(self):
self.heap_size = 0
self.heap = [0]*CAPACITY
def insert(self, item):
# when heap is full
if self.heap_size == CAPACITY:
return
self.heap[self.heap_size] = item
self.heap_size += 1
# check heap properties
self.fix_heap(self.heap_size-1)
# starting with actual node inserted to root node, compare values for swap operations-> log(N) operations, O(log(N))
def fix_heap(self, index):
# for node with index i, left child has index = 2i+1, right child has index 2i+2
# hence, reverse the eqn-> l = 2i+1, r = 2i+2-> i=l-1/2
parent_index = (index - 1)//2
# now consider all items above til root node, if heap prop is violated then swap parent with child
if index > 0 and self.heap[index] > self.heap[parent_index]:
self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index]
self.fix_heap(parent_index)
def get_max_item(self):
return self.heap[0]
# return the max element and remove it from the heap
def poll_heap(self):
max_item = self.get_max_item()
# swap the root with the last item
self.heap[0], self.heap[self.heap_size-1] = self.heap[self.heap_size-1], self.heap[0]
self.heap_size -= 1
# now perform heapify operation
self.heapify(0)
return max_item
# start from root node and rearrange heap to make sure heap properties are not violated, O(log(N))
def heapify(self, index):
index_left = 2 * index + 1
index_right = 2 * index + 2
largest_index = index
# look for the largest(parent or left node)
if index_left < self.heap_size and self.heap[index_left] > self.heap[index]:
largest_index = index_left
# if right child > left child, then largest_index = right child
if index_right < self.heap_size and self.heap[index_right] > self.heap[index]:
largest_index = index_right
# If parent larger than child: it is valid heap and we terminate all recursive calls further
if index != largest_index:
self.heap[index], self.heap[largest_index] = self.heap[largest_index], self.heap[index]
self.heapify(largest_index)
# O(Nlog(N)) -> N items and O(logN) for poll_heap operation
def heap_sort(self):
for _ in range(self.heap_size):
max_item = self.poll_heap()
print(max_item)
if __name__ == "__main__":
heap = Heap()
heap.insert(13)
heap.insert(-2)
heap.insert(0)
heap.insert(8)
heap.insert(1)
heap.insert(-5)
heap.insert(99)
heap.insert(100)
print(heap.heap)
print("----------------------------")
heap.heap_sort()
| capacity = 10
class Heap:
def __init__(self):
self.heap_size = 0
self.heap = [0] * CAPACITY
def insert(self, item):
if self.heap_size == CAPACITY:
return
self.heap[self.heap_size] = item
self.heap_size += 1
self.fix_heap(self.heap_size - 1)
def fix_heap(self, index):
parent_index = (index - 1) // 2
if index > 0 and self.heap[index] > self.heap[parent_index]:
(self.heap[index], self.heap[parent_index]) = (self.heap[parent_index], self.heap[index])
self.fix_heap(parent_index)
def get_max_item(self):
return self.heap[0]
def poll_heap(self):
max_item = self.get_max_item()
(self.heap[0], self.heap[self.heap_size - 1]) = (self.heap[self.heap_size - 1], self.heap[0])
self.heap_size -= 1
self.heapify(0)
return max_item
def heapify(self, index):
index_left = 2 * index + 1
index_right = 2 * index + 2
largest_index = index
if index_left < self.heap_size and self.heap[index_left] > self.heap[index]:
largest_index = index_left
if index_right < self.heap_size and self.heap[index_right] > self.heap[index]:
largest_index = index_right
if index != largest_index:
(self.heap[index], self.heap[largest_index]) = (self.heap[largest_index], self.heap[index])
self.heapify(largest_index)
def heap_sort(self):
for _ in range(self.heap_size):
max_item = self.poll_heap()
print(max_item)
if __name__ == '__main__':
heap = heap()
heap.insert(13)
heap.insert(-2)
heap.insert(0)
heap.insert(8)
heap.insert(1)
heap.insert(-5)
heap.insert(99)
heap.insert(100)
print(heap.heap)
print('----------------------------')
heap.heap_sort() |
src = Split('''
ota_service.c
ota_util.c
ota_update_manifest.c
ota_version.c
''')
component = aos_component('fota', src)
dependencis = Split('''
framework/fota/platform
framework/fota/download
utility/digest_algorithm
utility/cjson
''')
for i in dependencis:
component.add_comp_deps(i)
component.add_global_includes('.')
component.add_global_macros('AOS_FOTA')
| src = split('\n ota_service.c\n ota_util.c\n ota_update_manifest.c\n ota_version.c\n')
component = aos_component('fota', src)
dependencis = split('\n framework/fota/platform\n framework/fota/download \n utility/digest_algorithm \n utility/cjson \n')
for i in dependencis:
component.add_comp_deps(i)
component.add_global_includes('.')
component.add_global_macros('AOS_FOTA') |
# Works only with a good seed
# You need the Emperor's gloves to cast "Chain Lightning"
hero.cast("chain-lightning", hero.findNearestEnemy())
| hero.cast('chain-lightning', hero.findNearestEnemy()) |
def main():
rst = bf_cal()
print(f"{rst[0]}^5 + {rst[1]}^5 + {rst[2]}^5 + {rst[3]}^5 = {rst[4]}^5")
def bf_cal():
max_n = 250
pwr_pool = [n ** 5 for n in range(max_n)]
y_pwr_pool = {n ** 5: n for n in range(max_n)}
for x0 in range(1, max_n):
print(f"processing {x0} in (0..250)")
for x1 in range(x0, max_n):
for x2 in range(x1, max_n):
for x3 in range(x2, max_n):
y_pwr5 = sum(pwr_pool[i] for i in (x0, x1, x2, x3))
if y_pwr5 in y_pwr_pool:
y = y_pwr_pool[y_pwr5]
if y not in (x0, x1, x2, x3):
return x0, x1, x2, x3, y
if __name__ == "__main__":
main()
# 27^5 + 84^5 + 110^5 + 133^5 = 144^5
| def main():
rst = bf_cal()
print(f'{rst[0]}^5 + {rst[1]}^5 + {rst[2]}^5 + {rst[3]}^5 = {rst[4]}^5')
def bf_cal():
max_n = 250
pwr_pool = [n ** 5 for n in range(max_n)]
y_pwr_pool = {n ** 5: n for n in range(max_n)}
for x0 in range(1, max_n):
print(f'processing {x0} in (0..250)')
for x1 in range(x0, max_n):
for x2 in range(x1, max_n):
for x3 in range(x2, max_n):
y_pwr5 = sum((pwr_pool[i] for i in (x0, x1, x2, x3)))
if y_pwr5 in y_pwr_pool:
y = y_pwr_pool[y_pwr5]
if y not in (x0, x1, x2, x3):
return (x0, x1, x2, x3, y)
if __name__ == '__main__':
main() |
sq_sum, sum = 0, 0
for i in range(1, 101):
sq_sum = sq_sum + (i * i)
sum = sum + i
print((sum * sum) - sq_sum)
| (sq_sum, sum) = (0, 0)
for i in range(1, 101):
sq_sum = sq_sum + i * i
sum = sum + i
print(sum * sum - sq_sum) |
class NotFoundException(Exception):
pass
class BadRequestException(Exception):
pass
class JobExistsException(Exception):
pass
class NoSuchImportableDataset(Exception):
pass
| class Notfoundexception(Exception):
pass
class Badrequestexception(Exception):
pass
class Jobexistsexception(Exception):
pass
class Nosuchimportabledataset(Exception):
pass |
n = int(input('Enter A Number: '))
def findFactors(num):
arr = []
for x in range(1, n + 1 ,1):
if num % x == 0:
arr.append(x)
return arr
if len(findFactors(n)) == 2: # Array will have 1 and the number itself
print(f"{n} Is Prime.")
else :
print(f"{n} Is Composite") | n = int(input('Enter A Number: '))
def find_factors(num):
arr = []
for x in range(1, n + 1, 1):
if num % x == 0:
arr.append(x)
return arr
if len(find_factors(n)) == 2:
print(f'{n} Is Prime.')
else:
print(f'{n} Is Composite') |
'''
Created on 1.12.2016
@author: Darren
'''
'''
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.
'''
| """
Created on 1.12.2016
@author: Darren
"""
'\nGiven a binary search tree and a node in it, find the in-order successor of that node in the BST.\n\nNote: If the given node has no in-order successor in the tree, return null.\n' |
def printCommands():
print("Congratulations! You're running Ryan's Task list program.")
print("What would you like to do next?")
print("1. List all tasks.")
print("2. Add a task to the list.")
print("3. Delete a task.")
print("q. To quit the program")
printCommands()
aTaskListArray = ["bob", "dave"]
userSelection = input('Enter a command: ')
if userSelection == "1":
for itemList in aTaskListArray:
print(itemList)
userSelection = input('Enter a command: ')
if userSelection == "2":
newTask = input("What would you like to add? ")
aTaskListArray.append(newTask)
userSelection = input("Enter a command: ")
if userSelection == "3":
newTask = input("What would you like to remove? ")
aTaskListArray.remove(newTask)
userSelection = input("Enter a command: ")
if userSelection == "q":
quit()
else:
print("Not a command")
print(aTaskListArray) | def print_commands():
print("Congratulations! You're running Ryan's Task list program.")
print('What would you like to do next?')
print('1. List all tasks.')
print('2. Add a task to the list.')
print('3. Delete a task.')
print('q. To quit the program')
print_commands()
a_task_list_array = ['bob', 'dave']
user_selection = input('Enter a command: ')
if userSelection == '1':
for item_list in aTaskListArray:
print(itemList)
user_selection = input('Enter a command: ')
if userSelection == '2':
new_task = input('What would you like to add? ')
aTaskListArray.append(newTask)
user_selection = input('Enter a command: ')
if userSelection == '3':
new_task = input('What would you like to remove? ')
aTaskListArray.remove(newTask)
user_selection = input('Enter a command: ')
if userSelection == 'q':
quit()
else:
print('Not a command')
print(aTaskListArray) |
data = open("input.txt", "r")
data = data.read().split(",")
check = True
index = 0
while check is True:
section = data[index]
firstNum = int(data[int(data[index + 1])])
secondNum = int(data[int(data[index + 2])])
if section == "1":
total = firstNum + secondNum
if section == "2":
total = firstNum * secondNum
data[int(data[index + 3])] = str(total)
if data[index + 4] == "99":
check = False
index = index + 4
print("Your answer is... " + data[0]) | data = open('input.txt', 'r')
data = data.read().split(',')
check = True
index = 0
while check is True:
section = data[index]
first_num = int(data[int(data[index + 1])])
second_num = int(data[int(data[index + 2])])
if section == '1':
total = firstNum + secondNum
if section == '2':
total = firstNum * secondNum
data[int(data[index + 3])] = str(total)
if data[index + 4] == '99':
check = False
index = index + 4
print('Your answer is... ' + data[0]) |
mod = 10**9 + 7
n = int(input())
a = list(map(int, input().split()))
answer = 0
sumation = sum(a)
for i in range(n-1):
sumation -= a[i]
answer += a[i]*sumation
answer %= mod
print(answer)
| mod = 10 ** 9 + 7
n = int(input())
a = list(map(int, input().split()))
answer = 0
sumation = sum(a)
for i in range(n - 1):
sumation -= a[i]
answer += a[i] * sumation
answer %= mod
print(answer) |
{
"targets": [
{
"target_name": "sharedMemory",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")"
],
"sources": [ "./src/sharedMemory.cpp" ],
"libraries": [],
},
{
"target_name": "messaging",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")"
],
"sources": [ "./src/messaging.cpp" ],
"libraries": [],
}
]
} | {'targets': [{'target_name': 'sharedMemory', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")'], 'sources': ['./src/sharedMemory.cpp'], 'libraries': []}, {'target_name': 'messaging', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")'], 'sources': ['./src/messaging.cpp'], 'libraries': []}]} |
def protected(func):
def wrapper(password):
if password=='platzi':
return func()
else:
print('Contrasena invalida')
return wrapper
@protected
def protected_func():
print('To contrasena es correcta')
if __name__ == "__main__":
password=str(raw_input('Ingresa tu contrasena: '))
# wrapper=protected(protected_func)
# wrapper(password)
protected_func(password) | def protected(func):
def wrapper(password):
if password == 'platzi':
return func()
else:
print('Contrasena invalida')
return wrapper
@protected
def protected_func():
print('To contrasena es correcta')
if __name__ == '__main__':
password = str(raw_input('Ingresa tu contrasena: '))
protected_func(password) |
s=input()
if s[-1] in '24579':
print('hon')
elif s[-1] in '0168':
print('pon')
else:
print('bon') | s = input()
if s[-1] in '24579':
print('hon')
elif s[-1] in '0168':
print('pon')
else:
print('bon') |
# Text Type: str
# Numeric Types: int, float, complex
# Sequence Types: list, tuple, range
# Mapping Type: dict
# Set Types: set, frozenset
# Boolean Type: bool
# Binary Types: bytes, bytearray, memoryview
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
print("--------------------------------------------------------")
num =6
print(num)
print(str(num)+ " is my num")
# print(num + "my num")
# print(num + "my num") - will not work
print("--------------------------------------------------------")
| x = float(1)
y = float(2.8)
z = float('3')
w = float('4.2')
print('--------------------------------------------------------')
num = 6
print(num)
print(str(num) + ' is my num')
print('--------------------------------------------------------') |
TRAIN_DATA_PATH = "data/processed/train_folds.csv"
TEST_DATA_PATH = "data/processed/test.csv"
MODEL_PATH = "models/"
NUM_FOLDS = 5
SEED = 23
VERBOSE = 0
FEATURE_COLS = [
"Pclass",
"Sex",
"Age",
"SibSp",
"Parch",
"Ticket",
"Fare",
"Cabin",
"Embarked",
"Title",
"Surname",
"Family_Size",
]
TARGET_COL = "Survived"
| train_data_path = 'data/processed/train_folds.csv'
test_data_path = 'data/processed/test.csv'
model_path = 'models/'
num_folds = 5
seed = 23
verbose = 0
feature_cols = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked', 'Title', 'Surname', 'Family_Size']
target_col = 'Survived' |
def parse_ninja():
f = open('out/peerconnection_client.ninja', 'r')
for line in f.readlines():
lines = line.split(" ")
for l in lines:
print(l)
f.close()
def create_list_of_libs():
f = open('out/client_libs.txt', 'r')
for line in f.readlines():
segments = line.strip().split('/')
print('PUBLIC ' + segments[len(segments)-1].split('.')[0].upper())
f.close()
def main():
create_list_of_libs()
if __name__ == '__main__':
main()
| def parse_ninja():
f = open('out/peerconnection_client.ninja', 'r')
for line in f.readlines():
lines = line.split(' ')
for l in lines:
print(l)
f.close()
def create_list_of_libs():
f = open('out/client_libs.txt', 'r')
for line in f.readlines():
segments = line.strip().split('/')
print('PUBLIC ' + segments[len(segments) - 1].split('.')[0].upper())
f.close()
def main():
create_list_of_libs()
if __name__ == '__main__':
main() |
#(n-1)%M = x - 1
#(n-1)%N = y - 1
gcd = lambda a,b: gcd(b,a%b) if b else a
def finder(M,N,x,y):
for i in range(N//gcd(M,N)):
if (x-1+i*M)%N==y-1:
return x+i*M
return -1
for _ in range(int(input())):
M,N,x,y = map(int,input().split())
print(finder(M,N,x,y))
| gcd = lambda a, b: gcd(b, a % b) if b else a
def finder(M, N, x, y):
for i in range(N // gcd(M, N)):
if (x - 1 + i * M) % N == y - 1:
return x + i * M
return -1
for _ in range(int(input())):
(m, n, x, y) = map(int, input().split())
print(finder(M, N, x, y)) |
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(
type='PoseDetDetector',
pretrained='pretrained/dla34-ba72cf86.pth',
# pretrained='open-mmlab://msra/hrnetv2_w32',
backbone=dict(
type='DLA',
return_levels=True,
levels=[1, 1, 1, 2, 2, 1],
channels=[16, 32, 64, 128, 256, 512],
ouput_indice=[3,4,5,6],
),
neck=dict(
type='FPN',
in_channels=[64, 128, 256, 512],
out_channels=128,
start_level=1,
add_extra_convs='on_input',
num_outs=4,
# num_outs=3,
norm_cfg=norm_cfg,),
bbox_head=dict(
# type='PoseDetHead',
type='PoseDetHeadHeatMapMl',
norm_cfg=norm_cfg,
num_classes=1,
in_channels=128,
feat_channels=128,
embedding_feat_channels=128,
init_convs=3,
refine_convs=2,
cls_convs=2,
gradient_mul=0.1,
dcn_kernel=(1,17),
refine_num=1,
point_strides=[8, 16, 32, 64],
point_base_scale=4,
num_keypoints=17,
loss_cls=dict(
type='FocalLoss',
use_sigmoid=True,
gamma=2.0,
alpha=0.25,
loss_weight=1.0),
loss_keypoints_init=dict(type='KeypointsLoss',
d_type='L2',
weight=.1,
stage='init',
normalize_factor=1,
),
loss_keypoints_refine=dict(type='KeypointsLoss',
d_type='L2',
weight=.2,
stage='refine',
normalize_factor=1,
),
loss_heatmap=dict(type='HeatmapLoss', weight=.1, with_sigmas=False),
)
)
# training and testing settings
train_cfg = dict(
init=dict(
assigner=dict(type='KeypointsAssigner',
scale=4,
pos_num=1,
number_keypoints_thr=3,
num_keypoints=17,
center_type='keypoints',
# center_type='box'
),
allowed_border=-1,
pos_weight=-1,
debug=False),
refine=dict(
assigner=dict(
type='OksAssigner',
pos_PD_thr=0.7,
neg_PD_thr=0.7,
min_pos_iou=0.52,
ignore_iof_thr=-1,
match_low_quality=True,
num_keypoints=17,
number_keypoints_thr=3, #
),
allowed_border=-1,
pos_weight=-1,
debug=False
),
cls=dict(
assigner=dict(
type='OksAssigner',
pos_PD_thr=0.6,
neg_PD_thr=0.5,
min_pos_iou=0.5,
ignore_iof_thr=-1,
match_low_quality=False,
num_keypoints=17,
number_keypoints_thr=3,
),
allowed_border=-1,
pos_weight=-1,
debug=False
),
)
test_cfg = dict(
nms_pre=500,
min_bbox_size=0,
score_thr=0.05,
nms=dict(type='keypoints_nms', iou_thr=0.2),
max_per_img=100) | norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(type='PoseDetDetector', pretrained='pretrained/dla34-ba72cf86.pth', backbone=dict(type='DLA', return_levels=True, levels=[1, 1, 1, 2, 2, 1], channels=[16, 32, 64, 128, 256, 512], ouput_indice=[3, 4, 5, 6]), neck=dict(type='FPN', in_channels=[64, 128, 256, 512], out_channels=128, start_level=1, add_extra_convs='on_input', num_outs=4, norm_cfg=norm_cfg), bbox_head=dict(type='PoseDetHeadHeatMapMl', norm_cfg=norm_cfg, num_classes=1, in_channels=128, feat_channels=128, embedding_feat_channels=128, init_convs=3, refine_convs=2, cls_convs=2, gradient_mul=0.1, dcn_kernel=(1, 17), refine_num=1, point_strides=[8, 16, 32, 64], point_base_scale=4, num_keypoints=17, loss_cls=dict(type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_keypoints_init=dict(type='KeypointsLoss', d_type='L2', weight=0.1, stage='init', normalize_factor=1), loss_keypoints_refine=dict(type='KeypointsLoss', d_type='L2', weight=0.2, stage='refine', normalize_factor=1), loss_heatmap=dict(type='HeatmapLoss', weight=0.1, with_sigmas=False)))
train_cfg = dict(init=dict(assigner=dict(type='KeypointsAssigner', scale=4, pos_num=1, number_keypoints_thr=3, num_keypoints=17, center_type='keypoints'), allowed_border=-1, pos_weight=-1, debug=False), refine=dict(assigner=dict(type='OksAssigner', pos_PD_thr=0.7, neg_PD_thr=0.7, min_pos_iou=0.52, ignore_iof_thr=-1, match_low_quality=True, num_keypoints=17, number_keypoints_thr=3), allowed_border=-1, pos_weight=-1, debug=False), cls=dict(assigner=dict(type='OksAssigner', pos_PD_thr=0.6, neg_PD_thr=0.5, min_pos_iou=0.5, ignore_iof_thr=-1, match_low_quality=False, num_keypoints=17, number_keypoints_thr=3), allowed_border=-1, pos_weight=-1, debug=False))
test_cfg = dict(nms_pre=500, min_bbox_size=0, score_thr=0.05, nms=dict(type='keypoints_nms', iou_thr=0.2), max_per_img=100) |
# Exceptions
class SequenceFieldException(Exception):
pass
| class Sequencefieldexception(Exception):
pass |
try:
x = int(input("X: "))
except ValueError:
print("That is not an int!")
exit()
try:
y = int(input("Y: "))
except ValueError:
print("That is not an int!")
exit()
print (x + y) | try:
x = int(input('X: '))
except ValueError:
print('That is not an int!')
exit()
try:
y = int(input('Y: '))
except ValueError:
print('That is not an int!')
exit()
print(x + y) |
# Design Linked List
class ListNode:
def __init__(self, x):
self.value = x
self.next = None
class LinkedList:
def __init__(self):
self.size = 0
self.head = ListNode(0) # Sentinel Node as psuedo-head
# add at head
def addAtHead(self, val):
self.addAtHead(0, val)
# add at tail
def addAtTail(self, val):
self.addAtTail(self.size, val)
# add at index
def addAtIndex(self, index, val):
if index > self.size:
return
if index < 0:
index = 0
self.size += 1
# predecessor of the node
prd = self.head
for _ in range(index):
prd = prd.next
# node to be added
to_add = ListNode(val)
# Insert
to_add.next = prd.next
prd.next = to_add
# delete at index
def delAtIndex(self,index):
if index < 0 or index >= index.size:
return
self.size -= 1
prd = self.head
for _ in range(index):
prd = prd.next
prd.next = prd.next.next
# get element
def getElement(self,index):
if index < 0 or index >= self.size:
return -1
curr = self.head
for _ in range(index + 1):
curr = curr.next
return curr.val
| class Listnode:
def __init__(self, x):
self.value = x
self.next = None
class Linkedlist:
def __init__(self):
self.size = 0
self.head = list_node(0)
def add_at_head(self, val):
self.addAtHead(0, val)
def add_at_tail(self, val):
self.addAtTail(self.size, val)
def add_at_index(self, index, val):
if index > self.size:
return
if index < 0:
index = 0
self.size += 1
prd = self.head
for _ in range(index):
prd = prd.next
to_add = list_node(val)
to_add.next = prd.next
prd.next = to_add
def del_at_index(self, index):
if index < 0 or index >= index.size:
return
self.size -= 1
prd = self.head
for _ in range(index):
prd = prd.next
prd.next = prd.next.next
def get_element(self, index):
if index < 0 or index >= self.size:
return -1
curr = self.head
for _ in range(index + 1):
curr = curr.next
return curr.val |
# -*- coding:utf-8 -*-
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
| pizza = {'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese']} |
# You may remember by now that while loops use the condition to check when
# to exit. The body of the while loop needs to make sure that the condition begin
# checked will change. If it doesn't change, the loop may never finish and we get
# what's called an infinite loop, a loop that keeps executing and never stops.
# Check out this example. It uses the modulo operator that we saw a while back.
# This cycle will finish for positive and negative values of x. But what would
# happen if x was zero? The remainder of 0 divided by 2 is 0, so the condition
# would be true. The result of dividing 0 by 2 would also be zero, so the value of
# x wouldn't change. This loop would go on for ever, and so we'd get an infinite
# loop. If our code was called with x having the value of zero, the computer
# would just waster resources doing a division that would never lead to the loop
# stopping. The program would be stuck in an infinite loop circling background
# endlessly, and we don't want that. All that looping might make your computer
# dizzy. To avoid this, we need to think about what needs to be different than zero.
# So we could nest this while loop inside an if statement just like this. With this
# approach, the while loop is executed only when x is not zero. Alternatively, we
# could add the condition directly to the loop using a logical operator like in this
# example. This makes sure we only enter the body of the loop for values of x
# that are both different than zero and even. Talking about infinite loop reminds
# me of one of the first times I used while loops myself. I wrote a script that
# emailed me as a way of verifying that the code worked, and while some
# condition was true, I forgot to exit the loop. Turns out those e-mails get sent
# faster than once per second. As you can imagine, I got about 500 e-mails
# before I realized what was going on. Infinitely grateful for that little lesson.
# When you're done laughing at my story, remember, when you're writing loops,
# it's a good idea to take a moment to consider the different values a variable
# can take. This helps you make sure your loop won't get stuck, If you see that
# your program is running forever without finishing, have a second look at your
# loops to check there's no infinite loop hiding somewhere in the code. While
# you need to watch out for infinite loops, they are not always a bad thing.
# Sometimes you actually want your program to execute continuously until
# some external condition is met. If you've used the ping utility on Linux or
# macOS system, or ping-t on a Windows system, you've seen an infinite loop in
# action. This tool will keep sending packets and printing the results to the
# terminal unless you send it the interrupt signal, usually pressing Ctrl+C. If you
# were looking at the program source code you'll see that it uses an infinite loop
# to do hits with a block of code with instructions to keep sending the packets
# forever. One thing to call out is it should always be possible to break the loop
# by sending a certain signal. In the ping example, that signal is the user pressing
# Ctrl+C. In other cases, it could be that the user pressed the button on a
# graphical application, or that another program sent a specific signal, or even
# that a time limit was reached. In your code, you could have an infinite loop that
# looks something like this. In Python, we use the break keyword which you can
# see here to signal that the current loop should stop running. We can use it not
# only to stop infinite loops but also to stop a loop early if the code has already
# achieved what's needed. So quick refresh. How do you avoid the most
# common pitfalls when writing while loops? First, remember to initialize your
# variables, and second, check that your loops won't run forever. Wow, All this
# talk of loops is making me feel a little loopy. I'm going to have to go and lie
# down while you do the next practice quiz. Best of luck, and meet me over in
# the next video when you're done.
# The following code causes an infinite loop. Can you figure out what's missing
# and how to fix it?
def print_range(start, end):
# Loop through the numbers from stand to end
n = start
while n <= end:
print(n)
n += 1
print_range(1, 5) # Should print 1 2 3 4 5 (each number on its own line)
| def print_range(start, end):
n = start
while n <= end:
print(n)
n += 1
print_range(1, 5) |
DOMAIN = "audiconnect"
CONF_VIN = "vin"
CONF_CARNAME = "carname"
CONF_ACTION = "action"
MIN_UPDATE_INTERVAL = 5
DEFAULT_UPDATE_INTERVAL = 10
CONF_SPIN = "spin"
CONF_REGION = "region"
CONF_SERVICE_URL = "service_url"
CONF_MUTABLE = "mutable"
SIGNAL_STATE_UPDATED = "{}.updated".format(DOMAIN)
TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
RESOURCES = [
"position",
"last_update_time",
"mileage",
"range",
"service_inspection_time",
"service_inspection_distance",
"oil_change_time",
"oil_change_distance",
"oil_level",
"charging_state",
"max_charge_current",
"engine_type1",
"engine_type2",
"parking_light",
"any_window_open",
"any_door_unlocked",
"any_door_open",
"trunk_unlocked",
"trunk_open",
"hood_open",
"tank_level",
"state_of_charge",
"remaining_charging_time",
"plug_state",
"sun_roof",
"doors_trunk_status",
]
COMPONENTS = {
"sensor": "sensor",
"binary_sensor": "binary_sensor",
"lock": "lock",
"device_tracker": "device_tracker",
"switch": "switch",
}
| domain = 'audiconnect'
conf_vin = 'vin'
conf_carname = 'carname'
conf_action = 'action'
min_update_interval = 5
default_update_interval = 10
conf_spin = 'spin'
conf_region = 'region'
conf_service_url = 'service_url'
conf_mutable = 'mutable'
signal_state_updated = '{}.updated'.format(DOMAIN)
tracker_update = f'{DOMAIN}_tracker_update'
resources = ['position', 'last_update_time', 'mileage', 'range', 'service_inspection_time', 'service_inspection_distance', 'oil_change_time', 'oil_change_distance', 'oil_level', 'charging_state', 'max_charge_current', 'engine_type1', 'engine_type2', 'parking_light', 'any_window_open', 'any_door_unlocked', 'any_door_open', 'trunk_unlocked', 'trunk_open', 'hood_open', 'tank_level', 'state_of_charge', 'remaining_charging_time', 'plug_state', 'sun_roof', 'doors_trunk_status']
components = {'sensor': 'sensor', 'binary_sensor': 'binary_sensor', 'lock': 'lock', 'device_tracker': 'device_tracker', 'switch': 'switch'} |
class Mouse:
__slots__=(
'_system_cursor',
'has_mouse'
)
def __init__(self):
self._system_cursor = ez.window.panda_winprops.get_cursor_filename()
self.has_mouse = ez.panda_showbase.mouseWatcherNode.has_mouse
def hide(self):
ez.window.panda_winprops.set_cursor_hidden(True)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
def show(self):
ez.window.panda_winprops.set_cursor_hidden(False)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@property
def cursor(self):
return ez.window.panda_winprops.get_cursor_filename()
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@cursor.setter
def cursor(self, cursor):
if cursor:
ez.window.panda_winprops.set_cursor_filename(cursor)
else:
ez.window.panda_winprops.set_cursor_filename(self._system_cursor)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@property
def mouse_pos(self):
return ez.panda_showbase.mouseWatcherNode.get_mouse()
@property
def pos(self):
# Convert mouse coordinates to aspect2D coordinates:
mpos = ez.panda_showbase.mouseWatcherNode.get_mouse()
pos = aspect2d.get_relative_point(render, (mpos.x, mpos.y, 0))
return pos.xy
@pos.setter
def pos(self, pos):
# Have to convert aspect2D position to window coordinates:
x, y = pos
w, h = ez.panda_showbase.win.get_size()
cpos = ez.panda_showbase.camera2d.get_pos()
L, R, T, B = ez.window.get_aspect2D_edges()
# Get aspect2D size:
aw = R-L
ah = T-B
# Get mouse pos equivalent to window cordinates:
mx = x+R
my = abs(y+B)
# Convert the mouse pos to window position:
x = mx/aw*w
y = my/ah*h
ez.panda_showbase.win.move_pointer(0, round(x), round(y)) | class Mouse:
__slots__ = ('_system_cursor', 'has_mouse')
def __init__(self):
self._system_cursor = ez.window.panda_winprops.get_cursor_filename()
self.has_mouse = ez.panda_showbase.mouseWatcherNode.has_mouse
def hide(self):
ez.window.panda_winprops.set_cursor_hidden(True)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
def show(self):
ez.window.panda_winprops.set_cursor_hidden(False)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@property
def cursor(self):
return ez.window.panda_winprops.get_cursor_filename()
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@cursor.setter
def cursor(self, cursor):
if cursor:
ez.window.panda_winprops.set_cursor_filename(cursor)
else:
ez.window.panda_winprops.set_cursor_filename(self._system_cursor)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@property
def mouse_pos(self):
return ez.panda_showbase.mouseWatcherNode.get_mouse()
@property
def pos(self):
mpos = ez.panda_showbase.mouseWatcherNode.get_mouse()
pos = aspect2d.get_relative_point(render, (mpos.x, mpos.y, 0))
return pos.xy
@pos.setter
def pos(self, pos):
(x, y) = pos
(w, h) = ez.panda_showbase.win.get_size()
cpos = ez.panda_showbase.camera2d.get_pos()
(l, r, t, b) = ez.window.get_aspect2D_edges()
aw = R - L
ah = T - B
mx = x + R
my = abs(y + B)
x = mx / aw * w
y = my / ah * h
ez.panda_showbase.win.move_pointer(0, round(x), round(y)) |
n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
f = input().split()
if (f[0] == "pop"):
s.pop()
elif (f[0] == "remove"):
s.remove(int(f[-1]))
else:
s.discard(int(f[-1]))
print(sum(s)) | n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
f = input().split()
if f[0] == 'pop':
s.pop()
elif f[0] == 'remove':
s.remove(int(f[-1]))
else:
s.discard(int(f[-1]))
print(sum(s)) |
# ------------------------------------------------------------------------------------
# Tutorial: Learn how to use Dictionaries in Python
# ------------------------------------------------------------------------------------
# Dictionaries are a collection of key-value pairs.
# Keys can only appear once in a dictionary but can be of any type.
# Dictionaries are unordered.
# Values can appear in any number of keys.
# Keys can be of almost any type, values can be of any type.
# Defining a dictionary
# Dictionaries are assigned using a pair of curly brackets.
# Key pair values are assigned within the curly brackets with a : between the key and value
# Each pair is separated by a comma
my_dict = {
'my_key': 'my value',
'your_key': 42,
5: 10,
'speed': 20.0,
}
# Assigning key-value pairs
# Adding key pairs to an existing dictionary
my_dict['their_key'] = 3.142
# Retreiving a value
retrieved = my_dict['my_key']
print("Value of 'my_key': " + str(retrieved)) # Should print "Value of 'my_key': my value"
retrieved = my_dict.get('your_key')
print("Value of 'your_key': " + str(retrieved)) # Should print "Value of 'your_key': 42"
# With either of the above options Python will throw a key error if the key doesn't exist.
# To fix this dictionary.get() can be used to return a default value if no key exists
retrieved = my_dict.get('non_existent_key', 'Not here.')
print("Value of 'non_existent_key': " + str(retrieved)) # Should print "Value of 'non_existent_key' not here"
print("")
# ------------------------------------------------------------------------------------
# Challenge: Create a dictionary called person.
# The person dictionary should contain the following keys:
# name, height, age
# With the following values:
# 'Sally', 154.9, 15
# Add a key called occupation with value 'student'
# Update the value of age to 18
# Remember to uncomment the print lines
# You should see the output
# Person is called Sally
# Person is 18
# Person is 154.9cm
# Person is student
# ------------------------------------------------------------------------------------
# Define person dictionary here
# Add occupation key here
# Increase the age to 18 here
# Uncomment the lines below once you have completed the challenge
# print("Person is called " + str(person.get("name", "Unnamed")))
# print("Person is " + str(person.get("age", "Ageless")))
# print("Person is " + str(person.get("height", "Tiny")) + "cm")
# print("Person is " + str(person.get("occupation", "Unemployed")))
| my_dict = {'my_key': 'my value', 'your_key': 42, 5: 10, 'speed': 20.0}
my_dict['their_key'] = 3.142
retrieved = my_dict['my_key']
print("Value of 'my_key': " + str(retrieved))
retrieved = my_dict.get('your_key')
print("Value of 'your_key': " + str(retrieved))
retrieved = my_dict.get('non_existent_key', 'Not here.')
print("Value of 'non_existent_key': " + str(retrieved))
print('') |
def setup():
noLoop()
size(500, 500)
noStroke()
smooth()
def draw():
background(50)
fill(94, 206, 40, 100)
ellipse(250, 100, 160, 160)
fill(94, 206, 40, 150)
ellipse(250, 200, 160, 160)
fill(94, 206, 40, 200)
ellipse(250, 300, 160, 160)
fill(94, 206, 40, 250)
ellipse(250, 400, 160, 160)
| def setup():
no_loop()
size(500, 500)
no_stroke()
smooth()
def draw():
background(50)
fill(94, 206, 40, 100)
ellipse(250, 100, 160, 160)
fill(94, 206, 40, 150)
ellipse(250, 200, 160, 160)
fill(94, 206, 40, 200)
ellipse(250, 300, 160, 160)
fill(94, 206, 40, 250)
ellipse(250, 400, 160, 160) |
def test_get_condition_new():
scraper = Scraper('Apple', 3000, 'new')
result = scraper.condition_code
assert result == 1000
def test_get_condition_used():
scraper = Scraper('Apple', 3000, 'used')
result = scraper.condition_code
assert result == 3000
def test_get_condition_error():
scraper = Scraper('Apple', 3000, 'something else')
with pytest.raises(KeyError):
scraper.condition_code
def test_get_brand_id_apple():
scraper = Scraper('Apple', 3000, 'used')
result = scraper.brand_id
assert result == 319682
def test_get_brand_id_lg():
scraper = Scraper('LG', 3000, 'used')
result = scraper.brand_id
assert result == 353985
def test_get_brand_id_huawei():
scraper = Scraper('Huawei', 3000, 'used')
result = scraper.brand_id
assert result == 349965
def test_get_brand_id_samsung():
scraper = Scraper('Samsung', 3000, 'used')
result = scraper.brand_id
assert result == 352130
def test_get_brand_id_error():
scraper = Scraper('Something else', 3000, 'new')
with pytest.raises(KeyError):
scraper.brand_id
def test_get_num_of_pages_true():
scraper = Scraper('Apple', 48, 'new')
result = scraper.num_of_pages
assert result == 1
def test_get_num_of_pages_error():
scraper = Scraper('Something else', '3000', 'new')
with pytest.raises(TypeError):
scraper.num_of_pages | def test_get_condition_new():
scraper = scraper('Apple', 3000, 'new')
result = scraper.condition_code
assert result == 1000
def test_get_condition_used():
scraper = scraper('Apple', 3000, 'used')
result = scraper.condition_code
assert result == 3000
def test_get_condition_error():
scraper = scraper('Apple', 3000, 'something else')
with pytest.raises(KeyError):
scraper.condition_code
def test_get_brand_id_apple():
scraper = scraper('Apple', 3000, 'used')
result = scraper.brand_id
assert result == 319682
def test_get_brand_id_lg():
scraper = scraper('LG', 3000, 'used')
result = scraper.brand_id
assert result == 353985
def test_get_brand_id_huawei():
scraper = scraper('Huawei', 3000, 'used')
result = scraper.brand_id
assert result == 349965
def test_get_brand_id_samsung():
scraper = scraper('Samsung', 3000, 'used')
result = scraper.brand_id
assert result == 352130
def test_get_brand_id_error():
scraper = scraper('Something else', 3000, 'new')
with pytest.raises(KeyError):
scraper.brand_id
def test_get_num_of_pages_true():
scraper = scraper('Apple', 48, 'new')
result = scraper.num_of_pages
assert result == 1
def test_get_num_of_pages_error():
scraper = scraper('Something else', '3000', 'new')
with pytest.raises(TypeError):
scraper.num_of_pages |
def get_median( arr ):
size = len(arr)
mid_pos = size // 2
if size % 2 == 0:
# size is even
median = ( arr[mid_pos-1] + arr[mid_pos] ) / 2
else:
# size is odd
median = arr[mid_pos]
return (median)
def collect_Q1_Q2_Q3( arr ):
# Preprocessing
# in-place sorting
arr.sort()
Q2 = get_median( arr )
size = len(arr)
mid = size // 2
if size % 2 == 0:
# size is even
Q1 = get_median( arr[:mid] )
Q3 = get_median( arr[mid:] )
else:
# size is odd
Q1 = get_median( arr[:mid] )
Q3 = get_median( arr[mid+1:] )
return (Q1, Q2, Q3)
def expand_to_flat_list( element_arr, freq_arr ):
flat_list = []
for index in range( len(element_arr) ):
cur_element = element_arr[ index ]
cur_freq = freq_arr[ index ]
# repeat current element with cur_freq times
cur_list = [ cur_element ] * cur_freq
flat_list += cur_list
return flat_list
def get_interquartile_range( arr ):
Q1, Q2, Q3 = collect_Q1_Q2_Q3( arr )
return (Q3-Q1)
if __name__ == '__main__':
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int( input() )
element_arr = list( map(int, input().strip().split() ) )
frequency_arr = list( map(int, input().strip().split() ) )
flat_list = expand_to_flat_list( element_arr, frequency_arr)
inter_quartile_range = get_interquartile_range( flat_list )
print( "%.1f" % inter_quartile_range )
| def get_median(arr):
size = len(arr)
mid_pos = size // 2
if size % 2 == 0:
median = (arr[mid_pos - 1] + arr[mid_pos]) / 2
else:
median = arr[mid_pos]
return median
def collect_q1_q2_q3(arr):
arr.sort()
q2 = get_median(arr)
size = len(arr)
mid = size // 2
if size % 2 == 0:
q1 = get_median(arr[:mid])
q3 = get_median(arr[mid:])
else:
q1 = get_median(arr[:mid])
q3 = get_median(arr[mid + 1:])
return (Q1, Q2, Q3)
def expand_to_flat_list(element_arr, freq_arr):
flat_list = []
for index in range(len(element_arr)):
cur_element = element_arr[index]
cur_freq = freq_arr[index]
cur_list = [cur_element] * cur_freq
flat_list += cur_list
return flat_list
def get_interquartile_range(arr):
(q1, q2, q3) = collect_q1_q2_q3(arr)
return Q3 - Q1
if __name__ == '__main__':
n = int(input())
element_arr = list(map(int, input().strip().split()))
frequency_arr = list(map(int, input().strip().split()))
flat_list = expand_to_flat_list(element_arr, frequency_arr)
inter_quartile_range = get_interquartile_range(flat_list)
print('%.1f' % inter_quartile_range) |
def vowelCount(str):
count = 0
for i in str:
if i == "a" or i == "e" or i == "u" or i == "i" or i == "o":
count += 1
print(count)
exString = "Count the vowels in me!"
vowelCount(exString)
| def vowel_count(str):
count = 0
for i in str:
if i == 'a' or i == 'e' or i == 'u' or (i == 'i') or (i == 'o'):
count += 1
print(count)
ex_string = 'Count the vowels in me!'
vowel_count(exString) |
def test_add_two_params():
expected = 5
actual = add(2, 3)
assert expected == actual
def test_add_three_params():
expected = 9
actual = add(2, 3, 4)
assert expected == actual
def add(a, b, c=None):
if c is None:
return a + b
else:
return a + b + c | def test_add_two_params():
expected = 5
actual = add(2, 3)
assert expected == actual
def test_add_three_params():
expected = 9
actual = add(2, 3, 4)
assert expected == actual
def add(a, b, c=None):
if c is None:
return a + b
else:
return a + b + c |
l = [58, 60, 67, 72, 76, 74, 79]
s = '['
for ll in l:
s += ' %i' % (ll + 9)
s += ' ]'
print(s) | l = [58, 60, 67, 72, 76, 74, 79]
s = '['
for ll in l:
s += ' %i' % (ll + 9)
s += ' ]'
print(s) |
{
"variables": {
"GTK_Root%": "c:\\gtk",
"conditions": [
[ "OS == 'mac'", {
"pkg_env": "PKG_CONFIG_PATH=/opt/X11/lib/pkgconfig"
}, {
"pkg_env": ""
}]
]
},
"targets": [
{
"target_name": "rsvg",
"sources": [
"src/Rsvg.cc",
"src/Enums.cc",
"src/Autocrop.cc"
],
"include_dirs": [
"<!(node -e \"require('nan')\")"
],
"variables": {
"packages": "librsvg-2.0 cairo-png cairo-pdf cairo-svg",
"conditions": [
[ "OS!='win'", {
"libraries": "<!(<(pkg_env) pkg-config --libs-only-l <(packages))",
"ldflags": "<!(<(pkg_env) pkg-config --libs-only-L --libs-only-other <(packages))",
"cflags": "<!(<(pkg_env) pkg-config --cflags <(packages))"
}, { # else OS!='win'
"include_dirs": "<!(<(python) tools/include_dirs.py <(GTK_Root) <(packages))"
} ]
]
},
"conditions": [
[ "OS!='mac' and OS!='win'", {
"cflags": [
"<@(cflags)",
"-std=c++0x"
],
"ldflags": [
"<@(ldflags)"
],
"libraries": [
"<@(libraries)"
],
} ],
[ "OS=='mac'", {
"xcode_settings": {
"OTHER_CFLAGS": [
"<@(cflags)"
],
"OTHER_LDFLAGS": [
"<@(ldflags)"
]
},
"libraries": [
"<@(libraries)"
],
} ],
[ "OS=='win'", {
"sources+": [
"src/win32-math.cc"
],
"include_dirs": [
"<@(include_dirs)"
],
"libraries": [
'librsvg-2.dll.a',
'glib-2.0.lib',
'gobject-2.0.lib',
'cairo.lib'
],
"msvs_settings": {
'VCCLCompilerTool': {
'AdditionalOptions': [
"/EHsc"
]
}
},
"msbuild_settings": {
"Link": {
"AdditionalLibraryDirectories": [
"<(GTK_Root)\\lib"
],
"ImageHasSafeExceptionHandlers": "false"
}
}
} ]
]
}
]
}
| {'variables': {'GTK_Root%': 'c:\\gtk', 'conditions': [["OS == 'mac'", {'pkg_env': 'PKG_CONFIG_PATH=/opt/X11/lib/pkgconfig'}, {'pkg_env': ''}]]}, 'targets': [{'target_name': 'rsvg', 'sources': ['src/Rsvg.cc', 'src/Enums.cc', 'src/Autocrop.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'variables': {'packages': 'librsvg-2.0 cairo-png cairo-pdf cairo-svg', 'conditions': [["OS!='win'", {'libraries': '<!(<(pkg_env) pkg-config --libs-only-l <(packages))', 'ldflags': '<!(<(pkg_env) pkg-config --libs-only-L --libs-only-other <(packages))', 'cflags': '<!(<(pkg_env) pkg-config --cflags <(packages))'}, {'include_dirs': '<!(<(python) tools/include_dirs.py <(GTK_Root) <(packages))'}]]}, 'conditions': [["OS!='mac' and OS!='win'", {'cflags': ['<@(cflags)', '-std=c++0x'], 'ldflags': ['<@(ldflags)'], 'libraries': ['<@(libraries)']}], ["OS=='mac'", {'xcode_settings': {'OTHER_CFLAGS': ['<@(cflags)'], 'OTHER_LDFLAGS': ['<@(ldflags)']}, 'libraries': ['<@(libraries)']}], ["OS=='win'", {'sources+': ['src/win32-math.cc'], 'include_dirs': ['<@(include_dirs)'], 'libraries': ['librsvg-2.dll.a', 'glib-2.0.lib', 'gobject-2.0.lib', 'cairo.lib'], 'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': ['/EHsc']}}, 'msbuild_settings': {'Link': {'AdditionalLibraryDirectories': ['<(GTK_Root)\\lib'], 'ImageHasSafeExceptionHandlers': 'false'}}}]]}]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.