content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def num_of_factors(num):
n = 0
factor = 1
while factor * factor < num:
if num % factor == 0:
n += 1
factor += 1
if factor * factor > num:
return n * 2
else:
# perfect square
return n * 2 + 1
triangle = 0
i = 1
while True:
triangle += i
if ... | def num_of_factors(num):
n = 0
factor = 1
while factor * factor < num:
if num % factor == 0:
n += 1
factor += 1
if factor * factor > num:
return n * 2
else:
return n * 2 + 1
triangle = 0
i = 1
while True:
triangle += i
if num_of_factors(triangle) >... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Nonea
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... | class Solution(object):
def postorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ans = []
s = []
pre = None
while root or s:
if root:
s.append(root)
root = root.left
el... |
# bulk_data = []
# for row in csv_file_object:
# data_dict = {}
# for i in range(len(row)):
# data_dict[header[i]] = row[i]
# op_dict = {
# "index": {
# "_index": INDEX_NAME,
# "_type": TYPE_NAME,
# "_id": data_dict[ID_FIELD]
# }
# }
# b... | x = 10
y = 20
def a():
print(x)
x = x + 10
def b():
print(y)
print(a(), b(), x) |
class t_list():
def __init__(self, lst = []):
lst.sort()
self.lst = [[el, el] for el in lst]
def __len__ (self):
return len(self.lst)
def create(self, lst):
lst.sort()
self.lst = [[el, el] for el in lst]
def add(self, val, t):
left = 0
right = ... | class T_List:
def __init__(self, lst=[]):
lst.sort()
self.lst = [[el, el] for el in lst]
def __len__(self):
return len(self.lst)
def create(self, lst):
lst.sort()
self.lst = [[el, el] for el in lst]
def add(self, val, t):
left = 0
right = len(s... |
OperandSet = {
'Ib' : {
'16' : ( "0x10", ),
'32' : ( "0x10", ),
'64' : ( "0x20", )
},
'Eb_Gb' : {
'16' : ( "[bx+si], al", ),
'32' : ( "[eax+ebx], ch", "[ebx+ecx*4], bl", "[bx+0x10], dh"),
'64' : ( "[rax], r8b", )
... | operand_set = {'Ib': {'16': ('0x10',), '32': ('0x10',), '64': ('0x20',)}, 'Eb_Gb': {'16': ('[bx+si], al',), '32': ('[eax+ebx], ch', '[ebx+ecx*4], bl', '[bx+0x10], dh'), '64': ('[rax], r8b',)}, 'Ev_Gv': {'16': (), '32': ('[eax+0x1234], esi', '[bx+si+0x1234], esp', '[esp+0x10], ebp'), '64': ()}, 'Gb_Eb': {'16': ('al, bl'... |
"""Python serial number generator."""
class SerialGenerator:
"""Machine to create unique incrementing serial numbers.
>>> serial = SerialGenerator(start=100)
>>> serial.generate()
100
>>> serial.generate()
101
>>> serial.generate()
102
>>> serial.reset()
>>> serial.generate()
... | """Python serial number generator."""
class Serialgenerator:
"""Machine to create unique incrementing serial numbers.
>>> serial = SerialGenerator(start=100)
>>> serial.generate()
100
>>> serial.generate()
101
>>> serial.generate()
102
>>> serial.reset()
>>> serial.generate()
... |
def calculation(operator,n_1,n_2):
if operator == "multiply":
return n_1 * n_2
elif operator == "divide":
return n_1 // n_2
elif operator == "add":
return n_1 + n_2
elif operator == "subtract":
return n_1 - n_2
operator = input()
n_1 = int(input())
n_2 = int(input())
pr... | def calculation(operator, n_1, n_2):
if operator == 'multiply':
return n_1 * n_2
elif operator == 'divide':
return n_1 // n_2
elif operator == 'add':
return n_1 + n_2
elif operator == 'subtract':
return n_1 - n_2
operator = input()
n_1 = int(input())
n_2 = int(input())
pr... |
# -*- coding: utf-8 -*-
"""
flaskbb.utils.permissions
~~~~~~~~~~~~~~~~~~~~~~~~~
A place for all permission checks
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
def check_perm(user, perm, forum, post_user_id=None):
"""Checks if the `user` has a spe... | """
flaskbb.utils.permissions
~~~~~~~~~~~~~~~~~~~~~~~~~
A place for all permission checks
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
def check_perm(user, perm, forum, post_user_id=None):
"""Checks if the `user` has a specified `perm` in the `for... |
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
if target >= letters[-1]: return letters[0]
left, right = 0, len(letters)
while left < right:
mid = left + (right - left) // 2
if letters[mid] <= target:
left = mid ... | class Solution:
def next_greatest_letter(self, letters: List[str], target: str) -> str:
if target >= letters[-1]:
return letters[0]
(left, right) = (0, len(letters))
while left < right:
mid = left + (right - left) // 2
if letters[mid] <= target:
... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( keypad , n ) :
if ( not keypad or n <= 0 ) :
return 0
if ( n == 1 ) :
return 10
odd = [... | def f_gold(keypad, n):
if not keypad or n <= 0:
return 0
if n == 1:
return 10
odd = [0] * 10
even = [0] * 10
i = 0
j = 0
use_odd = 0
total_count = 0
for i in range(10):
odd[i] = 1
for j in range(2, n + 1):
use_odd = 1 - useOdd
if useOdd == ... |
def log(rv):
"""
Returns the natural logarithm of a random variable
"""
return rv.log()
def exp(rv):
"""
Returns the exponentiation of a random variable
"""
return rv.exp()
def sqrt(rv):
"""
Returns the square root of a random variable
"""
return rv**0.5
def pow(rv, k)... | def log(rv):
"""
Returns the natural logarithm of a random variable
"""
return rv.log()
def exp(rv):
"""
Returns the exponentiation of a random variable
"""
return rv.exp()
def sqrt(rv):
"""
Returns the square root of a random variable
"""
return rv ** 0.5
def pow(rv, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
DENIED_ACTIONS = {
"access-analyzer:DeleteAnalyzer",
"cloudtrail:CreateTrail",
"cloudtrail:DeleteTrail",
"cloudtrail:UpdateTrail",
"cloudtrail:StopLogging",
"config:DeleteConfigRule",
"config:DeleteConfigurationRecorder",
"config:DeleteDeliv... | denied_actions = {'access-analyzer:DeleteAnalyzer', 'cloudtrail:CreateTrail', 'cloudtrail:DeleteTrail', 'cloudtrail:UpdateTrail', 'cloudtrail:StopLogging', 'config:DeleteConfigRule', 'config:DeleteConfigurationRecorder', 'config:DeleteDeliveryChannel', 'config:StopConfigurationRecorder', 'ec2:AcceptVpcPeeringConnection... |
X = int(input())
Y = int(input())
Z = int(input())
N = int(input())
result = [ [x, y, z] for x in range(X+1) for y in range(Y+1) for z in range(Z+1) if x + y + z != N ]
print(result)
| x = int(input())
y = int(input())
z = int(input())
n = int(input())
result = [[x, y, z] for x in range(X + 1) for y in range(Y + 1) for z in range(Z + 1) if x + y + z != N]
print(result) |
class Solution:
def lexicographically_minimal_string(self, a, b):
"""
:type strs: a, b
:rtype: str
"""
a = [ord(x) for x in list(a[::-1])]
b = [ord(x) for x in list(b[::-1])]
lms = []
while len(a) != 0 and len(b) != 0:
if a[-1] < b[-1]:
... | class Solution:
def lexicographically_minimal_string(self, a, b):
"""
:type strs: a, b
:rtype: str
"""
a = [ord(x) for x in list(a[::-1])]
b = [ord(x) for x in list(b[::-1])]
lms = []
while len(a) != 0 and len(b) != 0:
if a[-1] < b[-1]:
... |
class Solution:
def minimumDeleteSum(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: int
"""
# use dynamic programming and rolling window
dp = [[0] * (len(s2) + 1) for _ in range(2)]
for i in range(len(s2)):
dp[0][i+1] = dp[0][i] + o... | class Solution:
def minimum_delete_sum(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: int
"""
dp = [[0] * (len(s2) + 1) for _ in range(2)]
for i in range(len(s2)):
dp[0][i + 1] = dp[0][i] + ord(s2[i])
for i in range(len(s1)):
... |
with open('test.txt', 'w') as file:
content = input('Write into file: ')
file.write(content)
with open('test.txt', 'a') as file:
s = ''
while s!= '@':
file.write(s)
s = input('Append into file: ')
with open('test.txt') as file:
print(file.read()) | with open('test.txt', 'w') as file:
content = input('Write into file: ')
file.write(content)
with open('test.txt', 'a') as file:
s = ''
while s != '@':
file.write(s)
s = input('Append into file: ')
with open('test.txt') as file:
print(file.read()) |
def sumofs1():
s1=0
n=int(input("enter a number:"))
for i in range(1,n+1):
s1=s1+i
print("sumofs1=",s1)
def sumofs2():
s2=0
m=int(input("enter a number:"))
for j in range(1,m+1):
s2=s2+(j*j)
print("sumofs2=",s2)
def sumofs3():
s3=0
p=int(input("enter... | def sumofs1():
s1 = 0
n = int(input('enter a number:'))
for i in range(1, n + 1):
s1 = s1 + i
print('sumofs1=', s1)
def sumofs2():
s2 = 0
m = int(input('enter a number:'))
for j in range(1, m + 1):
s2 = s2 + j * j
print('sumofs2=', s2)
def sumofs3():
s3 = 0
p = ... |
# Add your list of tweets here in this list. Make sure the messages are inside double quotes and end with a comma.
# For example: "Hello Check, my profile",
# The program will then randomly select one of the messages and post it to Twitter.
# Also if your message contains a double quote, you need to escape it with a b... | tweets = ['Hello, Check my profile', 'Great Job,', 'Cool NFTs']
accounts = {'account1': {'username': 'qbanbabee', 'password': 'CDxrRcqSHP'}, 'account2': {'username': 'r3i2x', 'password': '!seucNgU9D'}, 'account3': {'username': 'AprilThorne8', 'password': 'kfjOZcdkzVvOliv'}, 'account3': {'username': 'fitriamarthaa', 'pa... |
#!/usr/bin/env python3
types = {
"BASIC_CONSTRAINTS": {
"ca": "ca_bool_int",
"pathlen": "ASN1_INTEGER",
},
}
getter_conv_tmpl = {
"ca_bool_int": "ctx.{k} == 0xFF",
"ASN1_INTEGER": "tonumber(C.ASN1_INTEGER_get(ctx.{k}))",
}
setter_conv_tmpl = {
"ca_bool_int": '''
toset.{k} = cfg_... | types = {'BASIC_CONSTRAINTS': {'ca': 'ca_bool_int', 'pathlen': 'ASN1_INTEGER'}}
getter_conv_tmpl = {'ca_bool_int': 'ctx.{k} == 0xFF', 'ASN1_INTEGER': 'tonumber(C.ASN1_INTEGER_get(ctx.{k}))'}
setter_conv_tmpl = {'ca_bool_int': '\n toset.{k} = cfg_lower.{k} and 0xFF or 0', 'ASN1_INTEGER': '\n local {k} = cfg_lower.{k} ... |
#
# PySNMP MIB module DLINK-3100-MIR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-MIR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:48:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
# classificationMethod.py
# -----------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to ht... | class Classificationmethod:
"""
ClassificationMethod is the abstract superclass of
- MostFrequentClassifier
- NaiveBayesClassifier
- PerceptronClassifier
- MiraClassifier
As such, you need not add any code to this file. You can write
all of your implementation code in the files for... |
''' mbinary
#########################################################################
# File : allOoneDS.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-05-19 23:07
# Description:
####################################################... | """ mbinary
#########################################################################
# File : allOoneDS.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-05-19 23:07
# Description:
####################################################... |
def insertData(db):
db.insert("RESTRICTION",('Titanic',1997,'M','Australia'))
db.insert("RESTRICTION",('Titanic',1997,'KT','Belgium'))
db.insert("RESTRICTION",('Titanic',1997,'TE','Chile'))
db.insert("RESTRICTION",('Titanic',1997,'K-12','Finland'))
db.insert("RESTRICTION",('Titanic',1997,'U','France... | def insert_data(db):
db.insert('RESTRICTION', ('Titanic', 1997, 'M', 'Australia'))
db.insert('RESTRICTION', ('Titanic', 1997, 'KT', 'Belgium'))
db.insert('RESTRICTION', ('Titanic', 1997, 'TE', 'Chile'))
db.insert('RESTRICTION', ('Titanic', 1997, 'K-12', 'Finland'))
db.insert('RESTRICTION', ('Titanic... |
model = """# Stochastic Simulation Algorithm input format
R1:
$pool > TF
kTFsyn
R2:
TF > $pool
kTFdeg*TF
R3:
TFactive > $pool
kTFdeg*TFactive
R4:
TF > TFactive
kActivate*TF
R5:
TFactive > TF
kInactivate*TFactive
R6:
TFactive > mRNA + TFactive
kmRNAsyn*(TFactive/(TFact... | model = '# Stochastic Simulation Algorithm input format\n\nR1:\n $pool > TF\n kTFsyn\nR2:\n TF > $pool\n kTFdeg*TF\nR3:\n TFactive > $pool\n kTFdeg*TFactive\nR4:\n TF > TFactive\n kActivate*TF \nR5: \n TFactive > TF\n kInactivate*TFactive\nR6:\n TFactive > mRNA + TFactive\n kmRNAsyn... |
class Solution:
def assignBikes(self, W: List[List[int]], B: List[List[int]]) -> List[int]:
ans, used = [-1] * len(W), set()
for d, w, b in sorted([abs(W[i][0] - B[j][0]) + abs(W[i][1] - B[j][1]), i, j] for i in range(len(W)) for j in range(len(B))):
if ans[w] == -1 and b not in used:
... | class Solution:
def assign_bikes(self, W: List[List[int]], B: List[List[int]]) -> List[int]:
(ans, used) = ([-1] * len(W), set())
for (d, w, b) in sorted(([abs(W[i][0] - B[j][0]) + abs(W[i][1] - B[j][1]), i, j] for i in range(len(W)) for j in range(len(B)))):
if ans[w] == -1 and b not i... |
class OneLayerActiveScriptGen:
def __init__(self, args):
self.valid = args.split('|')
pass
def GenerateScript(self, arg2):
if len(self.valid) == 1:
#OK, this uses sub-layers
Script = "for (i=0;i<app.activeDocument.layers.length;i++)\n"
... | class Onelayeractivescriptgen:
def __init__(self, args):
self.valid = args.split('|')
pass
def generate_script(self, arg2):
if len(self.valid) == 1:
script = 'for (i=0;i<app.activeDocument.layers.length;i++)\n'
script += '{\n'
for vl in self.valid:
... |
def downcase_keys(dict_):
return {k.lower(): v for k, v in dict_.items()}
def assert_aws4auth_in_headers(headers):
lc_headers = downcase_keys(headers)
assert 'authorization' in lc_headers
assert 'x-amz-date' in lc_headers
assert 'x-amz-content-sha256' in lc_headers
auth_header = lc_headers.get... | def downcase_keys(dict_):
return {k.lower(): v for (k, v) in dict_.items()}
def assert_aws4auth_in_headers(headers):
lc_headers = downcase_keys(headers)
assert 'authorization' in lc_headers
assert 'x-amz-date' in lc_headers
assert 'x-amz-content-sha256' in lc_headers
auth_header = lc_headers.ge... |
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.n = 853
self.hashtable = [None] * self.n
def add(self, key: int) -> None:
idx = key % self.n
if not self.hashtable[idx]:
self.hashtable[idx] = BST(key)
... | class Myhashset:
def __init__(self):
"""
Initialize your data structure here.
"""
self.n = 853
self.hashtable = [None] * self.n
def add(self, key: int) -> None:
idx = key % self.n
if not self.hashtable[idx]:
self.hashtable[idx] = bst(key)
... |
"""Useful literals"""
TABLE_LEVEL_PG_STAT_USER_TABLES_COLUMNS = [
"relid",
"schemaname",
"relname",
"seq_scan",
"seq_tup_read",
"idx_scan",
"idx_tup_fetch",
"n_tup_ins",
"n_tup_upd",
"n_tup_del",
"n_tup_hot_upd",
"n_live_tup",
"n_dead_tup",
"n_mod_since_analyze",... | """Useful literals"""
table_level_pg_stat_user_tables_columns = ['relid', 'schemaname', 'relname', 'seq_scan', 'seq_tup_read', 'idx_scan', 'idx_tup_fetch', 'n_tup_ins', 'n_tup_upd', 'n_tup_del', 'n_tup_hot_upd', 'n_live_tup', 'n_dead_tup', 'n_mod_since_analyze', 'last_vacuum', 'last_autovacuum', 'last_analyze', 'last_a... |
class PersonError(Exception):
def __init__(self, a, b):
self.a = a
self.b = b
def print_obj(self):
print(self.a, self.b)
class Person:
def __init__(self, name: str, surname: str, age: int, gender: str):
try:
if age <= 0:
raise PersonError("Perso... | class Personerror(Exception):
def __init__(self, a, b):
self.a = a
self.b = b
def print_obj(self):
print(self.a, self.b)
class Person:
def __init__(self, name: str, surname: str, age: int, gender: str):
try:
if age <= 0:
raise person_error('Per... |
number_one = int(input("Enter a number: "))
number_two = int(input("Enter another number: "))
if (number_one > number_two):
print("Number one is greater than number two")
else:
print("Number two is greater than number one") | number_one = int(input('Enter a number: '))
number_two = int(input('Enter another number: '))
if number_one > number_two:
print('Number one is greater than number two')
else:
print('Number two is greater than number one') |
# Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours.
# Enter Hours: 45
# Enter Rate: 10
# Pay: 475.0
hours = int(input('Enter hours: '));
rate = float(input('Enter rate: '));
if hours > 40:
rate = rate * 1.5
pay = hours * rate;
print('Pay',pay); | hours = int(input('Enter hours: '))
rate = float(input('Enter rate: '))
if hours > 40:
rate = rate * 1.5
pay = hours * rate
print('Pay', pay) |
n = int(input())
for i in range(n,0,-1):
if n%i==0:
n=i
print(i, end=' ') | n = int(input())
for i in range(n, 0, -1):
if n % i == 0:
n = i
print(i, end=' ') |
###############################################################
# Servers
###############################################################
class ServerType(models.Model):
name = models.CharField(max_length=40, verbose_name='Nome')
type = models.CharField(max_length=40, verbose_name='Tipo')
creat... | class Servertype(models.Model):
name = models.CharField(max_length=40, verbose_name='Nome')
type = models.CharField(max_length=40, verbose_name='Tipo')
created_at = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name='Created')
updated_at = models.DateTimeField(auto_now=True, verbose_na... |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/92_set_directories.ipynb (unless otherwise specified).
__all__ = ['Dirs']
#Cell
"""
Directories for Image preparation training and testing
"""
class Dirs:
def __init__(obj, basepath):
obj.basepath = basepath
obj.originImages = basepath + '/Original'
... | __all__ = ['Dirs']
'\nDirectories for Image preparation training and testing\n'
class Dirs:
def __init__(obj, basepath):
obj.basepath = basepath
obj.originImages = basepath + '/Original'
obj.train = basepath + '/Fullsize/Train'
obj.validTxtFile = basepath + '/Fullsize/valid.txt'
... |
class MyClass:
def func_1(self):
return "1"
def func_2(func):
return func()
def main():
a=func_2(MyClass().func_1)
print(a)
if __name__ == '__main__':
main()
| class Myclass:
def func_1(self):
return '1'
def func_2(func):
return func()
def main():
a = func_2(my_class().func_1)
print(a)
if __name__ == '__main__':
main() |
people = ['Conrad', 'Deepak', 'Heinrich', 'Tom']
ages = [29, 30, 34, 36]
for position in range(len(people)):
person = people[position]
age = ages[position]
print(person, age)
| people = ['Conrad', 'Deepak', 'Heinrich', 'Tom']
ages = [29, 30, 34, 36]
for position in range(len(people)):
person = people[position]
age = ages[position]
print(person, age) |
income_tax=0
id = int(input("Enter Employee id: "))
basic_salary = int(input("Enter monthly gross salary: "))
allowance = int(input("Enter allowance: "))
gross_salary = basic_salary+allowance
if gross_salary<=5000:
income_tax = 0
elif gross_salary<=10000:
income_tax = 0.1 * gross_salary
elif gross_salary<=20... | income_tax = 0
id = int(input('Enter Employee id: '))
basic_salary = int(input('Enter monthly gross salary: '))
allowance = int(input('Enter allowance: '))
gross_salary = basic_salary + allowance
if gross_salary <= 5000:
income_tax = 0
elif gross_salary <= 10000:
income_tax = 0.1 * gross_salary
elif gross_salar... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-11-16 21:11:11
# Description:
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
count = 0
result = 0
dict_seen = {0: -1}
for i in range(len(nums)):
n = nums[i]
if n =... | class Solution:
def find_max_length(self, nums: List[int]) -> int:
count = 0
result = 0
dict_seen = {0: -1}
for i in range(len(nums)):
n = nums[i]
if n == 0:
count -= 1
if n == 1:
count += 1
if count in ... |
__author__ = 'prossi'
class DISK:
def __init__(self, obj, connection):
self.__dict__ = dict(obj.attrib)
self.connection = connection
| __author__ = 'prossi'
class Disk:
def __init__(self, obj, connection):
self.__dict__ = dict(obj.attrib)
self.connection = connection |
class ResponseMaker(object):
__slot__ = ['error_verbose']
def __init__(self, error_verbose=True):
self.error_verbose = error_verbose
def get_response(self, result, request_id):
return {
"jsonrpc": "2.0",
"result": result,
"id": request_id
}
... | class Responsemaker(object):
__slot__ = ['error_verbose']
def __init__(self, error_verbose=True):
self.error_verbose = error_verbose
def get_response(self, result, request_id):
return {'jsonrpc': '2.0', 'result': result, 'id': request_id}
def get_error(self, code, message, data=None, ... |
def Sorting_array_data(A,i):
B = sorted(A, key=lambda a_entry: a_entry[i])
return B
| def sorting_array_data(A, i):
b = sorted(A, key=lambda a_entry: a_entry[i])
return B |
class Tracker(object):
def __init__(self):
self.trk = [] # currently tracked 2D Points
self.trk_i = [] # self.pts[self.trk_i] are currently tracked
self.pts = [] # list of all known object feature point positions
self.kpt = [] # corresponding image coordinates for all points
... | class Tracker(object):
def __init__(self):
self.trk = []
self.trk_i = []
self.pts = []
self.kpt = []
self.des = []
def detect(self, img):
pass
def solve(self, img, pt0, pt1, li_c):
(e, _) = find_essential_mat(...)
def track(self, img0, kpt0, de... |
# Write an efficient program to find the sum of contiguous subarray within
# a one-dimensional array of numbers which has the largest sum.
def max_sum_kadane(nums: list) -> int:
# kadane's algorithm
max_so_far = max_ending_here = 0
for value in nums:
max_ending_here = max(max_ending_here + value,... | def max_sum_kadane(nums: list) -> int:
max_so_far = max_ending_here = 0
for value in nums:
max_ending_here = max(max_ending_here + value, 0)
if max_ending_here > 0:
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
def max_sum_print_subarray(nums: list) -> int:
... |
class Runtime:
"""Encapsulates the runtime state of execution itself, excluding I/O."""
def __init__(self, program, env):
self.program = program
self.env = env
| class Runtime:
"""Encapsulates the runtime state of execution itself, excluding I/O."""
def __init__(self, program, env):
self.program = program
self.env = env |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 15:54:59 2019
@author: janej
"""
print('name:'+__name__)
print('package:'+__package__)
print('doc:'+__doc__)
print('file:'+__file__)
| """
Created on Thu Jan 3 15:54:59 2019
@author: janej
"""
print('name:' + __name__)
print('package:' + __package__)
print('doc:' + __doc__)
print('file:' + __file__) |
# Copyright 2013 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,
'variables': {
'version_py_path': '<(DEPTH)/build/util/version.py',
'version_path': 'VERSION',
... | {'variables': {'chromium_code': 1, 'variables': {'version_py_path': '<(DEPTH)/build/util/version.py', 'version_path': 'VERSION'}, 'version_py_path': '<(version_py_path) -f', 'version_path': '<(version_path)'}, 'includes': ['../build/util/version.gypi'], 'targets': [{'target_name': 'cloud_print_version_resources', 'type... |
'''
Steven Kyritsis CS100
2021F Section 031 HW 08,
November 5, 2021
'''
#1
def two_words(length, first_letter):
while True:
word1 = input("Please enter a " + str(length) + "-letter word please: ")
if len(word1) == length:
break
while True:
word2 = input("Please enter a word ... | """
Steven Kyritsis CS100
2021F Section 031 HW 08,
November 5, 2021
"""
def two_words(length, first_letter):
while True:
word1 = input('Please enter a ' + str(length) + '-letter word please: ')
if len(word1) == length:
break
while True:
word2 = input('Please enter a word be... |
X, Y, A, B = map(int, input().split())
ans = 0
while True:
if X*A < B and X*A < Y:
X *= A
ans += 1
else:
break
ans += (Y-X-1)//B
print(ans)
| (x, y, a, b) = map(int, input().split())
ans = 0
while True:
if X * A < B and X * A < Y:
x *= A
ans += 1
else:
break
ans += (Y - X - 1) // B
print(ans) |
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
User with authorization to peform administrative tasks such as associating
users to roles within the scope of of a program.<br/><br/>When a person
creates a ... | scope = 'Private Program'
description = '\n User with authorization to peform administrative tasks such as associating\n users to roles within the scope of of a program.<br/><br/>When a person\n creates a program they are automatically given the ProgramOwner role. This\n allows them to Edit, Delete, or Map objects ... |
"""Exceptions raised by this NApp."""
class DeviceException(Exception):
"""Device related exception."""
def __init__(self, message, device=None):
"""Take the parameter to inform the user about the error.
Args:
device (str, :class:`Device`): The device that was looked for.
... | """Exceptions raised by this NApp."""
class Deviceexception(Exception):
"""Device related exception."""
def __init__(self, message, device=None):
"""Take the parameter to inform the user about the error.
Args:
device (str, :class:`Device`): The device that was looked for.
... |
"""A function for testing approximate equality of two numbers.
Same as math.isclose in Python v3.5 (and newer)
https://www.python.org/dev/peps/pep-0485
"""
def almost_equal(a, b, rel_tol=1e-09, abs_tol=0.0):
"""A function for testing approximate equality of two numbers.
Same as math.isclose in Python v3.5 (an... | """A function for testing approximate equality of two numbers.
Same as math.isclose in Python v3.5 (and newer)
https://www.python.org/dev/peps/pep-0485
"""
def almost_equal(a, b, rel_tol=1e-09, abs_tol=0.0):
"""A function for testing approximate equality of two numbers.
Same as math.isclose in Python v3.5 (and... |
old_file = open('city.txt', 'r')
new_file = open('city_with_format.txt', 'w')
all_cities = old_file.readlines()
# print all_cities
for i in all_cities:
city, country = i.strip().split()
new_file.write('%-25s%-25s\n' % (city, country))
old_file.close()
new_file.close()
| old_file = open('city.txt', 'r')
new_file = open('city_with_format.txt', 'w')
all_cities = old_file.readlines()
for i in all_cities:
(city, country) = i.strip().split()
new_file.write('%-25s%-25s\n' % (city, country))
old_file.close()
new_file.close() |
{
'targets': [
{
'configurations': {
'Debug': { },
'Release': { }
},
'target_name': 'appels',
'type': 'executable',
'dependencies': [
'third_party/skia/skia.gyp:alltargets',
'third_party/skia/gyp/sdl.gyp:sdl',
],
'include_dirs': [
'... | {'targets': [{'configurations': {'Debug': {}, 'Release': {}}, 'target_name': 'appels', 'type': 'executable', 'dependencies': ['third_party/skia/skia.gyp:alltargets', 'third_party/skia/gyp/sdl.gyp:sdl'], 'include_dirs': ['third_party/skia/include/config', 'third_party/skia/include/core', 'third_party/skia/include/gpu', ... |
def pattern(n):
if n <= 1:
return ""
res = ""
for i in range(1, n//2+1):
res += str(i*2)*(i*2)+"\n"
return res[:-1] | def pattern(n):
if n <= 1:
return ''
res = ''
for i in range(1, n // 2 + 1):
res += str(i * 2) * (i * 2) + '\n'
return res[:-1] |
TOTAL_CHARACTERS = 'SELECT COUNT(character_id) FROM charactercreator_character;'
TOTAL_SUBCLASS = '''
SELECT COUNT(*) FROM (SELECT *
FROM charactercreator_character cc_c
INNER JOIN charactercreator_necromancer cc_n
ON cc_c.character_id = cc... | total_characters = 'SELECT COUNT(character_id) FROM charactercreator_character;'
total_subclass = '\n SELECT COUNT(*) FROM (SELECT *\n FROM charactercreator_character cc_c\n INNER JOIN charactercreator_necromancer cc_n\n ON cc_c.character_id = ... |
response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [
(T('Home'),URL('default','index')==URL(),URL('default','index'),[]),
(T('C... | response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [(t('Home'), url('default', 'index') == url(), url('default', 'index'), []),... |
class Solution:
def split(self, spaces: int, sets: int) -> Iterable[int]:
if (spaces % sets == 0):
rem = spaces // sets
return (rem for i in range(sets))
else:
rem, bigRem = sets - (spaces % sets), spaces//sets
return (bigRem + 1 if (i >= rem) else big... | class Solution:
def split(self, spaces: int, sets: int) -> Iterable[int]:
if spaces % sets == 0:
rem = spaces // sets
return (rem for i in range(sets))
else:
(rem, big_rem) = (sets - spaces % sets, spaces // sets)
return (bigRem + 1 if i >= rem else b... |
#
# PySNMP MIB module FMS100-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FMS100-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:14:07 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:... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_range_constraint, value_size_constraint) ... |
"""
Write program, that will count the sum of all numbers from 1 to
number that was entered by user.
1,2,3,4,5,... 100
(1 + 100) / 2 * 100
For 5:
1+2+3+4+5
the result is gonna be:
15
(1 + 5) / 2 * 5 = 15
range(1, 6)
1,2,3,4,5
"""
def sum_up_to(end):
sum = 0 # 15
for number in rang... | """
Write program, that will count the sum of all numbers from 1 to
number that was entered by user.
1,2,3,4,5,... 100
(1 + 100) / 2 * 100
For 5:
1+2+3+4+5
the result is gonna be:
15
(1 + 5) / 2 * 5 = 15
range(1, 6)
1,2,3,4,5
"""
def sum_up_to(end):
sum = 0
for number in range(1, end + 1):
sum = ... |
{
"targets": [
{
"target_name": "cpp-netlib",
"type": "static_library", # unlike boost-asio which is header-only
"include_dirs": [
"0.11.1-final/cpp-netlib-cpp-netlib-0.11.1-final"
],
"defines": [
"BOOST_NETWORK_ENAB... | {'targets': [{'target_name': 'cpp-netlib', 'type': 'static_library', 'include_dirs': ['0.11.1-final/cpp-netlib-cpp-netlib-0.11.1-final'], 'defines': ['BOOST_NETWORK_ENABLE_HTTPS'], 'sources': ['0.11.1-final/cpp-netlib-cpp-netlib-0.11.1-final/libs/network/src/*.cpp', '0.11.1-final/cpp-netlib-cpp-netlib-0.11.1-final/libs... |
def chdir():
pass
def getcwd():
pass
def listdir():
pass
def mkdir():
pass
def remove():
pass
def rename():
pass
def rmdir():
pass
sep = "/"
def stat():
pass
def statvfs():
pass
def sync():
pass
def uname():
pass
def unlink():
pass
def urandom():... | def chdir():
pass
def getcwd():
pass
def listdir():
pass
def mkdir():
pass
def remove():
pass
def rename():
pass
def rmdir():
pass
sep = '/'
def stat():
pass
def statvfs():
pass
def sync():
pass
def uname():
pass
def unlink():
pass
def urandom():
pass |
#!/usr/bin/env python
"""Contains the Data Model Descripts for the REST Resources.
Contains the Data Model Configuration settings for each
REST Resource provided by the Python Eve Server. Data
validation object typing is also included.
"""
__author__ = "Sanjay Joshi"
__copyright__ = "IBM Copyright 2015"
__credits__ =... | """Contains the Data Model Descripts for the REST Resources.
Contains the Data Model Configuration settings for each
REST Resource provided by the Python Eve Server. Data
validation object typing is also included.
"""
__author__ = 'Sanjay Joshi'
__copyright__ = 'IBM Copyright 2015'
__credits__ = ['Sanjay Joshi']
__li... |
# Given a linked list, rotate the list to the right by k places, where k is non-negative.
#
# Example 1:
#
# Input: 1->2->3->4->5->NULL, k = 2
# Output: 4->5->1->2->3->NULL
# Explanation:
# rotate 1 steps to the right: 5->1->2->3->4->NULL
# rotate 2 steps to the right: 4->5->1->2->3->NULL
# Example 2:
#
# Input: 0->1->... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotate_right(self, head, k):
if not head:
return head
if not head.next:
return head
length = 0
curr = head
while curr:
length +=... |
# 28 Wind Chill
#Asking for air temperature and wind speed.
T = float(input('Enter the air temperature in celsius= '))
v = float(input('Enter the velocity of windin km/h = '))
x = round(13.12 * 0.6215 * T - 11.37 * v ** 0.16 + 0.3965 * T * v ** 0.16)
print('Wind chill index = ',x)
| t = float(input('Enter the air temperature in celsius= '))
v = float(input('Enter the velocity of windin km/h = '))
x = round(13.12 * 0.6215 * T - 11.37 * v ** 0.16 + 0.3965 * T * v ** 0.16)
print('Wind chill index = ', x) |
"""
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_... | """
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_... |
##Read the dictionary
fh = open('C:\\english-dict.txt')
dict = []
while True:
line = fh.readline()
dict.append(line.strip())
if not line:
break
fh.close()
#Enter letters to use when compile a list of words
letters = input("Please enter your letters: ")
letters_set=set(letters)
mini = input("Minimu... | fh = open('C:\\english-dict.txt')
dict = []
while True:
line = fh.readline()
dict.append(line.strip())
if not line:
break
fh.close()
letters = input('Please enter your letters: ')
letters_set = set(letters)
mini = input('Minimum length of the word (default is 2): ')
maks = int(input('Maximum length ... |
class Collector:
def __init__(self, name, have_task=True):
self.name = name
self.have_task = have_task
self.data_dict = None
self.last_collect = 0
def run_task(self):
pass
def get_data(self):
pass
| class Collector:
def __init__(self, name, have_task=True):
self.name = name
self.have_task = have_task
self.data_dict = None
self.last_collect = 0
def run_task(self):
pass
def get_data(self):
pass |
#
# Copyright (c) 2009 Voltaire
# $COPYRIGHT$
#
# Additional copyrights may follow
#
# $HEADER$
#
"""
Configuration settings for application
"""
# Debug mode
DEBUG = True
# Authorisation key
AUTH = "" | """
Configuration settings for application
"""
debug = True
auth = '' |
def digit_powers():
res = []
for i in range(1, 10):
j = 0
while True:
j += 1
num = i ** j
num_digits = len(str(num))
if num_digits != j:
break
res += [num]
return res | def digit_powers():
res = []
for i in range(1, 10):
j = 0
while True:
j += 1
num = i ** j
num_digits = len(str(num))
if num_digits != j:
break
res += [num]
return res |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def preProcess(s):
if not s:
return ['^', '$']
T = ['^']
for c in s:
T += ['#', c]
T += ['#', '$']
... | class Solution(object):
def longest_palindrome(self, s):
"""
:type s: str
:rtype: str
"""
def pre_process(s):
if not s:
return ['^', '$']
t = ['^']
for c in s:
t += ['#', c]
t += ['#', '$']
... |
print((type(None)))
print(type(True))
print(type(5))
print(type(5.5))
print(type('hi'))
print(type([]))
print(type(()))
print(type({})) | print(type(None))
print(type(True))
print(type(5))
print(type(5.5))
print(type('hi'))
print(type([]))
print(type(()))
print(type({})) |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class ProtectionDomain(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the... | class Protectiondomain(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {'c... |
a=1
b=2
print('a=',a,'b=',b)
x=3
y=3
z=3
print(x,y,z) | a = 1
b = 2
print('a=', a, 'b=', b)
x = 3
y = 3
z = 3
print(x, y, z) |
res = 0
n = 0
print("S= ", end="")
for n2 in range(1, 51):
if n2 == 1:
n += 1
print(f"{n}/{n}", end="")
else:
n += 2
res += (n / n2)
print(f" + {n}/{n2}", end="")
print(f"\nResultado = {res}")
| res = 0
n = 0
print('S= ', end='')
for n2 in range(1, 51):
if n2 == 1:
n += 1
print(f'{n}/{n}', end='')
else:
n += 2
res += n / n2
print(f' + {n}/{n2}', end='')
print(f'\nResultado = {res}') |
"""A single Node in the graph of the art."""
class ArtNode:
def __init__(self, x: int, y: int, thickness: int) -> None:
self.x = x
self.y = y
self.thickness: int = thickness
def xy(self, factor: int = 1):
"""
Gets the xy position of this node, but also allow for
... | """A single Node in the graph of the art."""
class Artnode:
def __init__(self, x: int, y: int, thickness: int) -> None:
self.x = x
self.y = y
self.thickness: int = thickness
def xy(self, factor: int=1):
"""
Gets the xy position of this node, but also allow for
... |
"""
By starting at the top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03... | """
By starting at the top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03... |
"""
PyNullWeb - a web server that returns minimal content.
:copyright: (c) 2017 by Detlef Kreuz
:license: Apache 2.0, see LICENSE
"""
| """
PyNullWeb - a web server that returns minimal content.
:copyright: (c) 2017 by Detlef Kreuz
:license: Apache 2.0, see LICENSE
""" |
def alphabeta(node, is_max=True, alpha=float('-inf'), beta=float('inf')):
if node and not node.children:
return (node.val, [node])
elif is_max:
# Can always fall back on alpha. This is the lower bound score
for child in node.children:
score, path = minimax(child, False, alpha... | def alphabeta(node, is_max=True, alpha=float('-inf'), beta=float('inf')):
if node and (not node.children):
return (node.val, [node])
elif is_max:
for child in node.children:
(score, path) = minimax(child, False, alpha, beta)
if score > beta:
return (score,... |
# -*- coding: utf-8 -*-
class ErrorResponse(Exception):
def __init__(self, error=None, errorcode=None, errormessage=None,
errordetails=None):
self.error = error
self.errorcode = errorcode
self.errormessage = errormessage
self.errordetails = errordetails
def _... | class Errorresponse(Exception):
def __init__(self, error=None, errorcode=None, errormessage=None, errordetails=None):
self.error = error
self.errorcode = errorcode
self.errormessage = errormessage
self.errordetails = errordetails
def __str__(self):
return repr(self)
... |
#!/usr/bin/env python3
"""
This module contains forms used by the app.
"""
| """
This module contains forms used by the app.
""" |
def primes(n):
for i, prime in enumerate(prime_generator()):
if i == n:
return prime
def prime_generator():
n = 2
primes = set()
while True:
for p in primes:
if n % p == 0:
break
else:
primes.add(n)
yield n
... | def primes(n):
for (i, prime) in enumerate(prime_generator()):
if i == n:
return prime
def prime_generator():
n = 2
primes = set()
while True:
for p in primes:
if n % p == 0:
break
else:
primes.add(n)
yield n
... |
#-*-coding=utf-8-*-
class Node(object):
def __init__(self, elem=-1,lchild=None, rchild=None):
self.elem=elem
self.lchild=lchild
self.rchild=rchild
class Tree(object):
def __init__(self):
self.root=Node()
self.nodequeue=[]
def addnode(self, elem):
node =Node(e... | class Node(object):
def __init__(self, elem=-1, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class Tree(object):
def __init__(self):
self.root = node()
self.nodequeue = []
def addnode(self, elem):
node = node(elem)
... |
def f(n:Int)->Int:
return (n * (n+1)) // 2
def get_numbers(how_many:Int)->List(Int):
nums = []
for i in range(1, 1 + how_many):
nums.append(f)
return nums
print(get_numbers(4))
def apply_first(funs, n):
return funs[0](n)
print(apply_first(get_numbers(4), 10))
| def f(n: Int) -> Int:
return n * (n + 1) // 2
def get_numbers(how_many: Int) -> list(Int):
nums = []
for i in range(1, 1 + how_many):
nums.append(f)
return nums
print(get_numbers(4))
def apply_first(funs, n):
return funs[0](n)
print(apply_first(get_numbers(4), 10)) |
'''
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
'''
class Solution:
def isValid(self, s: str) -> ... | """
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
"""
class Solution:
def is_valid(self, s: str) -... |
"""
Codemonk link: https://www.hackerearth.com/problem/algorithm/monk-and-palindromes-52299611/
Monk loves maths and is always curious to learn new things. Recently, he learned about palindromes. Now, he decided to
give his students a problem which uses maths and the concept of palindromes. So, he wants the students t... | """
Codemonk link: https://www.hackerearth.com/problem/algorithm/monk-and-palindromes-52299611/
Monk loves maths and is always curious to learn new things. Recently, he learned about palindromes. Now, he decided to
give his students a problem which uses maths and the concept of palindromes. So, he wants the students t... |
def contador(* num): # O asterisco no contador significa que pode receber diversos valores e vai colocar dentro de uma tupla
for valor in num:
print(f' {valor} ', end='')
print(f'Recebi os valores {num} e sao ao todo {len(num)}')
print('Fim')
contador(2, 1, 7)
contador(4, 0, 4, 6, 9, 8)
def so... | def contador(*num):
for valor in num:
print(f' {valor} ', end='')
print(f'Recebi os valores {num} e sao ao todo {len(num)}')
print('Fim')
contador(2, 1, 7)
contador(4, 0, 4, 6, 9, 8)
def soma(*valores):
s = 0
for n in valores:
s += n
print(f'somando os valores{valores} tems {s}'... |
# -*- coding: utf-8 -*-
"""Main module."""
def ascii_deco(vector):
cadena = vector.split(',')
suma = " "
for i in range(len(cadena)):
ascci = int(cadena[i])
caracter = chr(ascci)
suma = suma + caracter
print (suma)
| """Main module."""
def ascii_deco(vector):
cadena = vector.split(',')
suma = ' '
for i in range(len(cadena)):
ascci = int(cadena[i])
caracter = chr(ascci)
suma = suma + caracter
print(suma) |
#
# This file contains the Python code from Program 11.22 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/pgm11_22.txt
#
class Simulation(... | class Simulation(object):
arrival = 0
departure = 1
def __init__(self):
super(Simulation, self).__init__()
self._eventList = leftist_heap()
self._serverBusy = False
self._numberInQueue = 0
self._serviceTime = exponential_rv(100.0)
self._interArrivalTime = exp... |
NETWORKS = {
3: {
"name": "test",
"http_provider": "https://ropsten.infura.io",
"ws_provider": "wss://ropsten.infura.io/ws",
"db": {
"DB_DRIVER": "mysql+pymysql",
"DB_HOST": "localhost",
"DB_USER": "unittest_root",
"DB_PASSWORD": "unitt... | networks = {3: {'name': 'test', 'http_provider': 'https://ropsten.infura.io', 'ws_provider': 'wss://ropsten.infura.io/ws', 'db': {'DB_DRIVER': 'mysql+pymysql', 'DB_HOST': 'localhost', 'DB_USER': 'unittest_root', 'DB_PASSWORD': 'unittest_pwd', 'DB_NAME': 'verification_unittest_db', 'DB_PORT': 3306}}}
network_id = 3
slac... |
# Declares an initial list with 5 values
List1 = [1,2,3,4,5]
# Unpacks this list into 5 separate variables
a,b,c,d,e = List1
# Prints both the list and one of the unpacking variables
print(List1)
print(a)
# Changes the value of a to 6
a = 6
# Prints both the list and a, and we can see that changing a d... | list1 = [1, 2, 3, 4, 5]
(a, b, c, d, e) = List1
print(List1)
print(a)
a = 6
print(a)
print(List1)
List1[1] = 9
print(List1)
print(b) |
def sum_of_multiples(limit, multiples):
multiples_set = set()
for multiple in multiples:
if multiple != 0:
quotient, rest = divmod(limit, multiple)
if rest == 0:
quotient -=1
multiples_set = multiples_set.union(set(multiple * i for i in range(1,quotie... | def sum_of_multiples(limit, multiples):
multiples_set = set()
for multiple in multiples:
if multiple != 0:
(quotient, rest) = divmod(limit, multiple)
if rest == 0:
quotient -= 1
multiples_set = multiples_set.union(set((multiple * i for i in range(1, qu... |
# Size of the window
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
# Default friction used for sprites, unless otherwise specified
DEFAULT_FRICTION = 0.2
# Default mass used for sprites
DEFAULT_MASS = 1
# Gravity
GRAVITY = (0.0, -900.0)
# Player forces
PLAYER_MOVE_FORCE = 700
PLAYER_JUMP_IMPULSE = 600
PLAYER_PUNCH_IMPULS... | screen_width = 1200
screen_height = 800
default_friction = 0.2
default_mass = 1
gravity = (0.0, -900.0)
player_move_force = 700
player_jump_impulse = 600
player_punch_impulse = 600
sprite_size = 64
viewport_margin = 100 |
class Solution:
"""
Time Complexity: O(N)
Space Complexity: O(1)
"""
def balanced_string_split(self, s: str) -> int:
# initialize variables
L_count, R_count = 0, 0
balanced_substring_count = 0
# parse the string
for char in s:
# update the numbe... | class Solution:
"""
Time Complexity: O(N)
Space Complexity: O(1)
"""
def balanced_string_split(self, s: str) -> int:
(l_count, r_count) = (0, 0)
balanced_substring_count = 0
for char in s:
if char == 'L':
l_count += 1
elif char == 'R':... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 BigML
#
# 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 ... | """Options for BigMLer deepnet
"""
def get_deepnet_options(defaults=None):
"""Adding arguments for the deepnet subcommand
"""
if defaults is None:
defaults = {}
options = {'--deepnet-fields': {'action': 'store', 'dest': 'deepnet_fields', 'default': defaults.get('deepnet_fields', None), 'help'... |
"""
Introduction
============
The ``ox_profile`` package provides a python framework for statistical
profiling. If you are using ``Flask``, then ``ox_profile`` provides a
flask blueprint so that you can start/stop/analyze profiling from within
your application. You can also run the profiler stand-alone without
``Flask... | """
Introduction
============
The ``ox_profile`` package provides a python framework for statistical
profiling. If you are using ``Flask``, then ``ox_profile`` provides a
flask blueprint so that you can start/stop/analyze profiling from within
your application. You can also run the profiler stand-alone without
``Flask... |
def opcodeI() -> int:
with open("/home/thelichking/Desktop/adventOfCode/Day2/Opcodes",'r' ) as file:
lines = list(map(int,file.readline().replace("\n","").split(",")))
lines[1],lines[2] = 1,0
idx = 0
while idx < len(lines):
cur_opcode = lines[idx]
if cur_op... | def opcode_i() -> int:
with open('/home/thelichking/Desktop/adventOfCode/Day2/Opcodes', 'r') as file:
lines = list(map(int, file.readline().replace('\n', '').split(',')))
(lines[1], lines[2]) = (1, 0)
idx = 0
while idx < len(lines):
cur_opcode = lines[idx]
if ... |
class Solution:
def findLUSlength(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
"""
if a == b:
return -1
return max(len(a), len(b))
| class Solution:
def find_lu_slength(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
"""
if a == b:
return -1
return max(len(a), len(b)) |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inOrder(self, root, bstArr):
if not root:
return
if root.left:
self.inOrder(r... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def in_order(self, root, bstArr):
if not root:
return
if root.left:
self.inOrder(root.left, bstArr)
bstArr.append(root... |
# Advent Of Code 2016, day 3, part 2
# http://adventofcode.com/2016/day/3
# solution by ByteCommander, 2016-12-03
data = open("inputs/aoc2016_3.txt").read()
# parse input to vertical groups of 3 numbers
rows = [[int(x) for x in line.split()] for line in data.splitlines()]
vertically = [item for inner in zip(*rows) fo... | data = open('inputs/aoc2016_3.txt').read()
rows = [[int(x) for x in line.split()] for line in data.splitlines()]
vertically = [item for inner in zip(*rows) for item in inner]
v3 = [vertically[i:i + 3] for i in range(0, len(vertically), 3)]
counter = 0
for (a, b, c) in v3:
if a + b > c and a + c > b and (b + c > a):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.