content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
letters = ['o', 's', 'h', 'a', 'd', 'a']
print(letters.index('h'))
print(letters.index('d'))
print(max(letters))
print(min(letters))
print(letters.count('a'))
print(letters.remove('h'))
#after remove r from the list
print(letters)
#reverse the whole list
print(letters.reverse())
print(letters) | letters = ['o', 's', 'h', 'a', 'd', 'a']
print(letters.index('h'))
print(letters.index('d'))
print(max(letters))
print(min(letters))
print(letters.count('a'))
print(letters.remove('h'))
print(letters)
print(letters.reverse())
print(letters) |
def isPalindromeLinkedList(self, head: ListNode) -> bool:
arr = []
while head:
arr.append(head.val)
head = head.next
return arr == arr[::-1] | def is_palindrome_linked_list(self, head: ListNode) -> bool:
arr = []
while head:
arr.append(head.val)
head = head.next
return arr == arr[::-1] |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1020/A
def f(l):
dist = lambda a,b:a-b if a>b else b-a
global a,b
ta,fa,tb,fb = l
ht = dist(ta,tb)
if (fa>=a and fa<=b) or (fb>=a and fb<=b) or ht==0:
return ht + dist(fa,fb)
return ht + min(dist(fa,a)+dist(fb,a),dist(f... | def f(l):
dist = lambda a, b: a - b if a > b else b - a
global a, b
(ta, fa, tb, fb) = l
ht = dist(ta, tb)
if fa >= a and fa <= b or (fb >= a and fb <= b) or ht == 0:
return ht + dist(fa, fb)
return ht + min(dist(fa, a) + dist(fb, a), dist(fa, b) + dist(fb, b))
(n, h, a, b, k) = list(map... |
#!/usr/bin/env python
data = [
[
7,
[
3.50016331673, 7.37909364700, 8.02381229401, 8.01285839081,
9.77704334259, 9.15692901611, 8.73682498932, 7.93067312241
],
],
[
4.202,
[
2.06499981880, 2.08285713196, 2.18571448326, 2.1921432018... | data = [[7, [3.50016331673, 7.379093647, 8.02381229401, 8.01285839081, 9.77704334259, 9.15692901611, 8.73682498932, 7.93067312241]], [4.202, [2.0649998188, 2.08285713196, 2.18571448326, 2.19214320183, 2.19214320183, 2.19357180595, 2.19500041008, 2.19714307785]], [9.8592, [3.56500029564, 3.61142873764, 3.63214302063, 3.... |
def solution(string, markers):
output = []
for line in string.split("\n"):
containsCommentIndicator = ""
for c in line:
if c in markers:
containsCommentIndicator = c
break
if containsCommentIndicator != "":
line = line[:line.find(containsCommentIndicator)]
line = line.rstrip(" ")
output.appe... | def solution(string, markers):
output = []
for line in string.split('\n'):
contains_comment_indicator = ''
for c in line:
if c in markers:
contains_comment_indicator = c
break
if containsCommentIndicator != '':
line = line[:line.fin... |
__title__ = 'fipeapi'
__description__ = 'Python Extra Oficial API for REST Request to consult Vehicles Prices.'
__url__ = 'https://github.com/deibsoncarvalho/tabela-fipe-api'
__version__ = '0.1.0'
__author__ = 'Deibson Carvalho'
__author_email__ = 'eu@deibsoncarvalho.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Cop... | __title__ = 'fipeapi'
__description__ = 'Python Extra Oficial API for REST Request to consult Vehicles Prices.'
__url__ = 'https://github.com/deibsoncarvalho/tabela-fipe-api'
__version__ = '0.1.0'
__author__ = 'Deibson Carvalho'
__author_email__ = 'eu@deibsoncarvalho.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Cop... |
def _update_Spr(Gp, Gr, Rpr, Spr_shape, I, B, t):
# F Reconstruction
F = np.zeros(Spr_shape)
F += np.linalg.multi_dot((Gp.T, Rpr[0], Gr))
Gk = Gp * I[:, t][:, np.newaxis]
Ik = np.reshape(I[:, t], (len(I[:, t]), 1))
bk = np.reshape(B[t, :], (1, len(B[t, :])))
F += 2*np.linalg.multi_dot((Gk.T,... | def _update__spr(Gp, Gr, Rpr, Spr_shape, I, B, t):
f = np.zeros(Spr_shape)
f += np.linalg.multi_dot((Gp.T, Rpr[0], Gr))
gk = Gp * I[:, t][:, np.newaxis]
ik = np.reshape(I[:, t], (len(I[:, t]), 1))
bk = np.reshape(B[t, :], (1, len(B[t, :])))
f += 2 * np.linalg.multi_dot((Gk.T, Ik, bk))
a = Gp... |
with open("vocab_origin.txt", "r") as f:
lines = f.readlines()
for i in range(185):
lines.append("<s_{}>".format(i))
with open("vocab.txt", "w") as f:
for line in lines:
f.write(line.strip() + "\n")
| with open('vocab_origin.txt', 'r') as f:
lines = f.readlines()
for i in range(185):
lines.append('<s_{}>'.format(i))
with open('vocab.txt', 'w') as f:
for line in lines:
f.write(line.strip() + '\n') |
# Go to http://apps.twitter.com and create an app.
# The consumer key and secret will be generated for you
API_KEY = ""
API_SECRET_KEY = ""
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""
| api_key = ''
api_secret_key = ''
access_token = ''
access_token_secret = '' |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
UNTRIAGED = 0
TRIAGED_INCORRECT = 1
TRIAGED_CORRECT = 2
TRIAGED_UNSURE = 3
TRIAGE_STATUS_TO_DESCRIPTION = {
UNTRIAGED: 'Untriaged',
TRIAGED_INCORRE... | untriaged = 0
triaged_incorrect = 1
triaged_correct = 2
triaged_unsure = 3
triage_status_to_description = {UNTRIAGED: 'Untriaged', TRIAGED_INCORRECT: 'Incorrect', TRIAGED_CORRECT: 'Correct', TRIAGED_UNSURE: 'Unsure'} |
#!/usr/bin/env python
Nmp = 345
nbound = [0]*1037
step = 0
for l in open('test'):
step += 1
for i in range(Nmp):
if int(l[i]) > 0:
nbound[i] += 1
for i in range(Nmp):
print ('%i %i %f' % (i+1, nbound[i], nbound[i] / float(step)))
| nmp = 345
nbound = [0] * 1037
step = 0
for l in open('test'):
step += 1
for i in range(Nmp):
if int(l[i]) > 0:
nbound[i] += 1
for i in range(Nmp):
print('%i %i %f' % (i + 1, nbound[i], nbound[i] / float(step))) |
def file_upload(f):
with open('static/upload/'+f.name,'wb+') as destination:
for i in f.chunks():
destination.write(i)
| def file_upload(f):
with open('static/upload/' + f.name, 'wb+') as destination:
for i in f.chunks():
destination.write(i) |
def calculate_s(data_counts, qubit_indices, pauli_bases):
number_of_data_points = 0
s = 0
#print("qubit_indices", qubit_indices)
#print("pauli_bases", pauli_bases)
#print("data_counts", data_counts.items())
# loop through indices and read measurments
for key, value in data_counts.i... | def calculate_s(data_counts, qubit_indices, pauli_bases):
number_of_data_points = 0
s = 0
for (key, value) in data_counts.items():
number_of_data_points += value
number_of_1s = 0
for i in range(len(qubit_indices)):
if key[qubit_indices[i]] == '1':
if pauli... |
lisi = 1
lisi1 = 1
lisi2 = 2
zhangsan3 = 3
lisi3 = 3
dev = 1
| lisi = 1
lisi1 = 1
lisi2 = 2
zhangsan3 = 3
lisi3 = 3
dev = 1 |
decimal = int(input("Decimal: "))
binary = ""
while decimal != 0:
rest = decimal % 2
binary = str(rest) + binary
decimal = decimal // 2
print ("Binary: %s" % binary) | decimal = int(input('Decimal: '))
binary = ''
while decimal != 0:
rest = decimal % 2
binary = str(rest) + binary
decimal = decimal // 2
print('Binary: %s' % binary) |
def swap_in_place(arr, idx1, idx2):
new_arr = arr[:]
if idx1 > len(arr) - 1 or idx2 > len(arr) - 1:
return arr
new_arr.insert(idx1, new_arr.pop(idx2))
#print(new_arr)
new_arr.insert(idx2, new_arr.pop(idx1 + 1))
return new_arr
def test_case(arr, idx1, idx2, solution, test_func):
out... | def swap_in_place(arr, idx1, idx2):
new_arr = arr[:]
if idx1 > len(arr) - 1 or idx2 > len(arr) - 1:
return arr
new_arr.insert(idx1, new_arr.pop(idx2))
new_arr.insert(idx2, new_arr.pop(idx1 + 1))
return new_arr
def test_case(arr, idx1, idx2, solution, test_func):
output = test_func(arr, ... |
# you can use print for debugging purposes, e.g.
# print "this is a debug message"
# The strategy is to iterate through the string, putting each character onto
# a specific stack, depending on its type.
# A, When we put the character onto the stack, we check to see if the one before it
# is an opposite - eg. { then }... | def solution(S):
annihilate = {')': '(', ']': '[', '}': '{'}
stack = []
if not S:
return 1
for char in S:
if char in annihilate.keys() and len(stack) > 0:
if stack[-1] == annihilate[char]:
stack.pop()
else:
stack.append(char)
... |
class Pattern_Twenty_Three:
'''Pattern twenty_three
ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo
oooo
oooo
oooo
ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo
oooo
oooo
... | class Pattern_Twenty_Three:
"""Pattern twenty_three
ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo
oooo
oooo
oooo
ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo
oooo
oooo
... |
expected_output = {
'chassis_feature': 'V2 AC PEM',
'clei': 'IPMUP00BRB',
'desc': 'ASR 9006 4 Line Card Slot Chassis with V2 AC PEM',
'device_family': 'ASR',
'device_series': '9006',
'num_line_cards': 4,
'pid': 'ASR-9006-AC-V2',
'rack_num': 0,
'sn': 'FOX1810G8LR',
'top_assy_num... | expected_output = {'chassis_feature': 'V2 AC PEM', 'clei': 'IPMUP00BRB', 'desc': 'ASR 9006 4 Line Card Slot Chassis with V2 AC PEM', 'device_family': 'ASR', 'device_series': '9006', 'num_line_cards': 4, 'pid': 'ASR-9006-AC-V2', 'rack_num': 0, 'sn': 'FOX1810G8LR', 'top_assy_num': '68-4235-02', 'vid': 'V02'} |
ALL_NODES_TYPE = '<all>'
ALL_PRIMITIVES_TYPES = '<all-primitives>'
ALL_REGION_TYPES = '<all-regions>'
ALL_CONDITIONS_TYPES = '<all-conditions>'
LOCATION_OR_WAYPOINT = '<location-or-waypoint>'
STRING_TYPE = '<string>'
NUMBER_TYPE = '<number>'
BOOLEAN_TYPE = '<boolean>'
ENUM_TYPE = '<enum>'
ARBITRARY_OBJ_TYPE = '<arbit... | all_nodes_type = '<all>'
all_primitives_types = '<all-primitives>'
all_region_types = '<all-regions>'
all_conditions_types = '<all-conditions>'
location_or_waypoint = '<location-or-waypoint>'
string_type = '<string>'
number_type = '<number>'
boolean_type = '<boolean>'
enum_type = '<enum>'
arbitrary_obj_type = '<arbitra... |
# 2021-02-08
# Emma Benjaminson
# Implementation of Linked List
# for ch2-p1 (at least)
# need init, delete methods (possibly traverse?)
# singly linked list for now
# class Node
# this will contain init method
# attribute is next which is pointer to the next node
class Node:
def __init__(self, data):
s... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class Linkedlist:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = node(data=nodes.pop(0))
self.head =... |
#To find first index of an element in an array.
def firstIndex(arr, si, x):
l = len(arr) #length of array.
if l == 0: #base case
return -1
if arr[si] == x: #if element is found at start index of an array then return that index.
return si
return firstIndex(arr, si+1, x) #recursive call... | def first_index(arr, si, x):
l = len(arr)
if l == 0:
return -1
if arr[si] == x:
return si
return first_index(arr, si + 1, x)
arr = []
n = int(input('Enter size of array : '))
for i in range(n):
ele = int(input())
arr.append(ele)
x = int(input('Enter element to be searched '))
pri... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2020 Akumatic
#
#https://adventofcode.com/2020/day/12
def readFile() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [line.strip() for line in f.readlines()]
def part1(input: list) -> int:
x, y = 0, 0
dirs = ((1,0), (0, ... | def read_file() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", 'r') as f:
return [line.strip() for line in f.readlines()]
def part1(input: list) -> int:
(x, y) = (0, 0)
dirs = ((1, 0), (0, 1), (-1, 0), (0, -1))
idx = 0
for instruction in input:
action = instruction[0]
... |
print("Please inser the following")
print()
adjective = input("adjetive: ")
animal = input("animal: ")
verb1 = input("verb: ")
exclamation = input("exclamation: ")
verb2 = input ("verb: ")
verb3 = input("verb: ")
print()
print()
print("Your story is: ")
print()
print(f"The other day, I was really in trouble. It all sta... | print('Please inser the following')
print()
adjective = input('adjetive: ')
animal = input('animal: ')
verb1 = input('verb: ')
exclamation = input('exclamation: ')
verb2 = input('verb: ')
verb3 = input('verb: ')
print()
print()
print('Your story is: ')
print()
print(f"The other day, I was really in trouble. It all star... |
# JS console is having a very hard time running my logic,
# so I rewrote it in Python to ensure I was on the right track.
# Still trying to get JS to run the one-linerized code.
def run(input, turns):
input = input.split(',')
last = {int(n): i + 1 for (i, n) in enumerate(input)}
spoken = int(input[-1])
... | def run(input, turns):
input = input.split(',')
last = {int(n): i + 1 for (i, n) in enumerate(input)}
spoken = int(input[-1])
for turn in xrange(len(input), turns):
new_spoken = turn - last[spoken] if spoken in last else 0
last[spoken] = turn
spoken = new_spoken
return spoken... |
#
# PySNMP MIB module DMTF-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DMTF-MONITOR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:36:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
people = int(input())
lift = [int(i) for i in input().split()]
available_space = 0
for index,cabin in enumerate(lift):
available_space = 4 - int(cabin)
if people < 4:
lift[index] += people
people -= available_space
break
lift[index] += available_space
people -= available_space... | people = int(input())
lift = [int(i) for i in input().split()]
available_space = 0
for (index, cabin) in enumerate(lift):
available_space = 4 - int(cabin)
if people < 4:
lift[index] += people
people -= available_space
break
lift[index] += available_space
people -= available_space... |
global_default = {
'general_poll_interval': 3
}
incoming_default = {
'require_arrival_monitor': False,
'control_file_extension': 'stager-ctrl-bss',
'receipt_file_extension': 'stager-rcpt-bss',
'thankyou_file_extension': 'stager-thanks-bss',
'stop_file': '.stop'
}
outgoing_default = {
'target_uses_arrival_monitor': F... | global_default = {'general_poll_interval': 3}
incoming_default = {'require_arrival_monitor': False, 'control_file_extension': 'stager-ctrl-bss', 'receipt_file_extension': 'stager-rcpt-bss', 'thankyou_file_extension': 'stager-thanks-bss', 'stop_file': '.stop'}
outgoing_default = {'target_uses_arrival_monitor': False, 'c... |
class WebOperationCollection:
def __init__(self):
self.id = None
self.opt_type = None
self.opt_name = None
self.opt_trans = None
self.opt_element = None
self.opt_data = None
self.opt_code = None
@staticmethod
def __parse(ui_data: dict, name):
... | class Weboperationcollection:
def __init__(self):
self.id = None
self.opt_type = None
self.opt_name = None
self.opt_trans = None
self.opt_element = None
self.opt_data = None
self.opt_code = None
@staticmethod
def __parse(ui_data: dict, name):
... |
#Write a function that computes cosine or sine by taking the first n terms of the appropriate series expansion
#To evaluate the value of sin and cos, we can make use of MacLaurin's Theorem
#f(x) = f(0) + f'(0)x+ f''(0)/2! x^2 + f'''0/3! x^3 ...
def cos(n):
result = 0.0
for i in range(31): #Performs series fo... | def cos(n):
result = 0.0
for i in range(31):
dividend = (-1) ** i * n ** (2 * i)
divisor = fact(2 * i)
result += dividend / divisor
return result
def sin(n):
result = 0.0
for i in range(31):
dividend = (-1) ** i * n ** (2 * i + 1)
divisor = fact(2 * i + 1)
... |
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
diff = -1
minValue = nums[0]+1
for i in range(len(nums)):
if nums[i] > minValue:
diff = max(diff, nums[i]- minValue)
minValue = min(minValue, nums[i]) #... | class Solution:
def maximum_difference(self, nums: List[int]) -> int:
diff = -1
min_value = nums[0] + 1
for i in range(len(nums)):
if nums[i] > minValue:
diff = max(diff, nums[i] - minValue)
min_value = min(minValue, nums[i])
return diff |
filename='pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string +=line.strip()
print(pi_string)
print(len(pi_string)) | filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string)) |
#Collections, Lists and Tubles - colecao de dados
familia = ["Hugo", "Louyse", "Julieta"] #listas podem ser feitas com qualquer tipo de dado, bool, int, float, string
print(familia[0]) #primeiro dado
print(familia[-1]) #ultimo dado
print(familia[0:2]) #intervalo de dado, sem exclui o ultimo dado do vetor, neste caso ... | familia = ['Hugo', 'Louyse', 'Julieta']
print(familia[0])
print(familia[-1])
print(familia[0:2])
print(familia[1])
print(familia)
familia[2] = 'Juju '
print(familia)
familia.extend(['Seraaaaaa?', 'Na mao de Deus'])
print(familia)
familia.insert(1, 'Spock')
print(familia)
familia.pop()
print(familia)
familia.remove('Spo... |
#
# Unicode Mapping generated by uni2python.xsl
#
unicode_map = {
0x00100: r"\={A}", # LATIN CAPITAL LETTER A WITH MACRON
0x00101: r"\={a}", # LATIN SMALL LETTER A WITH MACRON
0x00102: r"\u{A}", # LATIN CAPITAL LETTER A WITH BREVE
0x00103: r"\u{a}", # LATIN SMALL LETTER A WITH BREVE
0x00104: r"\k{A}", # LATIN CAPITAL L... | unicode_map = {256: '\\={A}', 257: '\\={a}', 258: '\\u{A}', 259: '\\u{a}', 260: '\\k{A}', 261: '\\k{a}', 262: "\\'{C}", 263: "\\'{c}", 264: '\\^{C}', 265: '\\^{c}', 266: '\\.{C}', 267: '\\.{c}', 268: '\\v{C}', 269: '\\v{c}', 270: '\\v{D}', 271: '\\v{d}', 272: '\\DJ{}', 273: '\\dj{}', 274: '\\={E}', 275: '\\={e}', 276: ... |
def main():
info('Jan unknown laser analysis')
#gosub('jan:PrepareForCO2Analysis')
if exp.analysis_type == 'blank':
info('is blank. not heating')
else:
info('move to position {}'.format(exp.position))
move_to_position(exp.position)
if exp.ramp_rate > 0:
'''... | def main():
info('Jan unknown laser analysis')
if exp.analysis_type == 'blank':
info('is blank. not heating')
else:
info('move to position {}'.format(exp.position))
move_to_position(exp.position)
if exp.ramp_rate > 0:
'\n style 1.\n '
... |
c = float(input('Digite a temperatura em Celsius: '))
f = (c * 1.8) + 32
print(f'A temperatura de {c} Grau Celsius em fahrenheit equivale a {f}F')
| c = float(input('Digite a temperatura em Celsius: '))
f = c * 1.8 + 32
print(f'A temperatura de {c} Grau Celsius em fahrenheit equivale a {f}F') |
# Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
class MCInvalidValue(object):
def __init__(self, name):
self.name = name
def __nonzero__(self):
return False
def __repr__(self):
return self.name
... | class Mcinvalidvalue(object):
def __init__(self, name):
self.name = name
def __nonzero__(self):
return False
def __repr__(self):
return self.name
def json_equivalent(self):
return self.__repr__()
mc_required = mc_invalid_value('MC_REQUIRED')
mc_todo = mc_invalid_value... |
# Longest Substring Without Repeating Characters
class Solution:
def lengthOfLongestSubstring(self, s):
longest = 0
start = 0
length = len(s)
while start < length - longest:
substr = s[start:start + longest + 1]
if len(set(substr)) == longest + 1:
... | class Solution:
def length_of_longest_substring(self, s):
longest = 0
start = 0
length = len(s)
while start < length - longest:
substr = s[start:start + longest + 1]
if len(set(substr)) == longest + 1:
longest += 1
else:
... |
workers = 2
errorlog = "/demo/mysite.gunicorn.error"
accesslog = "/demo/mysite.gunicorn.access"
loglevel = "debug"
| workers = 2
errorlog = '/demo/mysite.gunicorn.error'
accesslog = '/demo/mysite.gunicorn.access'
loglevel = 'debug' |
# https://www.codechef.com/problems/LOSTMAX
for T in range(int(input())):
l=list(map(int,input().split()))
l.remove(len(l)-1)
print(max(l)) | for t in range(int(input())):
l = list(map(int, input().split()))
l.remove(len(l) - 1)
print(max(l)) |
BOARD_SIZE = 8
class Queen(object):
def __init__(self, x, y):
if (
x < 0 or x >= BOARD_SIZE or
y < 0 or y >= BOARD_SIZE
):
raise ValueError('invalid board position')
self.p = (x, y)
def __eq__(self, other):
return self.p == othe... | board_size = 8
class Queen(object):
def __init__(self, x, y):
if x < 0 or x >= BOARD_SIZE or y < 0 or (y >= BOARD_SIZE):
raise value_error('invalid board position')
self.p = (x, y)
def __eq__(self, other):
return self.p == other.p
def can_attack(self, other):
... |
class Solution:
# @param A : tuple of integers
# @return a list of integers
def repeatedNumber(self, A):
n = len(A)
f_sum = sum(A) #false sum
actual_sum = 0
actual_sum_squares = 0
f_sum_square = 0 #false sum squares
for i in range(1,n+1):
actual_su... | class Solution:
def repeated_number(self, A):
n = len(A)
f_sum = sum(A)
actual_sum = 0
actual_sum_squares = 0
f_sum_square = 0
for i in range(1, n + 1):
actual_sum += i
actual_sum_squares += i * i
f_sum_square += A[i - 1] * A[i - 1... |
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
cnt, pre = 0, 0
length = len(flowerbed)
flowers = flowerbed + [0]
for idx, _ in enumerate(flowerbed):
next_ = flowers[idx]
if not _:
print(cnt, idx, pre, flowers[i... | class Solution:
def can_place_flowers(self, flowerbed: List[int], n: int) -> bool:
(cnt, pre) = (0, 0)
length = len(flowerbed)
flowers = flowerbed + [0]
for (idx, _) in enumerate(flowerbed):
next_ = flowers[idx]
if not _:
print(cnt, idx, pre, ... |
start = int(input())
end = int(input())
def is_divide(number):
return any(number % i == 0 for i in range(2, 11))
def get_divise_numbers(start, end):
return [s for s in range(start, end + 1) if is_divide(s)]
def print_result(numbers):
print(numbers)
numbers = get_divise_numbers(start, end)
print_resu... | start = int(input())
end = int(input())
def is_divide(number):
return any((number % i == 0 for i in range(2, 11)))
def get_divise_numbers(start, end):
return [s for s in range(start, end + 1) if is_divide(s)]
def print_result(numbers):
print(numbers)
numbers = get_divise_numbers(start, end)
print_result(... |
token = "1047594455:AAGGblu9FGRNgPkjMEcbX7I5BuwDHUBQqsI"
MODULE_NAME = "admin"
MESSAGE_AMOUNT = "People registered: "
MESSAGE_UNAUTHORIZED = "Unauthorized access attempt. Administrator was notified"
MESSAGE_SENT_EVERYBODY = "Message has been sent to everybody"
MESSAGE_SENT_PERSONAL = "Message has been sent"
MESSAGE_AB... | token = '1047594455:AAGGblu9FGRNgPkjMEcbX7I5BuwDHUBQqsI'
module_name = 'admin'
message_amount = 'People registered: '
message_unauthorized = 'Unauthorized access attempt. Administrator was notified'
message_sent_everybody = 'Message has been sent to everybody'
message_sent_personal = 'Message has been sent'
message_abo... |
class KikErrorException(Exception):
def __init__(self, xml_error, message=None):
self.message = message
self.xml_error = xml_error
def __str__(self):
return self.__repr__()
def __repr__(self):
if self.message is not None:
return self.message
else:
... | class Kikerrorexception(Exception):
def __init__(self, xml_error, message=None):
self.message = message
self.xml_error = xml_error
def __str__(self):
return self.__repr__()
def __repr__(self):
if self.message is not None:
return self.message
else:
... |
def anonymous_allowed(fn):
fn.authenticated = False
return fn
def authentication_required(fn):
fn.authenticated = True
return fn
| def anonymous_allowed(fn):
fn.authenticated = False
return fn
def authentication_required(fn):
fn.authenticated = True
return fn |
class ansi: pass
ansi.red = '\x1b[41m'
ansi.orange = '\x1b[48;5;130m'
ansi.green = '\x1b[42m'
ansi.yellow = '\x1b[43m'
ansi.blue = '\x1b[44m'
ansi.magenta = '\x1b[45m'
ansi.cyan = '\x1b[46m'
ansi.white = '\x1b[47m'
ansi.reset = '\x1b[49m'
fill = {
'O': ansi.orange+' '+ansi.reset,
'G': ansi.green+' '+ansi.reset... | class Ansi:
pass
ansi.red = '\x1b[41m'
ansi.orange = '\x1b[48;5;130m'
ansi.green = '\x1b[42m'
ansi.yellow = '\x1b[43m'
ansi.blue = '\x1b[44m'
ansi.magenta = '\x1b[45m'
ansi.cyan = '\x1b[46m'
ansi.white = '\x1b[47m'
ansi.reset = '\x1b[49m'
fill = {'O': ansi.orange + ' ' + ansi.reset, 'G': ansi.green + ' ' + ansi.res... |
class MNIST_v4(torch.nn.Module):
training_losses = [] #for plotting purposes
validation_losses = [] #for plotting purposes
training_accuracy = [] #for plotting purposes
validation_accuracy = [] #for plotting purposes
criterion = None #for criterion check
optim ... | class Mnist_V4(torch.nn.Module):
training_losses = []
validation_losses = []
training_accuracy = []
validation_accuracy = []
criterion = None
optim = None
nonlinear = False
def __init__(self, in_features, out_features, layers=None, optim=None, criterion=None, dropout=0.2):
super... |
input()
l = [*map(int, input().split())]
l.sort()
print(max(l[0]*l[1], l[0]*l[1]*l[-1], l[-1]*l[-2]*l[-3], l[-1]*l[-2]))
| input()
l = [*map(int, input().split())]
l.sort()
print(max(l[0] * l[1], l[0] * l[1] * l[-1], l[-1] * l[-2] * l[-3], l[-1] * l[-2])) |
'''
MIT License
Copyright (c) 2020 Jimeno Fonseca
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... | """
MIT License
Copyright (c) 2020 Jimeno Fonseca
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... |
pkgname = "python-pyyaml"
pkgver = "6.0"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools", "python-cython"]
makedepends = ["libyaml-devel", "python-devel"]
pkgdesc = "YAML parser and emitter for Python"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "http://pyyaml.org/wi... | pkgname = 'python-pyyaml'
pkgver = '6.0'
pkgrel = 0
build_style = 'python_module'
hostmakedepends = ['python-setuptools', 'python-cython']
makedepends = ['libyaml-devel', 'python-devel']
pkgdesc = 'YAML parser and emitter for Python'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'MIT'
url = 'http://pyyaml.org/wi... |
# -*- coding: utf-8 -*-
class Root(object):
def __init__(self, request):
self.request = request
| class Root(object):
def __init__(self, request):
self.request = request |
# https://codeforces.com/problemset/problem/510/A
n, m = [int(x) for x in input().split()]
counter = 0
for row in range(1, n + 1):
if row % 2 == 1:
print(m * '#')
else:
counter += 1
if counter % 2 == 1:
print((m - 1) * '.' + '#')
else:
print('#' + (m - ... | (n, m) = [int(x) for x in input().split()]
counter = 0
for row in range(1, n + 1):
if row % 2 == 1:
print(m * '#')
else:
counter += 1
if counter % 2 == 1:
print((m - 1) * '.' + '#')
else:
print('#' + (m - 1) * '.') |
roll = [1, 2, 3]
names = ['Ayush', 'Joe', 'Rob']
pair = zip(roll, names)
print(dict(pair))
bob2 = dict(zip(['names', 'job', 'age'], ['Bob', 'dev', 40]))
print(bob2)
# Nested dictionaties
record = {
'emp1' :
{ 'name' : {'first' : 'Ayush', 'last' : 'Dutta' },
'job' : 'Software Dev',
'age' : 17... | roll = [1, 2, 3]
names = ['Ayush', 'Joe', 'Rob']
pair = zip(roll, names)
print(dict(pair))
bob2 = dict(zip(['names', 'job', 'age'], ['Bob', 'dev', 40]))
print(bob2)
record = {'emp1': {'name': {'first': 'Ayush', 'last': 'Dutta'}, 'job': 'Software Dev', 'age': 17}}
dict1 = record['emp1']['name']
print(dict1)
full_name = ... |
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Code the for loop
for areas in areas :
print(areas)
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Change for loop to use enumerate() and update print()
for index, area in enumerate(areas) :
print("room " + str(index) + ": " + str... | areas = [11.25, 18.0, 20.0, 10.75, 9.5]
for areas in areas:
print(areas)
areas = [11.25, 18.0, 20.0, 10.75, 9.5]
for (index, area) in enumerate(areas):
print('room ' + str(index) + ': ' + str(area))
areas = [11.25, 18.0, 20.0, 10.75, 9.5]
for (index, area) in enumerate(areas):
print('room ' + str(index + 1)... |
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
... | class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, newdata):
self.data = newdata
def set_next(self, newnext):
self.next = new... |
# Arithmetic
# +, -, *, /, %, all work with numbers and variables holding numbers
# +=, -=, *=, /=, i.e x += 1 is the same as x = x + 1
x = 1 + 1 # assign 1 + 1 to x
y = 0
y += x # add x to y
| x = 1 + 1
y = 0
y += x |
def best_stock(data):
max = 0 # max price
best = '' # best stock
for s in data:
if data[s] > max:
max = data[s]
best = s
return best
if __name__ == '__main__':
print("Example:")
print(best_stock({
'CAC': 10.0,
'ATX': 390.2,
... | def best_stock(data):
max = 0
best = ''
for s in data:
if data[s] > max:
max = data[s]
best = s
return best
if __name__ == '__main__':
print('Example:')
print(best_stock({'CAC': 10.0, 'ATX': 390.2, 'WIG': 1.2}))
assert best_stock({'CAC': 10.0, 'ATX': 390.2, 'W... |
# https://leetcode.com/problems/sort-characters-by-frequency/
class Solution:
def frequencySort(self, s: str) -> str:
char_frequencies = dict()
for char in s:
char_frequencies[char] = char_frequencies.get(char, 0) + 1
char_frequencies = list(char_frequencies.items())
cha... | class Solution:
def frequency_sort(self, s: str) -> str:
char_frequencies = dict()
for char in s:
char_frequencies[char] = char_frequencies.get(char, 0) + 1
char_frequencies = list(char_frequencies.items())
char_frequencies.sort(reverse=True, key=lambda x: x[1])
... |
def solution(nums):
n = len(nums)
dp = [1]*n
for i in range(n):
if i == 0:
dp[0] = nums[0]
else:
dp[i] = max(dp[i-1]*nums[i], nums[i])
return max(dp)
def main():
n = int(input())
nums = []
for _ in range(n):
nums.append(float(input()))
nu... | def solution(nums):
n = len(nums)
dp = [1] * n
for i in range(n):
if i == 0:
dp[0] = nums[0]
else:
dp[i] = max(dp[i - 1] * nums[i], nums[i])
return max(dp)
def main():
n = int(input())
nums = []
for _ in range(n):
nums.append(float(input()))
... |
#
# PySNMP MIB module Q-IN-Q-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Q-IN-Q-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:43:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
def handler(connection, event):
if event.arguments and event.arguments[0].startswith("!r"):
connection.privmsg(event.target, "\x02\x034 Rule one: \x035 No Banninating!")
connection.privmsg(event.target, "\x02\x034 Rule two: \x035 See rule one")
connection.privmsg(
event.targe... | def handler(connection, event):
if event.arguments and event.arguments[0].startswith('!r'):
connection.privmsg(event.target, '\x02\x034 Rule one: \x035 No Banninating!')
connection.privmsg(event.target, '\x02\x034 Rule two: \x035 See rule one')
connection.privmsg(event.target, "\x02\x034... |
previous_scores = [0] * 301
def solve(num_stairs, points):
if num_stairs < 3:
print(previous_scores[num_stairs])
return
else:
return points[num_stairs - 1] + solve(num_stairs - 1)
if __name__ == '__main__':
num_stairs = int(input())
points = [int(input()) for _ in range(num_s... | previous_scores = [0] * 301
def solve(num_stairs, points):
if num_stairs < 3:
print(previous_scores[num_stairs])
return
else:
return points[num_stairs - 1] + solve(num_stairs - 1)
if __name__ == '__main__':
num_stairs = int(input())
points = [int(input()) for _ in range(num_stai... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 21_multi_attributes.ipynb (unless otherwise specified).
__all__ = ['are_recurrent', 'get_summary_statistic', 'get_routine_scores', 'get_synchrony', 'get_sequence_frequencies']
# Cell
def are_recurrent(sequences):
"Returns true if any of the sequences in a given collecti... | __all__ = ['are_recurrent', 'get_summary_statistic', 'get_routine_scores', 'get_synchrony', 'get_sequence_frequencies']
def are_recurrent(sequences):
"""Returns true if any of the sequences in a given collection are recurrant, false otherwise."""
for sequence in sequences:
if pysan_core.is_recurrent(se... |
class Speed:
def __init__(self):
self._cache = {}
def get_value(self, entity):
value = 0
if entity in self._cache:
value = self._cache[entity]
return value
def update(self, entity, value):
self._cache[entity] = value
# speed.py
| class Speed:
def __init__(self):
self._cache = {}
def get_value(self, entity):
value = 0
if entity in self._cache:
value = self._cache[entity]
return value
def update(self, entity, value):
self._cache[entity] = value |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# Recursion ([left, mid, right])
'''
if root is None:
... | class Solution:
def inorder_traversal(self, root: TreeNode) -> List[int]:
"""
if root is None:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
"""
if root is None:
return []
result = []
... |
def main():
for x in range(4):
if x == 5:
break
else:
print("Well of course that didn't happen")
for x in range(7):
if x == 5:
break
else:
print("H-hey wait!")
if __name__ == '__main__':
main()
| def main():
for x in range(4):
if x == 5:
break
else:
print("Well of course that didn't happen")
for x in range(7):
if x == 5:
break
else:
print('H-hey wait!')
if __name__ == '__main__':
main() |
# Section 5.3 snippets
# Creating Tuples
student_tuple = ()
student_tuple
len(student_tuple)
student_tuple = 'John', 'Green', 3.3
student_tuple
len(student_tuple)
another_student_tuple = ('Mary', 'Red', 3.3)
another_student_tuple
a_singleton_tuple = ('red',) # note the comma
a_singleton_tuple
# Accessing Tu... | student_tuple = ()
student_tuple
len(student_tuple)
student_tuple = ('John', 'Green', 3.3)
student_tuple
len(student_tuple)
another_student_tuple = ('Mary', 'Red', 3.3)
another_student_tuple
a_singleton_tuple = ('red',)
a_singleton_tuple
time_tuple = (9, 16, 1)
time_tuple
time_tuple[0] * 3600 + time_tuple[1] * 60 + tim... |
# Plugin author
__author__ = 'John Maguire'
# Plugin homepage
__url__ = 'https://github.com/JohnMaguire2013/Cardinal/'
| __author__ = 'John Maguire'
__url__ = 'https://github.com/JohnMaguire2013/Cardinal/' |
x = False
y = True
# a. Write an expression that produces True iff both variables are True.
print((x and not y) or (y and not x))
# b. Write an expression that produces True iff x is False.
print(not x)
# c. Write an expression that produces True iff at least one of the variables is True.
print(x or y) | x = False
y = True
print(x and (not y) or (y and (not x)))
print(not x)
print(x or y) |
n,m,a,x,r = [int(i) for i in input().split()]
s = input()
for i in range(m):
t = input()
for i in range(a):
p = input()
if(n<10**6 and r<=x):
print(1)
print(3,1,10**6-n)
else:
print(0)
| (n, m, a, x, r) = [int(i) for i in input().split()]
s = input()
for i in range(m):
t = input()
for i in range(a):
p = input()
if n < 10 ** 6 and r <= x:
print(1)
print(3, 1, 10 ** 6 - n)
else:
print(0) |
def get_pk_type(schema, pk_field) -> type:
try:
return schema.__fields__[pk_field].type_
except KeyError:
return int
| def get_pk_type(schema, pk_field) -> type:
try:
return schema.__fields__[pk_field].type_
except KeyError:
return int |
load("@bazel_skylib//lib:paths.bzl", "paths")
load("//:def.bzl", "project")
def _start_drone_runner_impl(ctx):
template_name = paths.basename(ctx.file._script_template.short_path)
script = ctx.actions.declare_file("rendered_{}".format(template_name))
ctx.actions.expand_template(
template = ctx.fil... | load('@bazel_skylib//lib:paths.bzl', 'paths')
load('//:def.bzl', 'project')
def _start_drone_runner_impl(ctx):
template_name = paths.basename(ctx.file._script_template.short_path)
script = ctx.actions.declare_file('rendered_{}'.format(template_name))
ctx.actions.expand_template(template=ctx.file._script_te... |
table = {'1985': 'Test movie' , '1983': 'Test Movie2' , '2000': 'Test Movie 3'}
year = '1983'
movie = table[year]
print(movie)
for year in table:
print(year + '\t' + movie + '\t') | table = {'1985': 'Test movie', '1983': 'Test Movie2', '2000': 'Test Movie 3'}
year = '1983'
movie = table[year]
print(movie)
for year in table:
print(year + '\t' + movie + '\t') |
class Router:
def __init__(
self,
databricks_url: str,
routes: dict,
):
self.__databricks_url = databricks_url
self.__routes = routes
def generate_url(self, route_name: str, **kwargs):
if route_name not in self.__routes:
raise Exception(f"Route no... | class Router:
def __init__(self, databricks_url: str, routes: dict):
self.__databricks_url = databricks_url
self.__routes = routes
def generate_url(self, route_name: str, **kwargs):
if route_name not in self.__routes:
raise exception(f'Route not defined: {route_name}')
... |
exception_messages = {
"InvalidSelectionStrategy": lambda selection_strategy, allowed_selection_strategies: f"{selection_strategy} is not a valid selection strategy. "
f"Available options are {', '.join(allowed_selection_strategies)}.",
"InvalidPopulationSize": "The population size must be larger than 2",
... | exception_messages = {'InvalidSelectionStrategy': lambda selection_strategy, allowed_selection_strategies: f"{selection_strategy} is not a valid selection strategy. Available options are {', '.join(allowed_selection_strategies)}.", 'InvalidPopulationSize': 'The population size must be larger than 2', 'InvalidExcludedGe... |
x = 25
epsilon = 0.01
numGuesses = 0
low = 1.0
high = x
guess = (high + low ) / 2.0
while abs(guess**2 - x) >= epsilon:
print ('low = ' + str(low) + 'high =' + str(high) + 'Guess = ' + str(guess))
numGuesses += 1
if guess**2 < x:
low = guess
else:
high = guess
guess ... | x = 25
epsilon = 0.01
num_guesses = 0
low = 1.0
high = x
guess = (high + low) / 2.0
while abs(guess ** 2 - x) >= epsilon:
print('low = ' + str(low) + 'high =' + str(high) + 'Guess = ' + str(guess))
num_guesses += 1
if guess ** 2 < x:
low = guess
else:
high = guess
guess = (high + low... |
# programme to input student details and view them
# this is a modification of students.py but using a dict for choices/options
# helen o'shea
# 20210218
# function to show the menu - same as students.py
def show_menu():
print("What would you like to do? \n\
\t(a) Add new student\n\
\t(v) View students\n\
\t... | def show_menu():
print('What would you like to do? \n \t(a) Add new student\n \t(v) View students\n \t(q) Quit')
option = input('Type one letter (a/v/q): ').strip()
return option
def do_add(students):
my_student = {}
myStudent['firstname'] = input('Enter your first name: ').strip()
myStudent... |
def tomadas():
reguas = list(map(int, input().split()))
t1 = reguas[0]
t2 = reguas[1]
t3 = reguas[2]
t4 = reguas[3]
numeros_de_aparelhos = t1 + t2 + t3 - 3 + t4
print(numeros_de_aparelhos)
tomadas()
| def tomadas():
reguas = list(map(int, input().split()))
t1 = reguas[0]
t2 = reguas[1]
t3 = reguas[2]
t4 = reguas[3]
numeros_de_aparelhos = t1 + t2 + t3 - 3 + t4
print(numeros_de_aparelhos)
tomadas() |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
# GN version: //cc
'target_name': 'cc',
'type': '<(component)',
... | {'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'cc', 'type': '<(component)', 'dependencies': ['cc_proto', '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '<(DEPTH)/gpu/gpu.gyp:gpu', '<(DEPTH)/media/media.gyp:media', '<(DEPTH)/s... |
max_size = 10
print(
"(a)" + " " * (max_size) +
"(b)" + " " * (max_size) +
"(c)" + " " * (max_size) +
"(d)" + " " * (max_size)
)
for i in range(1, max_size + 1):
print("*" * i, end = " " * (max_size - i + 3))
print("*" * (max_size - i + 1), end = " " * (i - 1 + 3))
print(" " * (i - ... | max_size = 10
print('(a)' + ' ' * max_size + '(b)' + ' ' * max_size + '(c)' + ' ' * max_size + '(d)' + ' ' * max_size)
for i in range(1, max_size + 1):
print('*' * i, end=' ' * (max_size - i + 3))
print('*' * (max_size - i + 1), end=' ' * (i - 1 + 3))
print(' ' * (i - 1) + '*' * (max_size - i + 1), end=' ' ... |
#
# PySNMP MIB module CNT2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNT2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
#flask
DEBUG = True
#session
SECRET_KEY="1145141919810"
#mysql
DIQLECT = "mysql"
DRIVER="pymysql"
USERNAME = "root"
PASSWORD = "root"
# PASSWORD = "7410188xw"
HOST = "127.0.0.1"
PORT = "3306"
DATABASE = "CSBIGHW"
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIQLECT,DRIVER,US... | debug = True
secret_key = '1145141919810'
diqlect = 'mysql'
driver = 'pymysql'
username = 'root'
password = 'root'
host = '127.0.0.1'
port = '3306'
database = 'CSBIGHW'
sqlalchemy_database_uri = '{}+{}://{}:{}@{}:{}/{}?charset=utf8'.format(DIQLECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE)
sqlalchemy_track_modi... |
def sum_double(a, b):
if a == b:
return (a+b)*2
else:
return a+b
| def sum_double(a, b):
if a == b:
return (a + b) * 2
else:
return a + b |
class CoalescenceException(Exception):
def __init__(self, msg=''):
self.msg = msg
class NoSuchSourceException(CoalescenceException):
pass
class NotAnElementException(CoalescenceException):
pass
class NotAValueException(CoalescenceException):
pass
class NoValueException(CoalescenceExceptio... | class Coalescenceexception(Exception):
def __init__(self, msg=''):
self.msg = msg
class Nosuchsourceexception(CoalescenceException):
pass
class Notanelementexception(CoalescenceException):
pass
class Notavalueexception(CoalescenceException):
pass
class Novalueexception(CoalescenceException)... |
# lextab.py. This file automatically created by PLY (version 3.4). Don't edit!
_tabversion = '3.4'
_lextokens = {'DO': 1, 'REMAINDER_ASSIGN': 1, 'RSHIFT': 1, 'SYNCHRONIZED': 1, 'GTEQ': 1, 'MINUS_ASSIGN': 1, 'OR_ASSIGN': 1, 'VOID': 1, 'STRING_LITERAL': 1, 'ABSTRACT': 1, 'CHAR': 1, 'LSHIFT_ASSIGN': 1, 'WHILE': 1, 'S... | _tabversion = '3.4'
_lextokens = {'DO': 1, 'REMAINDER_ASSIGN': 1, 'RSHIFT': 1, 'SYNCHRONIZED': 1, 'GTEQ': 1, 'MINUS_ASSIGN': 1, 'OR_ASSIGN': 1, 'VOID': 1, 'STRING_LITERAL': 1, 'ABSTRACT': 1, 'CHAR': 1, 'LSHIFT_ASSIGN': 1, 'WHILE': 1, 'SHORT': 1, 'STATIC': 1, 'PRIVATE': 1, 'LSHIFT': 1, 'CONTINUE': 1, 'THROWS': 1, 'NULL'... |
for i in range(0,21,2):
if(i==0):
i=i
elif(i==10 or i==20):
i=int(i/10)
else:
i/=10
for k in range(1,4):
print("I={} J={}".format(i, k+i)) | for i in range(0, 21, 2):
if i == 0:
i = i
elif i == 10 or i == 20:
i = int(i / 10)
else:
i /= 10
for k in range(1, 4):
print('I={} J={}'.format(i, k + i)) |
n = int(input())
i = 1
while(i < n):
j = 1
while(j <= i):
print((i*2-1), end=" ")
j = j+1
i = i + 1
print()
| n = int(input())
i = 1
while i < n:
j = 1
while j <= i:
print(i * 2 - 1, end=' ')
j = j + 1
i = i + 1
print() |
class Solution(object):
def maxSubArray(self, nums):
if not nums:
return 0
best_sum = nums[0]
current_sum = 0
for x in nums:
current_sum = max(x, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
in_arrs = [
[2, 1... | class Solution(object):
def max_sub_array(self, nums):
if not nums:
return 0
best_sum = nums[0]
current_sum = 0
for x in nums:
current_sum = max(x, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
in_arrs = [[2, 1, 2,... |
class Solution:
def moveZeroes(self, nums):
length = len(nums)
on_zero = run = 0
while True:
# find first zero in nums.
while nums[on_zero]:
on_zero = on_zero + 1
if on_zero == length:
return
# s... | class Solution:
def move_zeroes(self, nums):
length = len(nums)
on_zero = run = 0
while True:
while nums[on_zero]:
on_zero = on_zero + 1
if on_zero == length:
return
while not nums[run] or run < on_zero:
... |
#
# PySNMP MIB module VMWARE-VMINFO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-VMINFO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:27:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
'''
Created on 18 Nov 2020
@author: ernesto
'''
class AnnotationURIs(object):
'''
This class manages the most common ontology annotations
'''
def __init__(self):
'''
Constructor
'''
#Main label of an entity typically only one, but there may be several ... | """
Created on 18 Nov 2020
@author: ernesto
"""
class Annotationuris(object):
"""
This class manages the most common ontology annotations
"""
def __init__(self):
"""
Constructor
"""
self.mainLabelURIs = set()
self.synonymLabelURIs = set()
self.lexicalAn... |
DATA_TYPES = {
'AutoField': 'int IDENTITY (1, 1)',
'BooleanField': 'bit',
'CharField': 'varchar(%(maxlength)s)',
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)',
'DateField': 'smalldatetime',
'DateTimeField': 'smalldatetime',
'DecimalField': 'nume... | data_types = {'AutoField': 'int IDENTITY (1, 1)', 'BooleanField': 'bit', 'CharField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'DateField': 'smalldatetime', 'DateTimeField': 'smalldatetime', 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'FileField': 'varchar(100... |
'''Define terminal escape sequences for color codes.
<ESC>[{attr1};...;{attrn}m
0 Reset all attributes
1 Bright
2 Dim
4 Underscore
5 Blink
7 Reverse
8 Hidden
Foreground Colours
------------------
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White
Background Colours
------------------
40 Black
41... | """Define terminal escape sequences for color codes.
<ESC>[{attr1};...;{attrn}m
0 Reset all attributes
1 Bright
2 Dim
4 Underscore
5 Blink
7 Reverse
8 Hidden
Foreground Colours
------------------
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White
Background Colours
------------------
40 Black
41... |
JOINTS = {
"HipCenter": 0,
"RHip": 1,
"RKnee": 2,
"RFoot": 3,
"LHip": 4,
"LKnee": 5,
"LFoot": 6,
"Spine": 7,
"Thorax": 8,
"Neck/Nose": 9,
"Head": 10,
"LShoulder": 11,
"LElbow": 12,
"LWrist": 13,
"RShoulder": 14,
"RElbow": 15,
"RWrist": 16,
}
EDGES = (... | joints = {'HipCenter': 0, 'RHip': 1, 'RKnee': 2, 'RFoot': 3, 'LHip': 4, 'LKnee': 5, 'LFoot': 6, 'Spine': 7, 'Thorax': 8, 'Neck/Nose': 9, 'Head': 10, 'LShoulder': 11, 'LElbow': 12, 'LWrist': 13, 'RShoulder': 14, 'RElbow': 15, 'RWrist': 16}
edges = ((0, 1), (1, 2), (2, 3), (0, 4), (4, 5), (5, 6), (0, 7), (7, 8), (8, 9), ... |
#!/usr/bin/env python3
# The missing value is always in range 1...len(nums)+1
# linear space and time
def find_first_missing(nums):
seen = [False] * len(nums)
for n in nums:
if n >= 1 and n <= len(nums):
seen[n-1] = True
for i in range(len(nums)):
if not seen[i]:
... | def find_first_missing(nums):
seen = [False] * len(nums)
for n in nums:
if n >= 1 and n <= len(nums):
seen[n - 1] = True
for i in range(len(nums)):
if not seen[i]:
return i + 1
return len(nums) + 1
def find_first_missing_opt(nums):
for i in range(len(nums)):
... |
#!/usr/bin/python3
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2 * 2)
except MyError as err:
print('My Exception occurred, value: ', err.value)
| class Myerror(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise my_error(2 * 2)
except MyError as err:
print('My Exception occurred, value: ', err.value) |
class Laptop:
def getTime(self):
pass
def playWavFile(self, file):
pass
def wavWasPlayed(self, file):
pass
def resetWav(self, file):
pass
| class Laptop:
def get_time(self):
pass
def play_wav_file(self, file):
pass
def wav_was_played(self, file):
pass
def reset_wav(self, file):
pass |
def rowapplymods(transactionrow):
value = transactionrow.prevalue
for mod in transactionrow.includes_mods:
value = mod.apply(transactionrow.amount, value)[0]
transactionrow.value = value
| def rowapplymods(transactionrow):
value = transactionrow.prevalue
for mod in transactionrow.includes_mods:
value = mod.apply(transactionrow.amount, value)[0]
transactionrow.value = value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.