content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def insertSort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = i-1
while j >=0 and val < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = val
arr = [67, 12, 1, 6, 9]
insertSort(arr)
print(arr) | def insert_sort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = i - 1
while j >= 0 and val < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = val
arr = [67, 12, 1, 6, 9]
insert_sort(arr)
print(arr) |
# this files contains basic metadata about the project. This data will be used
# (by default) in the base.html and index.html
PROJECT_METADATA = {
'title': 'Thunau',
'author': 'Peter Andorfer',
'subtitle': 'An Exavation Docu',
'description': 'A web application to manage and publish data gathered around... | project_metadata = {'title': 'Thunau', 'author': 'Peter Andorfer', 'subtitle': 'An Exavation Docu', 'description': 'A web application to manage and publish data gathered around the excavations in Thunau', 'github': 'https://github.com/acdh-oeaw/thunau', 'purpose_de': 'Ziel ist die Publikation von Forschungsdaten', 'pur... |
def last_sqrt(x):
n = 1
sqr = 0
while x>=sqr:
sqr = sqr + ((2*n)-1)
n+=1
return n-2
list = []
n = int(input("Enter the Number:"))
for num in range(2,(n+1)):
list.append(num)
for ltsqrt in range(0,(last_sqrt(n)-1)):
if list[ltsqrt]!=0:
for nums in range((lts... | def last_sqrt(x):
n = 1
sqr = 0
while x >= sqr:
sqr = sqr + (2 * n - 1)
n += 1
return n - 2
list = []
n = int(input('Enter the Number:'))
for num in range(2, n + 1):
list.append(num)
for ltsqrt in range(0, last_sqrt(n) - 1):
if list[ltsqrt] != 0:
for nums in range(ltsqrt ... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftPLUSMINUSleftTIMESDIVIDErightUMINUSDIVIDE EQUALS LPAREN MINUS NAME NUMBER PLUS RPAREN TIMESstatement : expressionexpression : expression PLUS expression\n ... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftPLUSMINUSleftTIMESDIVIDErightUMINUSDIVIDE EQUALS LPAREN MINUS NAME NUMBER PLUS RPAREN TIMESstatement : expressionexpression : expression PLUS expression\n | expression MINUS expression\n | expression TIMES expression\n ... |
## Aim :
## You are given two strings, A and B.
## Find if there is a substring that appears in both A and B.
# Input:
# The first line of the input will contain a single integer , tthe number of test cases.
# Then there will be t descriptions of the test cases. Each description contains two lines.
# The first line ... | n = int(input().strip())
a = []
for a_i in range(2 * n):
a_t = [a_temp for a_temp in input().strip().split(' ')][0]
a.append(a_t)
for i in range(2 * n):
if i % 2 == 0:
s1 = set(a[i])
s2 = set(a[i + 1])
s = s1.intersection(s2)
if len(S) == 0:
print('NO')
el... |
'''
* @File: main.py
* @Author: CSY
* @Date: 2019/7/27 - 9:40
'''
| """
* @File: main.py
* @Author: CSY
* @Date: 2019/7/27 - 9:40
""" |
class LoopDetected(Exception):
"""
A loop has been detected while tracing a cable path.
"""
pass
class CableTraceSplit(Exception):
"""
A cable trace cannot be completed because a RearPort maps to multiple FrontPorts and
we don't know which one to follow.
"""
def __init__(self, term... | class Loopdetected(Exception):
"""
A loop has been detected while tracing a cable path.
"""
pass
class Cabletracesplit(Exception):
"""
A cable trace cannot be completed because a RearPort maps to multiple FrontPorts and
we don't know which one to follow.
"""
def __init__(self, term... |
def show_free(cal_name, d, m, t1, t2):
"String x Integer x String x String x String ->"
day = new_day(d)
mon = new_month(m)
start = convert_time(t1)
end = convert_time(t2)
cal_day = calendar_day(day, calendar_month(mon, fetch_calendar(cal_name)))
show_time_spans(free_spans(cal_day, start, ... | def show_free(cal_name, d, m, t1, t2):
"""String x Integer x String x String x String ->"""
day = new_day(d)
mon = new_month(m)
start = convert_time(t1)
end = convert_time(t2)
cal_day = calendar_day(day, calendar_month(mon, fetch_calendar(cal_name)))
show_time_spans(free_spans(cal_day, start... |
def list_comprehension():
matrix = [
[1 if row == 2 or column == 2 else 0 for column in range(5)] for row in range(5)
]
print(matrix)
# von Jonas(JoBo12) aus dem Discord
def with_for():
matrix_1 = []
for item in range(5):
matrix_1.append([])
for item2 in range(5):
... | def list_comprehension():
matrix = [[1 if row == 2 or column == 2 else 0 for column in range(5)] for row in range(5)]
print(matrix)
def with_for():
matrix_1 = []
for item in range(5):
matrix_1.append([])
for item2 in range(5):
matrix_1[item].append(int(item == 2 or item2 == ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Zeyuan Shang
# @Date: 2015-11-19 21:10:01
# @Last Modified by: Zeyuan Shang
# @Last Modified time: 2015-11-19 21:10:09
class NumMatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List... | class Nummatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
if not matrix:
return
(n, m) = (len(matrix), len(matrix[0]))
self.sums = [[0] * (m + 1)]
for i in xrange(1, n +... |
# dataset settings
data_source_cfg = dict(type='CIFAR10', root='data/cifar10/')
dataset_type = 'ExtractDataset'
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_pipeline = [
dict(
type='RandomResizedCrop', size=224, scale=(0.2, 1.0), interpolation=3),
dict(type='RandomHo... | data_source_cfg = dict(type='CIFAR10', root='data/cifar10/')
dataset_type = 'ExtractDataset'
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_pipeline = [dict(type='RandomResizedCrop', size=224, scale=(0.2, 1.0), interpolation=3), dict(type='RandomHorizontalFlip')]
prefetch = True
if not... |
"""
Sandbox for MicroPyDatabase
A low-memory json-based databse for MicroPython.
Data is stored in a folder structure in json for easy inspection.
This file contains sample usage.
"""
#Database examples:
db_object = Database.create("mydb2")
db_object = Database.open("mydb")
#Table examples:
db_table = db_object.create... | """
Sandbox for MicroPyDatabase
A low-memory json-based databse for MicroPython.
Data is stored in a folder structure in json for easy inspection.
This file contains sample usage.
"""
db_object = Database.create('mydb2')
db_object = Database.open('mydb')
db_table = db_object.create_table('mytable', ['name', 'password']... |
travel_mode = {"1": "car", "2": "plane"}
items = {
"can opener",
"fuel",
"jumper",
"knife",
"matches",
"razor blades",
"razor",
"scissors",
"shampoo",
"shaving cream",
"shirts (3)",
"shorts",
"sleeping bag(s)",
"soap",
"socks (3 pairs)",
"stove",
"ten... | travel_mode = {'1': 'car', '2': 'plane'}
items = {'can opener', 'fuel', 'jumper', 'knife', 'matches', 'razor blades', 'razor', 'scissors', 'shampoo', 'shaving cream', 'shirts (3)', 'shorts', 'sleeping bag(s)', 'soap', 'socks (3 pairs)', 'stove', 'tent', 'mug', 'toothbrush', 'toothpaste', 'towel', 'underwear (3 pairs)',... |
class Solution:
def removeOuterParentheses(self, S: str) -> str:
primitiveEndIndices = set([0])
count = 0
for i, char in enumerate(S):
if char == '(':
count += 1
elif char == ')':
count -= 1
if count == 0:
pr... | class Solution:
def remove_outer_parentheses(self, S: str) -> str:
primitive_end_indices = set([0])
count = 0
for (i, char) in enumerate(S):
if char == '(':
count += 1
elif char == ')':
count -= 1
if count == 0:
... |
person = {
"name": "Bernardo",
"age": 21
}
print(person)
print(person.items())
print(person["name"])
person["wright"] = "78kg"
print(person) | person = {'name': 'Bernardo', 'age': 21}
print(person)
print(person.items())
print(person['name'])
person['wright'] = '78kg'
print(person) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
BASE_CF_TEMPLATE = '''
AWSTemplateFormatVersion: 2010-09-09
Description: AWS CloudFormation template
Parameters:
EcsAmiId:
Type: String
Description: ECS AMI Id
EcsInstanceType:
Type: String
Description: ECS EC2 instance type
Default: t2.micro
C... | base_cf_template = "\nAWSTemplateFormatVersion: 2010-09-09\nDescription: AWS CloudFormation template\nParameters:\n EcsAmiId:\n Type: String\n Description: ECS AMI Id\n EcsInstanceType:\n Type: String\n Description: ECS EC2 instance type\n Default: t2.micro\n ConstraintDescription: must be a valid E... |
STABLECOIN_SYMBOLS = ['USDC', 'DAI', 'USDT', 'BUSD', 'TUSD', 'PAX', 'VAI']
FREE_RPC_ENDPOINTS = ['https://api.mycryptoapi.com/eth',
'https://nodes.mewapi.io/rpc/eth',
'https://mainnet-nethermind.blockscout.com/',
'https://mainnet.eth.cloud.ava.do/',
... | stablecoin_symbols = ['USDC', 'DAI', 'USDT', 'BUSD', 'TUSD', 'PAX', 'VAI']
free_rpc_endpoints = ['https://api.mycryptoapi.com/eth', 'https://nodes.mewapi.io/rpc/eth', 'https://mainnet-nethermind.blockscout.com/', 'https://mainnet.eth.cloud.ava.do/', 'https://cloudflare-eth.com/']
chainlink_addresses = {'1INCH-ETH': '0x... |
# -*- coding: utf-8 -*-
class SyncCommand(object):
"""
Helper class to call core sync
"""
def __init__(self, core):
self.core = core
def do(self):
"""
Do core sync
"""
self.core.sync()
| class Synccommand(object):
"""
Helper class to call core sync
"""
def __init__(self, core):
self.core = core
def do(self):
"""
Do core sync
"""
self.core.sync() |
# based on nuts_and_bolts.scad from MCAD library
# https:# github.com/elmom/MCAD/
# Copyright 2010 D1plo1d
# This library is dual licensed under the GPL 3.0 and the GNU Lesser General Public License as per http:# creativecommons.org/licenses/LGPL/2.1/ .
MM = "mm"
INCH = "inch" # Not yet supported
# Based on: htt... | mm = 'mm'
inch = 'inch'
metric_nut_ac_widths = [-1, -1, -1, 6.4, 8.1, 9.2, 11.5, -1, 15.0, -1, 19.6, -1, 22.1, -1, -1, -1, 27.7, -1, -1, -1, 34.6, -1, -1, -1, 41.6, -1, -1, -1, -1, -1, 53.1, -1, -1, -1, -1, -1, 63.5]
metric_nut_thickness = [-1, -1, -1, 2.4, 3.2, 4.0, 5.0, -1, 6.5, -1, 8.0, -1, 10.0, -1, -1, -1, 13.0, -... |
var = 77
def func():
global var
var = 100
print(locals())
func()
print(var)
| var = 77
def func():
global var
var = 100
print(locals())
func()
print(var) |
def solution(xs):
mn = -1000
count = 0
product = 0
for element in xs:
if element != 0:
if product != 0:
product = product * element
else:
product = element
count += 1
if element < 0 and element > mn:
... | def solution(xs):
mn = -1000
count = 0
product = 0
for element in xs:
if element != 0:
if product != 0:
product = product * element
else:
product = element
count += 1
if element < 0 and element > mn:
... |
first_num = 2
secord_num = 3
sum = first_num + secord_num
print(sum)
| first_num = 2
secord_num = 3
sum = first_num + secord_num
print(sum) |
#
# PySNMP MIB module NOKIA-NTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOKIA-NTP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:13:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ... |
"""
.. module:: errors
:platform: Unix, Windows
:synopsis: Global error classes for gNMIP-API
.. moduleauthor:: Greg Brown <gsb5067@gmail.com>
"""
class GNMIException(Exception):
""" Exception for GNMI API Errors """
pass
class ElasticSearchUploaderException(Exception):
""" Exception for Elast... | """
.. module:: errors
:platform: Unix, Windows
:synopsis: Global error classes for gNMIP-API
.. moduleauthor:: Greg Brown <gsb5067@gmail.com>
"""
class Gnmiexception(Exception):
""" Exception for GNMI API Errors """
pass
class Elasticsearchuploaderexception(Exception):
""" Exception for ElasticS... |
#!/usr/bin/python
#300 most common words according to google
#Source: https://github.com/first20hours/google-10000-english
#Some words that might refer to scientific information have been removed
boringWords=set(['the','of','and','to','a','in','for','is','on','that','by','this','with','i','you','it','not','or','be','a... | boring_words = set(['the', 'of', 'and', 'to', 'a', 'in', 'for', 'is', 'on', 'that', 'by', 'this', 'with', 'i', 'you', 'it', 'not', 'or', 'be', 'are', 'from', 'at', 'as', 'your', 'all', 'have', 'new', 'more', 'an', 'was', 'we', 'will', 'home', 'can', 'us', 'about', 'if', 'page', 'my', 'has', 'search', 'free', 'but', 'ou... |
{
'targets': [
{
'target_name': 'publish',
'type':'none',
'dependencies': [
'appjs'
],
'copies':[
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs/',
'files': [
'<(module_root_dir)/README.md',
'<(module_root_... | {'targets': [{'target_name': 'publish', 'type': 'none', 'dependencies': ['appjs'], 'copies': [{'destination': '<(module_root_dir)/app/data/node_modules/appjs/', 'files': ['<(module_root_dir)/README.md', '<(module_root_dir)/package.json', '<(module_root_dir)/lib/']}, {'destination': '<(module_root_dir)/app/data/node_mod... |
n, m = map(int, input().split())
ruins = [list(map(int, input().split())) for _ in range(n)]
imos = [0] * (m+1)
sum_s = 0
for i in range(n):
l, r, s = ruins[i]
l -= 1
imos[l] += s
imos[r] -= s
sum_s += s
for i in range(m):
imos[i+1] += imos[i]
print(sum_s - min(imos[:-1]))
| (n, m) = map(int, input().split())
ruins = [list(map(int, input().split())) for _ in range(n)]
imos = [0] * (m + 1)
sum_s = 0
for i in range(n):
(l, r, s) = ruins[i]
l -= 1
imos[l] += s
imos[r] -= s
sum_s += s
for i in range(m):
imos[i + 1] += imos[i]
print(sum_s - min(imos[:-1])) |
input = """
i(0). i(1).
a(X) | -a(X) :- i(X).
ok :- 0 < #count{X:a(X)}< 2.
:- not ok.
"""
output = """
i(0). i(1).
a(X) | -a(X) :- i(X).
ok :- 0 < #count{X:a(X)}< 2.
:- not ok.
"""
| input = '\ni(0). i(1).\na(X) | -a(X) :- i(X).\nok :- 0 < #count{X:a(X)}< 2.\n:- not ok.\n'
output = '\ni(0). i(1).\na(X) | -a(X) :- i(X).\nok :- 0 < #count{X:a(X)}< 2.\n:- not ok.\n' |
def check(s, t):
v = 0
for i in range(len(t)):
if t[i] == s[v]:
v += 1
if v == len(s):
return "Yes"
return "No"
while True:
try:
s, t = input().split()
ans = check(s, t)
print(ans)
except:
break
| def check(s, t):
v = 0
for i in range(len(t)):
if t[i] == s[v]:
v += 1
if v == len(s):
return 'Yes'
return 'No'
while True:
try:
(s, t) = input().split()
ans = check(s, t)
print(ans)
except:
break |
class _descriptor(object):
def __get__(self, *_):
raise RuntimeError("more like funtime error")
class Methods(object):
ok_method = "ok"
err_method = _descriptor()
| class _Descriptor(object):
def __get__(self, *_):
raise runtime_error('more like funtime error')
class Methods(object):
ok_method = 'ok'
err_method = _descriptor() |
'''
+Build Your Dream Python Project Discord Team
Invite: https://dsc.gg/python_team
19 Feb 2021
@alexandros answer to @Subham
https://discord.com/channels/794684213697052712/794684213697052718/812231193213796362
Sublist Yielder
'''
lst = [[1, 3, 4], [2, 5, 7]]
def f(lst):
for sublst in lst:
yield from s... | """
+Build Your Dream Python Project Discord Team
Invite: https://dsc.gg/python_team
19 Feb 2021
@alexandros answer to @Subham
https://discord.com/channels/794684213697052712/794684213697052718/812231193213796362
Sublist Yielder
"""
lst = [[1, 3, 4], [2, 5, 7]]
def f(lst):
for sublst in lst:
yield from sub... |
#----------* CHALLENGE 35 *----------
#Ask the user to enter their name and then display their name three times.
name = input("Enter your name: ")
for i in range (1,4):
print(name+" ") | name = input('Enter your name: ')
for i in range(1, 4):
print(name + ' ') |
edibles = ["ham", "spam","eggs","nuts"]
for food in edibles:
if food == "spams":
print("No more spam please!")
break
print("Great, delicious " + food)
else:
print("I am so glad: No " + food +"!")
print("Finally, I finished stuffing myself") | edibles = ['ham', 'spam', 'eggs', 'nuts']
for food in edibles:
if food == 'spams':
print('No more spam please!')
break
print('Great, delicious ' + food)
else:
print('I am so glad: No ' + food + '!')
print('Finally, I finished stuffing myself') |
domain = 'mycompany.local'
user = 'automation@vsphere.local'
pwd = 'somepassword'
| domain = 'mycompany.local'
user = 'automation@vsphere.local'
pwd = 'somepassword' |
game = "Hello world"
#print(id(game))
def game_board(player=0, row=0, col=0, just_display=False):
game = "Change !"
#print(id(game))
print(game)
print(game)
game_board()
print(game)
#print(id(game))
| game = 'Hello world'
def game_board(player=0, row=0, col=0, just_display=False):
game = 'Change !'
print(game)
print(game)
game_board()
print(game) |
def groupnames(name_iterable):
name_dict = {}
for name in name_iterable:
key = _groupkeyfunc(name)
name_dict.setdefault(key, []).append(name)
for k, v in name_dict.iteritems():
aux = [(_sortkeyfunc(name), name) for name in v]
aux.sort()
name_dict[k] = tuple([ n for __... | def groupnames(name_iterable):
name_dict = {}
for name in name_iterable:
key = _groupkeyfunc(name)
name_dict.setdefault(key, []).append(name)
for (k, v) in name_dict.iteritems():
aux = [(_sortkeyfunc(name), name) for name in v]
aux.sort()
name_dict[k] = tuple([n for (... |
class reverse_iter:
def __init__(self, iterable) -> None:
self.iterable = iterable
self.start = len(iterable)
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start > 0:
self.start -= 1
return self.iterable[self.sta... | class Reverse_Iter:
def __init__(self, iterable) -> None:
self.iterable = iterable
self.start = len(iterable)
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start > 0:
self.start -= 1
return self.iterable[self.start]
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insertAtLast(self, data):
node = Node(data)
if self.head == None:
self.head = node
return
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insert_at_last(self, data):
node = node(data)
if self.head == None:
self.head = node
return
curr_poin... |
# __init__.py
"""[Module pys.conf]
Parse .ini configuration of cmd -> build and cmd -> expand
"""
__all__ = ['mconf', 'mgroup']
| """[Module pys.conf]
Parse .ini configuration of cmd -> build and cmd -> expand
"""
__all__ = ['mconf', 'mgroup'] |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.incr = 0
def convertBST(self, root: TreeNode) -> TreeNode:
def dfs(node):
if not node:
... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.incr = 0
def convert_bst(self, root: TreeNode) -> TreeNode:
def dfs(node):
if not node:
return 0
... |
#import necessary data
df = pd.read_csv('~/lstm_test/input/nu_public_rep.csv', sep=';',
parse_dates={'dt' : ['Date', 'Time']}, infer_datetime_format=True,
low_memory=False, na_values=['nan','?'], index_col='dt')
#fill nan with the means of the columns to handle missing databases
dropi... | df = pd.read_csv('~/lstm_test/input/nu_public_rep.csv', sep=';', parse_dates={'dt': ['Date', 'Time']}, infer_datetime_format=True, low_memory=False, na_values=['nan', '?'], index_col='dt')
droping_list_all = []
for j in range(0, 7):
if not df.iloc[:, j].notnull().all():
droping_list_all.append(j)
droping_li... |
#!/usr/bin/env python
# coding: utf8
def writeResults(links, outfile):
fw = open(outfile, "w")
for link in links:
fw.write(link)
| def write_results(links, outfile):
fw = open(outfile, 'w')
for link in links:
fw.write(link) |
i = get_safe('id')
username = ""
if i != 0:
username = get('username')
username = escape_string(username)
query = 'some query'
it = execute(query + username)
| i = get_safe('id')
username = ''
if i != 0:
username = get('username')
username = escape_string(username)
query = 'some query'
it = execute(query + username) |
'''
file:except.py
exceptions for piclock
'''
class NoConfigError(Exception):
'''
No Config Error Exception
'''
class CharacterNotFound(Exception):
'''
Character not found exception
'''
class MatrixCharError(Exception):
'''
Matrix Character Error
'''
class NoMqttConfigSection... | """
file:except.py
exceptions for piclock
"""
class Noconfigerror(Exception):
"""
No Config Error Exception
"""
class Characternotfound(Exception):
"""
Character not found exception
"""
class Matrixcharerror(Exception):
"""
Matrix Character Error
"""
class Nomqttconfigsection(Exc... |
# Objectives
#
# In this stage, you should write a program that:
#
# Reads matrix A A A from the input.
# Reads matrix B B B from the input.
# Outputs their sum if it is possible to add them. Otherwise, it should output the ERROR message.
#
# Each matrix in the input is given in the following way: the first... | def same_dimensions(n_rows_a, n_columns_a, n_rows_b, n_columns_b):
return n_rows_a == n_rows_b and n_columns_a == n_columns_b
def addition(mat_a, mat_b, n_rows, n_columns):
return [[str(mat_a[i][j] + mat_b[i][j]) for j in range(n_columns)] for i in range(n_rows)]
def print_matrix(mat):
for row in mat:
... |
"""Zorro's dependency injection framework
Usage
=====
Declare a class' dependencies::
@has_dependencies
class Hello(object):
world = dependency(World, 'universe')
You must decorate class with ``@has_dependencies``. All dependencies has a
type(class), which is ``World`` in this case, and a name, whi... | """Zorro's dependency injection framework
Usage
=====
Declare a class' dependencies::
@has_dependencies
class Hello(object):
world = dependency(World, 'universe')
You must decorate class with ``@has_dependencies``. All dependencies has a
type(class), which is ``World`` in this case, and a name, whi... |
rows = 9
for i in range(rows):
# nested loop
for j in range(i):
# display number
print(i, end=' ')
# new line after each row
print('')
| rows = 9
for i in range(rows):
for j in range(i):
print(i, end=' ')
print('') |
"""
_
__ _ ___ ___ __ _| | ___
/ _` |/ _ \ / _ \ / _` | |/ _ \
| (_| | (_) | (_) | (_| | | __/
\__, |\___/ \___/ \__, |_|\___|
|___/ |___/
Author: Aaditya Chapagain
version: 1.0.1
description: scripts which will make google API's easy in python.
""" | """
_
__ _ ___ ___ __ _| | ___
/ _` |/ _ \\ / _ \\ / _` | |/ _ | (_| | (_) | (_) | (_| | | __/
\\__, |\\___/ \\___/ \\__, |_|\\___|
|___/ |___/
Author: Aaditya Chapagain
version: 1.0.1
description: scripts which will make google API's easy in python.
""" |
# OpenWeatherMap API Key
weather_api_key = "ea45174aae3e4fc5de1af5d14f74cd81"
# Google API Key
g_key = "AIzaSyCiyVKYg3FYX0fAR2S2RGR1m-kUN947W9s" | weather_api_key = 'ea45174aae3e4fc5de1af5d14f74cd81'
g_key = 'AIzaSyCiyVKYg3FYX0fAR2S2RGR1m-kUN947W9s' |
def editDistance(str1, str2, m, n, ci=1,crm=1,crp=1):
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
... | def edit_distance(str1, str2, m, n, ci=1, crm=1, crp=1):
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif str1[i - 1] == str2[j -... |
"""
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -... | """
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def funcion_generadora_print():
try:
print("GENERADOR: Se va a generar un PRIMER dato")
yield "valorGenerado1"
print("GENERADOR: Se va a generar un SEGUNDO dato")
yield "valorGenerado2"
print("GENERADOR: Se va a generar un TER... | def funcion_generadora_print():
try:
print('GENERADOR: Se va a generar un PRIMER dato')
yield 'valorGenerado1'
print('GENERADOR: Se va a generar un SEGUNDO dato')
yield 'valorGenerado2'
print('GENERADOR: Se va a generar un TERCER dato')
yield 'valorGenerado3'
fina... |
"""Provides classes for connecting to and controlling real and mock Spectrum digitiser cards and StarHubs."""
# Christian Baker, King's College London
# Copyright (c) 2021 School of Biomedical Engineering & Imaging Sciences, King's College London
# Licensed under the MIT. You may obtain a copy at https://opensource.or... | """Provides classes for connecting to and controlling real and mock Spectrum digitiser cards and StarHubs.""" |
file_input="dump.seq_e10.mci.I12"
num=1
output=open('assign_cluster_num.out','w')
for i in open(file_input):
i=i.replace('\n','')
o=i.split()
for j in o:
output.write(j+'\t'+str(num)+'\n')
num+=1
output.close()
| file_input = 'dump.seq_e10.mci.I12'
num = 1
output = open('assign_cluster_num.out', 'w')
for i in open(file_input):
i = i.replace('\n', '')
o = i.split()
for j in o:
output.write(j + '\t' + str(num) + '\n')
num += 1
output.close() |
t=int(input('Tabuada do : '))
r1 = t * 1
r2 = t * 2
r3 = t * 3
r4 = t * 4
r5 = t * 5
r6 = t * 6
r7 = t * 7
r8 = t * 8
r9 = t * 9
r10 = t * 10
print("RESUlTADO\n------------------------")
print('{} x 1 = {}'.format(t,r1))
print('{} x 2 = {}'.format(t,r2))
print('{} x 3 = {}'.format(t,r3))
print('{} x 4 = {}'.format(t,... | t = int(input('Tabuada do : '))
r1 = t * 1
r2 = t * 2
r3 = t * 3
r4 = t * 4
r5 = t * 5
r6 = t * 6
r7 = t * 7
r8 = t * 8
r9 = t * 9
r10 = t * 10
print('RESUlTADO\n------------------------')
print('{} x 1 = {}'.format(t, r1))
print('{} x 2 = {}'.format(t, r2))
print('{} x 3 = {}'.format(t, r3))
print('{} x 4 = {}'.format... |
class Palettes: # pylint: disable=too-few-public-methods
"""Color palettes applied to Map visualizations in the style helper methods.
By default, each color helper method has its own default palette.
More information at https://carto.com/carto-colors/
Example:
Create color bins style with the ... | class Palettes:
"""Color palettes applied to Map visualizations in the style helper methods.
By default, each color helper method has its own default palette.
More information at https://carto.com/carto-colors/
Example:
Create color bins style with the burg palette
>>> color_bins_style... |
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
with plt.xkcd():
fig = plt.figure(figsize=(fig_w, fig_h))
my_plot(x, auditory, visual, posterior_pointwise)
plt.ti... | auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
with plt.xkcd():
fig = plt.figure(figsize=(fig_w, fig_h))
my_plot(x, auditory, visual, posterior_pointwise)
plt.tit... |
def get_google_folder_id(service, folder_name):
"""Get folder id of a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/... | def get_google_folder_id(service, folder_name):
"""Get folder id of a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.co... |
# Tutorial skipper snippet
def skip_tutorial():
MAPLE_ADMINISTARTOR = 2007
quests_to_complete = [
20820, # The City of Ereve
20821, # Knight's Orientation
20822, # The Path of Bravery
20823, # Question and Answer
20824, # Knight's Cavalier
20825, # Well-Behaved Student
20826, # Lesson 1 - Ereve History... | def skip_tutorial():
maple_administartor = 2007
quests_to_complete = [20820, 20821, 20822, 20823, 20824, 20825, 20826, 20827, 20828, 20829, 20830, 20831, 20832, 20833, 20834, 20835, 20836, 20837, 20838, 20839]
map_to_warp = 130000000
target_level = 10
sm.setSpeakerID(MAPLE_ADMINISTARTOR)
sm.remo... |
class ATM:
def __init__(self,balance,bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def show_withdrawals(self):
for withdrawal in self.withdrawals_list:
print("withdrawal: "+str(withdrawal))
def print_information(self):
print("Welcome to "+ self.bank_nam... | class Atm:
def __init__(self, balance, bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def show_withdrawals(self):
for withdrawal in self.withdrawals_list:
print('withdrawal: ' + str(withdrawal))
def print_information(se... |
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# brute force
ar = nums1 + nums2
ar.sort()
n = len(ar)
median = ar[n//2]
if n%2 != 0:
return median
else:
return (median + ... | class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
ar = nums1 + nums2
ar.sort()
n = len(ar)
median = ar[n // 2]
if n % 2 != 0:
return median
else:
return (median + ar[n // 2 - 1]) / 2 |
defines = {}
specials = {}
defines.update(globals()["__builtins__"])
def define(fnc):
defines[fnc.__name__] = fnc
return fnc
def rename(name):
def deco(fnc):
fnc.__name__ = name
return define(fnc)
return deco
def special(fnc):
specials[fnc.__name__] = fnc
return fnc
def ... | defines = {}
specials = {}
defines.update(globals()['__builtins__'])
def define(fnc):
defines[fnc.__name__] = fnc
return fnc
def rename(name):
def deco(fnc):
fnc.__name__ = name
return define(fnc)
return deco
def special(fnc):
specials[fnc.__name__] = fnc
return fnc
def regi... |
def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and array[i] < array[j]:
array[i], array[j] = array[j], array[i]
j -= 1
i -= 1
return array
def test_insertion_sort_simple():
assert insertion_sort([4... | def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and array[i] < array[j]:
(array[i], array[j]) = (array[j], array[i])
j -= 1
i -= 1
return array
def test_insertion_sort_simple():
assert insertion_sort... |
def generatorA(value, stop):
i = 0
while i < stop:
value = (value * 16807) % 2147483647
yield value
i += 1
def generatorB(value, stop):
i = 0
while i < stop:
value = (value * 48271) % 2147483647
yield value
i += 1
def generatorAPart2(value, stop):
i... | def generator_a(value, stop):
i = 0
while i < stop:
value = value * 16807 % 2147483647
yield value
i += 1
def generator_b(value, stop):
i = 0
while i < stop:
value = value * 48271 % 2147483647
yield value
i += 1
def generator_a_part2(value, stop):
i ... |
# https://www.codechef.com/ELE32018/problems/JACKJILL
t=int(input())
for _ in range(t):
n,k,d=[int(x) for x in input().strip().split()]
a=[int(x) for x in input().strip().split()]
b=[int(x) for x in input().strip().split()]
flag=0
res1=0
res2=0
for i in range(k):
res1 += a[i]
res2 += b[i]
if(re... | t = int(input())
for _ in range(t):
(n, k, d) = [int(x) for x in input().strip().split()]
a = [int(x) for x in input().strip().split()]
b = [int(x) for x in input().strip().split()]
flag = 0
res1 = 0
res2 = 0
for i in range(k):
res1 += a[i]
res2 += b[i]
if res1 + res2 >= ... |
# Copyright 2011 Google Inc. All Rights Reserved.
"""Specify the modules for which a Python 2.7 stub exists."""
# pylint: disable=undefined-all-variable
__all__ = [
# These reside here.
'httplib',
'socket',
'subprocess',
'threading',
'urllib',
]
MODULE_OVERRIDES = __all__
| """Specify the modules for which a Python 2.7 stub exists."""
__all__ = ['httplib', 'socket', 'subprocess', 'threading', 'urllib']
module_overrides = __all__ |
class Solution(object):
def isValid(self, S):
"""
:type S: str
:rtype: bool
"""
stack = []
for s in S:
if s == 'c':
valid = [s]
for i in range(2):
if not stack:
return False
... | class Solution(object):
def is_valid(self, S):
"""
:type S: str
:rtype: bool
"""
stack = []
for s in S:
if s == 'c':
valid = [s]
for i in range(2):
if not stack:
return False
... |
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
ans = 0
cnt = 0
for i in range(len(nums)):
if nums[i] == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans
| class Solution(object):
def find_max_consecutive_ones(self, nums):
ans = 0
cnt = 0
for i in range(len(nums)):
if nums[i] == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans |
# Accept one int and one float type value & display average
a = int(input("Enter int no.: "))
b = float(input("Enter float no.: "))
c = (a+b)/2
print(f"Average value {c}")
| a = int(input('Enter int no.: '))
b = float(input('Enter float no.: '))
c = (a + b) / 2
print(f'Average value {c}') |
class Solution:
def minimizeError(self, prices: List[str], target: int) -> str:
# A[i] := (costCeil - costFloor, costCeil, costFloor)
# the lower the costCeil - costFloor, the cheaper to ceil it
A = []
sumFloored = 0
sumCeiled = 0
for price in map(float, prices):
floored = math.floor(pr... | class Solution:
def minimize_error(self, prices: List[str], target: int) -> str:
a = []
sum_floored = 0
sum_ceiled = 0
for price in map(float, prices):
floored = math.floor(price)
ceiled = math.ceil(price)
sum_floored += floored
sum_ce... |
# GENERATED VERSION FILE
# TIME: Mon Oct 11 04:02:23 2021
__version__ = '1.2.0+f83fd55'
short_version = '1.2.0'
version_info = (1, 2, 0)
| __version__ = '1.2.0+f83fd55'
short_version = '1.2.0'
version_info = (1, 2, 0) |
# -*- coding: utf-8 -*-
# goma
# ----
# Generic object mapping algorithm.
#
# Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk]
# Version: 0.2, copyright Wednesday, 18 September 2019
# Website: https://github.com/sonntagsgesicht/goma
# License: Apache License 2.0 (see LICENSE file)
class B... | class Basematch(object):
""" Base match class """
def match(self, *args):
""" return match results """
pass
def _has_relation_operator(self, condition_str):
return str(condition_str)[:1] in ['<', '>', '!', '=', '(', '[']
def _apply_relation_match(self, match_value, detail_valu... |
class InvalidServiceBusMessage(Exception):
"""
Raised when a message is not valid
"""
def __init__(self, reason='InvalidServiceBusMessage', description='The received message is not valid') -> None:
self.reason = reason
self.description = description
super().__init__(self.reason)... | class Invalidservicebusmessage(Exception):
"""
Raised when a message is not valid
"""
def __init__(self, reason='InvalidServiceBusMessage', description='The received message is not valid') -> None:
self.reason = reason
self.description = description
super().__init__(self.reason)... |
"""
class attribute
class method
static method
"""
class Person:
number_of_people = 0
def __init__(self, name) -> None:
self.name = name
Person.number_of_people += 1
Person.add_person()
@classmethod
def add_person(cls):
cls.number_of_people + 1
@classmetho... | """
class attribute
class method
static method
"""
class Person:
number_of_people = 0
def __init__(self, name) -> None:
self.name = name
Person.number_of_people += 1
Person.add_person()
@classmethod
def add_person(cls):
cls.number_of_people + 1
@classmethod
de... |
values = input("Enter comma separated values: ")
list = values.split(",")
tuple = tuple(list)
#this is a forked branch
print("list: {}".format(list))
print("tuple: {}".format(tuple))
| values = input('Enter comma separated values: ')
list = values.split(',')
tuple = tuple(list)
print('list: {}'.format(list))
print('tuple: {}'.format(tuple)) |
def add_replicaset(instance, alias, roles, servers,
status='healthy', all_rw=False, weight=None):
r_uuid = '{}-uuid'.format(alias)
r_servers = []
for s in servers: # servers = ['alias-1', 'alias-2']
r_servers.append({
'alias': s,
'uuid': '{}-uuid'.format(s... | def add_replicaset(instance, alias, roles, servers, status='healthy', all_rw=False, weight=None):
r_uuid = '{}-uuid'.format(alias)
r_servers = []
for s in servers:
r_servers.append({'alias': s, 'uuid': '{}-uuid'.format(s), 'uri': '{}-uri'.format(s), 'status': 'healthy', 'replicaset': {'uuid': r_uuid... |
"""
__version__.py
~~~~~~~~~~~~~~
Information about the current version of the street-situation-detection package.
"""
__title__ = 'street-detection'
__description__ = 'street-detection - A python package for detecting streets'
__version__ = '0.1.0'
__author__ = 'Steven Mi'
__author_email__ = 's0558366@htw-berlin.de'... | """
__version__.py
~~~~~~~~~~~~~~
Information about the current version of the street-situation-detection package.
"""
__title__ = 'street-detection'
__description__ = 'street-detection - A python package for detecting streets'
__version__ = '0.1.0'
__author__ = 'Steven Mi'
__author_email__ = 's0558366@htw-berlin.de'
... |
DEBUG = True
SECRET_KEY = "kasih-tau-gak-ya"
BUNDLE_ERRORS = True
MONGO_HOST = 'mongo'
MONGO_DBNAME = 'news-api'
MONGO_PORT = 27017
JSONIFY_PRETTYPRINT_REGULAR = False | debug = True
secret_key = 'kasih-tau-gak-ya'
bundle_errors = True
mongo_host = 'mongo'
mongo_dbname = 'news-api'
mongo_port = 27017
jsonify_prettyprint_regular = False |
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
'''
T: O(n log n), n = number of words
S: O(n)
'''
for punc in "!?',;.":
paragraph = paragraph.replace(punc, ' ')
words = paragraph.lower().strip().split()
... | class Solution:
def most_common_word(self, paragraph: str, banned: List[str]) -> str:
"""
T: O(n log n), n = number of words
S: O(n)
"""
for punc in "!?',;.":
paragraph = paragraph.replace(punc, ' ')
words = paragraph.lower().strip().split()
banne... |
# configuration file
TRAINING_FILE_ORIGINAL = '../mnist_train.csv'
TRAINING_FILE = '../input/mnist_train_folds.csv'
TESTING_FILE = '../input/mnist_test.csv'
MODEL_OUTPUT = "../models/" | training_file_original = '../mnist_train.csv'
training_file = '../input/mnist_train_folds.csv'
testing_file = '../input/mnist_test.csv'
model_output = '../models/' |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 10:17:27 2019
@author: Administrator
"""
#class Solution:
# def superPow(self, a: int, b: list) -> int:
# B = 0
# b.reverse()
# for k in range(len(b)):
# B += b[k] * 10 ** k
#
# A = a**B#self.pow(a, B)#
#
## ... | """
Created on Fri Jun 21 10:17:27 2019
@author: Administrator
"""
class Solution:
def super_pow(self, a: int, b: list) -> int:
sum = 0
for i in b:
sum = sum * 10 + i
return pow(a, sum, 1337)
solu = solution()
(a, b) = (2, [3])
(a, b) = (2, [1, 0])
(a, b) = (78267, [1, 7, 7, 4... |
# -*- coding: utf-8 -*-
class MunicipalityRecord(object):
"""
The base document class.
Args:
fosnr (int): The unique id bfs of the municipality.
name (unicode): The zipcode for this address.
published (bool): Is this municipality ready for publishing via server.
logo (pyra... | class Municipalityrecord(object):
"""
The base document class.
Args:
fosnr (int): The unique id bfs of the municipality.
name (unicode): The zipcode for this address.
published (bool): Is this municipality ready for publishing via server.
logo (pyramid_oereb.lib.records.imag... |
"""The :func:`deephyper.nas.run.quick.run` function is a function used to check the good behaviour of a neural architecture search algorithm. It will simply return the sum of the scalar values encoding a neural architecture in the ``config["arch_seq"]`` key.
"""
def run(config: dict) -> float:
return sum(config['a... | """The :func:`deephyper.nas.run.quick.run` function is a function used to check the good behaviour of a neural architecture search algorithm. It will simply return the sum of the scalar values encoding a neural architecture in the ``config["arch_seq"]`` key.
"""
def run(config: dict) -> float:
return sum(config['a... |
__all__ = [
"BoundHandler",
"ClassHook",
"Handler",
"Hook",
"Hookable",
"HookableMeta",
"HookDescriptor",
"InstanceHook",
"hookable",
]
| __all__ = ['BoundHandler', 'ClassHook', 'Handler', 'Hook', 'Hookable', 'HookableMeta', 'HookDescriptor', 'InstanceHook', 'hookable'] |
class gen_config(object):
vocab_size = 35000
train_dir = "/home/ssc/project/dataset/dataset/weibo/v0.0/"
data_dir = "/home/ssc/project/dataset/dataset/weibo/v0.0/"
buckets = [(5, 10), (10, 15), (20, 25), (40, 50)] | class Gen_Config(object):
vocab_size = 35000
train_dir = '/home/ssc/project/dataset/dataset/weibo/v0.0/'
data_dir = '/home/ssc/project/dataset/dataset/weibo/v0.0/'
buckets = [(5, 10), (10, 15), (20, 25), (40, 50)] |
"""
Problem
Given two rectangles, determine if they overlap. The rectangles are defined as a Dictionary:
r1 = {
# x and y coordinates of the bottom-left corner of the rectangle
'x': 2, 'y': 4,
# Width and Height of rectangle
'w': 5, 'h': 12
}
If the rectangles do overlap, return the dictionary which de... | """
Problem
Given two rectangles, determine if they overlap. The rectangles are defined as a Dictionary:
r1 = {
# x and y coordinates of the bottom-left corner of the rectangle
'x': 2, 'y': 4,
# Width and Height of rectangle
'w': 5, 'h': 12
}
If the rectangles do overlap, return the dictionary which de... |
#!/usr/bin/env python
# Assumption for the star format:
# contain one or more 'data_*' blocks, for each block,
# either
'''
data_*
loop_
item1 #1
...
itemn #n
item1_data ... itemn_data
...
item1_data ... itemn_data
'''
# or
'''
data_*
item1 item1_data
...
itemn itemn_data
'''
def star_data(star):
# return 2 d... | """
data_*
loop_
item1 #1
...
itemn #n
item1_data ... itemn_data
...
item1_data ... itemn_data
"""
'\n\ndata_*\n\nitem1 item1_data\n...\nitemn itemn_data\n\n'
def star_data(star):
data_dict = {}
with open(star) as read:
for (i, line) in enumerate(read.readlines()):
if line[:5] == 'data_'... |
def get_book_info(book_id, books):
"""Obtain meta data of certain books.
:param book_id: Books to look up
:type: int or list of ints
:param books: Dataframe containing the meta data
:type: pandas dataframe
:return: Meta data for the book ids
:rtype: List[str], List[str], List[str]
"... | def get_book_info(book_id, books):
"""Obtain meta data of certain books.
:param book_id: Books to look up
:type: int or list of ints
:param books: Dataframe containing the meta data
:type: pandas dataframe
:return: Meta data for the book ids
:rtype: List[str], List[str], List[str]
"... |
#
# PySNMP MIB module TRANGOP5830S-RU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRANGOP5830S-RU-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:19:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_range_constraint, constraints_intersection, value_size_constraint) ... |
class CarrinhoCompras:
def __init__(self):
self.produtos = []
def insere_produto(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
def soma_total(self):
total = 0
... | class Carrinhocompras:
def __init__(self):
self.produtos = []
def insere_produto(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
def soma_total(self):
total = 0
... |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '8.3.beta3'
date = '2018-05-27'
| version = '8.3.beta3'
date = '2018-05-27' |
class Judge:
PAPER_LIMIT = 7
def __init__(
self,
judge_id,
first,
last,
email,
phone,
preferred_categories,
is_paper_reviewer,
presentation_availability,
):
self.judge_id = judge_id # int
self.first = first # str
... | class Judge:
paper_limit = 7
def __init__(self, judge_id, first, last, email, phone, preferred_categories, is_paper_reviewer, presentation_availability):
self.judge_id = judge_id
self.first = first
self.last = last
self.email = email
self.phone = phone
self.prefe... |
class dispatcher:
name = 'dispatcher'
def __init__(self, function_to_exec):
self.function = function_to_exec
return self.function
def get_name(self):
return self.name
def function_one(a,b):
return a + b
def function_two():
return 'function two' | class Dispatcher:
name = 'dispatcher'
def __init__(self, function_to_exec):
self.function = function_to_exec
return self.function
def get_name(self):
return self.name
def function_one(a, b):
return a + b
def function_two():
return 'function two' |
"""
ice_pick.exceptions
~~~~~~~~~~~~~~~~~~~
This module implements contains the Ice Pick exceptions.
Copyright 2014 Demand Media.
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
h... | """
ice_pick.exceptions
~~~~~~~~~~~~~~~~~~~
This module implements contains the Ice Pick exceptions.
Copyright 2014 Demand Media.
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
h... |
class UniformExchange(object):
def __init__(self, A):
if not isinstance(A, (float, int)) or A <= 0:
raise ValueError('Exchange constant must be positive float/int.')
else:
self.A = A
def get_mif(self):
# Create mif string.
mif = '# UniformExchange\n'
... | class Uniformexchange(object):
def __init__(self, A):
if not isinstance(A, (float, int)) or A <= 0:
raise value_error('Exchange constant must be positive float/int.')
else:
self.A = A
def get_mif(self):
mif = '# UniformExchange\n'
mif += 'Specify Oxs_Uni... |
# model
model = Model()
i1 = Input("op1", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}, 0.8, 5")
i2 = Output("op2", "TENSOR_QUANT8_ASYMM", "{1, 3, 3, 1}, 0.8, 5")
w = Int32Scalar("width", 3)
h = Int32Scalar("height", 3)
model = model.Operation("RESIZE_BILINEAR", i1, w, h).To(i2)
# Example 1. Input in operand 0,
input0 = {i1: ... | model = model()
i1 = input('op1', 'TENSOR_QUANT8_ASYMM', '{1, 2, 2, 1}, 0.8, 5')
i2 = output('op2', 'TENSOR_QUANT8_ASYMM', '{1, 3, 3, 1}, 0.8, 5')
w = int32_scalar('width', 3)
h = int32_scalar('height', 3)
model = model.Operation('RESIZE_BILINEAR', i1, w, h).To(i2)
input0 = {i1: [1, 1, 2, 2]}
output0 = {i2: [1, 1, 1, 2... |
def add(a, b):
print(f"ADDING {a} + {b}")
return a + b
def subtract(a, b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a, b):
print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a, b):
print(f"DIVIDING {a} / {b}")
return a / b
a = float(input("input a:"))
b = float(... | def add(a, b):
print(f'ADDING {a} + {b}')
return a + b
def subtract(a, b):
print(f'SUBTRACTING {a} - {b}')
return a - b
def multiply(a, b):
print(f'MULTIPLYING {a} * {b}')
return a * b
def divide(a, b):
print(f'DIVIDING {a} / {b}')
return a / b
a = float(input('input a:'))
b = float(i... |
# Description: Pass Statement in Python
# Pass statement in for loop
for var in range(5):
pass
# Pass statement in a while loop
while True:
pass # Busy-wait for keyboard interrupt (Ctrl + C)
# This is commonly used for creating minimal classes:
class MyEmptyClass:
pass
# Pass can also be ... | for var in range(5):
pass
while True:
pass
class Myemptyclass:
pass
def define_a_function():
pass |
number_dict = {
"0" : {
"color" : (187,173,160),
"font_size" : 45,
"backgroud_color" : (205,193,180),
"coordinate" : [(0,0), (0,0), (0,0), (0,0)]
},
"2" : {
"color" : (119, 110, 101),
"font_size" : [70, 60, 50, 40],
"backgroud_color" : (238, 228, 218),
"coordinate" : [(40,10), (30,3), (25,2), (22,3)]
},
"4... | number_dict = {'0': {'color': (187, 173, 160), 'font_size': 45, 'backgroud_color': (205, 193, 180), 'coordinate': [(0, 0), (0, 0), (0, 0), (0, 0)]}, '2': {'color': (119, 110, 101), 'font_size': [70, 60, 50, 40], 'backgroud_color': (238, 228, 218), 'coordinate': [(40, 10), (30, 3), (25, 2), (22, 3)]}, '4': {'color': (11... |
""" Install the latest Windows binary wheel package from PyPI """
def install_gitfat_win():
""" Install the latest Windows binary wheel package from PyPI """
# TODO: Parse all available packages through PyPI Simple:
# https://pypi.python.org/simple/git-fat/
raise NotImplementedError("TODO: Insta... | """ Install the latest Windows binary wheel package from PyPI """
def install_gitfat_win():
""" Install the latest Windows binary wheel package from PyPI """
raise not_implemented_error('TODO: Installing pypi/git-fat on Windows')
def main():
install_gitfat_win()
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.