content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def test_array_one_d_type_promotion(tmp_path, helpers):
# int + float to float
v_str = [ '1', '2', '3.0', '+4.0e0' ]
v = [1.0, 2.0, 3.0, 4.0]
helpers.do_one_d_variants(tmp_path, False, 4, v, v_str)
# int + barestring to string
v_str = [ '1', '2', 'abc', 'd']
v = ['1', '2', 'abc', 'd']
... | def test_array_one_d_type_promotion(tmp_path, helpers):
v_str = ['1', '2', '3.0', '+4.0e0']
v = [1.0, 2.0, 3.0, 4.0]
helpers.do_one_d_variants(tmp_path, False, 4, v, v_str)
v_str = ['1', '2', 'abc', 'd']
v = ['1', '2', 'abc', 'd']
helpers.do_one_d_variants(tmp_path, True, 4, v, v_str)
v_str ... |
def minion_game(string):
upper_string = string.upper()
vowels = 'AEIOU'
len_str = len(upper_string)
K_score, S_score = 0,0
if len_str>0 and len_str< pow(10,6):
for i in range(len_str):
if upper_string[i] in vowels:
K_score+= len(string)-i
#the score is... | def minion_game(string):
upper_string = string.upper()
vowels = 'AEIOU'
len_str = len(upper_string)
(k_score, s_score) = (0, 0)
if len_str > 0 and len_str < pow(10, 6):
for i in range(len_str):
if upper_string[i] in vowels:
k_score += len(string) - i
e... |
class DismissReason(object):
"""
This class represents a notification dismiss reason. It is passed to callback registered in on_dismiss parameter
of :py:func:`zroya.show` function.
You can print it to get a reason description or compare it with any of following attributes.
"""
User = 0
""... | class Dismissreason(object):
"""
This class represents a notification dismiss reason. It is passed to callback registered in on_dismiss parameter
of :py:func:`zroya.show` function.
You can print it to get a reason description or compare it with any of following attributes.
"""
user = 0
'\n ... |
class Constraints(object):
def __init__(self, numberOfQueens):
self.set = set()
self.populateConstraints(self.set, numberOfQueens)
def populateConstraints(self, mySet, numberOfQueens):
self.rowConstraints(mySet, numberOfQueens)
self.diagonalConstraints(mySet, numberOfQueens)
... | class Constraints(object):
def __init__(self, numberOfQueens):
self.set = set()
self.populateConstraints(self.set, numberOfQueens)
def populate_constraints(self, mySet, numberOfQueens):
self.rowConstraints(mySet, numberOfQueens)
self.diagonalConstraints(mySet, numberOfQueens)
... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def tippecanoe():
http_archive(
name="tippecanoe" ,
build_file="//bazel/deps/tippecanoe:build.BUILD" ,
sha256="916... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def tippecanoe():
http_archive(name='tippecanoe', build_file='//bazel/deps/tippecanoe:build.BUILD', sha256='9169a734cebd6d541e57f0fba98c7ef1d76b9afd9eb335f538d803e847bc41b4', strip_prefix='tippecanoe-a17bd79f7788952d8ecc046c4b47315640f92d93', url... |
"""
Quiz Problem 5
Write a Python function that returns the sublist of strings in aList
that contain fewer than 4 characters. For example, if
aList = ["apple", "cat", "dog", "banana"]
- your function should return: ["cat", "dog"]
This function takes in a list of strings and returns a list of
strings. Your func... | """
Quiz Problem 5
Write a Python function that returns the sublist of strings in aList
that contain fewer than 4 characters. For example, if
aList = ["apple", "cat", "dog", "banana"]
- your function should return: ["cat", "dog"]
This function takes in a list of strings and returns a list of
strings. Your func... |
"""Constants for the Wyze Home Assistant Integration integration."""
DOMAIN = "wyzeapi"
CONF_CLIENT = "wyzeapi_client"
ACCESS_TOKEN = "access_token"
REFRESH_TOKEN = "refresh_token"
REFRESH_TIME = "refresh_time"
WYZE_NOTIFICATION_TOGGLE = f"{DOMAIN}.wyze.notification.toggle"
LOCK_UPDATED = f"{DOMAIN}.lock_updated"
C... | """Constants for the Wyze Home Assistant Integration integration."""
domain = 'wyzeapi'
conf_client = 'wyzeapi_client'
access_token = 'access_token'
refresh_token = 'refresh_token'
refresh_time = 'refresh_time'
wyze_notification_toggle = f'{DOMAIN}.wyze.notification.toggle'
lock_updated = f'{DOMAIN}.lock_updated'
camer... |
expected_output = {
"ap": {
"ayod-1815i" : {
"number_of_sgts_referred_by_the_ap": 2,
"sgts": {
"UNKNOWN(0)": {
"policy_pushed_to_ap": "NO",
"no_of_clients": 0
},
"D... | expected_output = {'ap': {'ayod-1815i': {'number_of_sgts_referred_by_the_ap': 2, 'sgts': {'UNKNOWN(0)': {'policy_pushed_to_ap': 'NO', 'no_of_clients': 0}, 'DEFAULT(65535)': {'policy_pushed_to_ap': 'NO', 'no_of_clients': 0}}}}} |
class Node:
def __init__(self, item):
self.item = item
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, item):
if self.head is None:
self.head = Node(item)
self.tail = Node(item)
else:
new_node = Node(item)
# Make referenc... | class Node:
def __init__(self, item):
self.item = item
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, item):
if self.head is None:
self.head = node(item)
self.tail = node(item)
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Silvio Peroni <essepuntato@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE I... | def test_f(n1, n2, expected):
result = f(n1, n2)
if expected == result:
return True
else:
return False
def f(n1, n2):
n = n1 - n2
if n < 0:
n = -n
return list(range(n))
print(test_f(3, 4, [0]))
print(test_f(4, 2, [0, 1]))
print(test_f(9, 0, [0, 1, 2, 3, 4, 5, 6, 7, 8])) |
def get_attributedelta_type(attrs): # attrs: {name: func}
class ProtoAttributeDelta(object):
__slots__ = ['head', 'tail'] + list(attrs.keys())
@classmethod
def get_none(cls, element_id):
return cls(element_id, element_id, **dict((k, 0) for k in attrs)) #TODO: head and tail = ele... | def get_attributedelta_type(attrs):
class Protoattributedelta(object):
__slots__ = ['head', 'tail'] + list(attrs.keys())
@classmethod
def get_none(cls, element_id):
return cls(element_id, element_id, **dict(((k, 0) for k in attrs)))
@classmethod
def from_elemen... |
scheme = {
'base00' : '#231e18',
'base01' : '#302b25',
'base02' : '#48413a',
'base03' : '#9d8b70',
'base04' : '#b4a490',
'base05' : '#cabcb1',
'base06' : '#d7c8bc',
'base07' : '#e4d4c8',
'base08' : '#d35c5c',
'base09' : '#ca7f32',
'base0a' : '#e0ac16',
'base0b' : '#b7ba53... | scheme = {'base00': '#231e18', 'base01': '#302b25', 'base02': '#48413a', 'base03': '#9d8b70', 'base04': '#b4a490', 'base05': '#cabcb1', 'base06': '#d7c8bc', 'base07': '#e4d4c8', 'base08': '#d35c5c', 'base09': '#ca7f32', 'base0a': '#e0ac16', 'base0b': '#b7ba53', 'base0c': '#6eb958', 'base0d': '#88a4d3', 'base0e': '#bb90... |
#
# PySNMP MIB module REDSTONE-DHCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDSTONE-DHCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:55:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
# In this file, constants are defined that are used throughout the project.
# Definition in one place prevents accidental use of different strings
battery_model_simple = 'battery_model_simple'
battery_model_height_difference = 'battery_model_height_difference'
| battery_model_simple = 'battery_model_simple'
battery_model_height_difference = 'battery_model_height_difference' |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class BinaryNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
# Check the traversal ... | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Binarynode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Binarytree:
def __init__(self):
self.root = None
def type(self, type):... |
set_name(0x801384E4, "GameOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x801384EC, "vecleny__Fii", SN_NOWARN)
set_name(0x80138510, "veclenx__Fii", SN_NOWARN)
set_name(0x8013853C, "GetDamageAmt__FiPiT1", SN_NOWARN)
set_name(0x80138B34, "CheckBlock__Fiiii", SN_NOWARN)
set_name(0x80138C1C, "FindClosest__Fiii", SN_NOWARN)
set... | set_name(2148762852, 'GameOnlyTestRoutine__Fv', SN_NOWARN)
set_name(2148762860, 'vecleny__Fii', SN_NOWARN)
set_name(2148762896, 'veclenx__Fii', SN_NOWARN)
set_name(2148762940, 'GetDamageAmt__FiPiT1', SN_NOWARN)
set_name(2148764468, 'CheckBlock__Fiiii', SN_NOWARN)
set_name(2148764700, 'FindClosest__Fiii', SN_NOWARN)
set... |
persona1 = {'first_name':'Luis','last_name':'Romero','age':21,'city':'Saltillo'}
print(persona1['first_name'])
print(persona1['last_name'])
print(persona1['age'])
print(persona1['city'])
print()
persona2 = {'first_name':'Maria','last_name':'Vazquez','age':23,'city':'Saltillo'}
print(persona2['first_name'])
print(person... | persona1 = {'first_name': 'Luis', 'last_name': 'Romero', 'age': 21, 'city': 'Saltillo'}
print(persona1['first_name'])
print(persona1['last_name'])
print(persona1['age'])
print(persona1['city'])
print()
persona2 = {'first_name': 'Maria', 'last_name': 'Vazquez', 'age': 23, 'city': 'Saltillo'}
print(persona2['first_name']... |
# test builtin abs
print(abs(False))
print(abs(True))
print(abs(1))
print(abs(-1))
# bignum
print(abs(123456789012345678901234567890))
print(abs(-123456789012345678901234567890))
# edge cases for 32 and 64 bit archs (small int overflow when negating)
print(abs(-0x3fffffff - 1))
print(abs(-0x3fffffffffffffff - 1))
| print(abs(False))
print(abs(True))
print(abs(1))
print(abs(-1))
print(abs(123456789012345678901234567890))
print(abs(-123456789012345678901234567890))
print(abs(-1073741823 - 1))
print(abs(-4611686018427387903 - 1)) |
# -*- Coding: utf-8 -*-
# Base class for representing a player in a game.
class Player():
def __init__(self, name, score = 0):
self.name = name
self.score = score
def getName(self):
return self.name
def getScore(self):
return self.score
def addScore(self, value):
... | class Player:
def __init__(self, name, score=0):
self.name = name
self.score = score
def get_name(self):
return self.name
def get_score(self):
return self.score
def add_score(self, value):
self.score += value
def to_tuple(self):
return (self.name,... |
def request_serializer(Request) -> dict:
return {
"id": str(Request["_id"]),
"tenant_uid": Request["tenant_uid"],
"landlord_uid": Request["landlord_uid"],
"landlord_no": Request["landlord_no"],
"status": Request["status"],
"landlord_address": Request["landlord_address... | def request_serializer(Request) -> dict:
return {'id': str(Request['_id']), 'tenant_uid': Request['tenant_uid'], 'landlord_uid': Request['landlord_uid'], 'landlord_no': Request['landlord_no'], 'status': Request['status'], 'landlord_address': Request['landlord_address'], 'created': Request['created'], 'relation': Re... |
def format_align_digits(text, reference_text):
if len(text) != len(reference_text):
for idx, t in enumerate(reference_text):
if not t.isdigit():
text = text[:idx] + reference_text[idx] + text[idx:]
return text
| def format_align_digits(text, reference_text):
if len(text) != len(reference_text):
for (idx, t) in enumerate(reference_text):
if not t.isdigit():
text = text[:idx] + reference_text[idx] + text[idx:]
return text |
def single_quad_function(point, x0, A, rotation):
"""
Quadratic function.
Parameters
----------
point : 1-D array with shape (d, )
A point used to evaluate the gradient.
x0 : 1-D array with shape (d, ).
A : 2-D array with shape (d, d).
Diagonal matrix.
rotation : 2-D... | def single_quad_function(point, x0, A, rotation):
"""
Quadratic function.
Parameters
----------
point : 1-D array with shape (d, )
A point used to evaluate the gradient.
x0 : 1-D array with shape (d, ).
A : 2-D array with shape (d, d).
Diagonal matrix.
rotation : 2-D... |
class Monostate:
__estado: dict = {}
def __new__(cls, *args, **kwargs):
obj = super(Monostate, cls).__new__(cls, *args, **kwargs)
obj.__dict__ = cls.__estado
return obj
if __name__ == '__main__':
m1 = Monostate()
print(f'M1 ID: {id(m1)}')
print(m1.__dict__)
m2 = Monos... | class Monostate:
__estado: dict = {}
def __new__(cls, *args, **kwargs):
obj = super(Monostate, cls).__new__(cls, *args, **kwargs)
obj.__dict__ = cls.__estado
return obj
if __name__ == '__main__':
m1 = monostate()
print(f'M1 ID: {id(m1)}')
print(m1.__dict__)
m2 = monostat... |
N = int(input())
for i in range(0,N):
print(i*i)
| n = int(input())
for i in range(0, N):
print(i * i) |
guess = int(input())
# new transcript
while guess != 0:
response = input()
higherThan = [0 for x in range(10)]
lowerThan = [0 for x in range(10)]
# build case in transcript
while response != "right on":
if response == "too low":
# set any number <= guess to 1 in lowerthan
... | guess = int(input())
while guess != 0:
response = input()
higher_than = [0 for x in range(10)]
lower_than = [0 for x in range(10)]
while response != 'right on':
if response == 'too low':
for x in range(guess - 1, -1, -1):
lowerThan[x] = 1
else:
for... |
# GENERATED VERSION FILE
# TIME: Sun Aug 30 00:34:46 2020
__version__ = '1.0.0+5d75636'
short_version = '1.0.0'
| __version__ = '1.0.0+5d75636'
short_version = '1.0.0' |
repeat = int(input())
for x in range(repeat):
inlist = input().split()
for i in range(len(inlist) - 1):
print(inlist[i][::-1], end=" ")
print(inlist[-1][::-1])
| repeat = int(input())
for x in range(repeat):
inlist = input().split()
for i in range(len(inlist) - 1):
print(inlist[i][::-1], end=' ')
print(inlist[-1][::-1]) |
def touch(*files) -> bool:
"""
Create several empty files.
:param files: The list of file paths to create.
:return: The list of created files.
"""
try:
for file in files:
open(file, 'w').close()
return True
except FileNotFoundError as e:
print('... | def touch(*files) -> bool:
"""
Create several empty files.
:param files: The list of file paths to create.
:return: The list of created files.
"""
try:
for file in files:
open(file, 'w').close()
return True
except FileNotFoundError as e:
print('Check pat... |
def find_outlier(integers):
"""Find The Parity Outlier.
Idea: go though array, counting odd and even integers, counting numnber of
odd and even integers seen, and saving the last seen.
We can terminate early when we have >= 2 odd and one even (which will be
our outlier) or vice verse.
"""
... | def find_outlier(integers):
"""Find The Parity Outlier.
Idea: go though array, counting odd and even integers, counting numnber of
odd and even integers seen, and saving the last seen.
We can terminate early when we have >= 2 odd and one even (which will be
our outlier) or vice verse.
"""
... |
# create the __init__ function for class car
class Car:
def __init__(self, make, model, year, weight):
self.make = make
self.model = model
self.year = year
self.weight = weight
# initialise the car with attributes for make, model, year and weight
my_car = Car('mazda', '6', 2010, 15... | class Car:
def __init__(self, make, model, year, weight):
self.make = make
self.model = model
self.year = year
self.weight = weight
my_car = car('mazda', '6', 2010, 1510)
dream_car = car('Delorean', 'DMC', 1983, 1300)
print(my_car.__dict__)
print(dream_car.__dict__)
print('my dream ... |
def get_OP_matrix(self):
"""Return the OP matrix
Parameters
----------
self : VarLoadCurrent
A VarLoadCurrent object
Returns
-------
OP_matrix : ndarray
Operating Points matrix
"""
return self.OP_matrix
| def get_op_matrix(self):
"""Return the OP matrix
Parameters
----------
self : VarLoadCurrent
A VarLoadCurrent object
Returns
-------
OP_matrix : ndarray
Operating Points matrix
"""
return self.OP_matrix |
DEBUG = True
SECRET_KEY = "fake-key"
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.staticfiles",
"graphql_auth",
]
| debug = True
secret_key = 'fake-key'
installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'graphql_auth'] |
range(10) # stores the value of all numbers 0- 1 less than selected
range(2,8) # stores the value of all numbers first to 1 less than that selected
range(2,18,2) # stores the value of the first number - 1 less than the 2nd number, at the interval of the 3rd
# num1, starting number
# num2, number it will not pass (o... | range(10)
range(2, 8)
range(2, 18, 2)
for x in [1, 2, 4]:
print(x)
if x == 4:
break
my_list = [2, 14.4, 'ravens', 'y']
for x in my_list:
print(x)
if x == 'y':
break
print('')
for i in 'Go Red Sox!':
print(i) |
class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if len(pattern) != len(str.split(" ")):
return False
pmap = {}
smap = {}
for i in range(len(pattern)):
ppreIndex = pma... | class Solution:
def word_pattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if len(pattern) != len(str.split(' ')):
return False
pmap = {}
smap = {}
for i in range(len(pattern)):
ppre_in... |
n = int(input())
l = list(map(int, input().split()))
l.sort()
print(" ".join(map(str, l))) | n = int(input())
l = list(map(int, input().split()))
l.sort()
print(' '.join(map(str, l))) |
'''
Distribution Statement A: Approved for public release: distribution unlimited. ; May 3, 2016
This software was developed under the authority of SPAWAR Systems Center
Atlantic by employees of the Federal Government in the course of their official
duties. Pursuant to title 17 Section 105 of the United States Code th... | """
Distribution Statement A: Approved for public release: distribution unlimited. ; May 3, 2016
This software was developed under the authority of SPAWAR Systems Center
Atlantic by employees of the Federal Government in the course of their official
duties. Pursuant to title 17 Section 105 of the United States Code th... |
mat1 = [[1,2,3],[4,5,6]]
mat2 = [[7,8,9],[6,7,3]]
result= [[0,0,0],[0,0,0]]
for i in range(len(mat1)):
for j in range(len(mat2[0])):
for k in range(len(mat2)):
result[i][j]+= mat1[i][k]*mat2[j][k]
for r in result:
print(r)
| mat1 = [[1, 2, 3], [4, 5, 6]]
mat2 = [[7, 8, 9], [6, 7, 3]]
result = [[0, 0, 0], [0, 0, 0]]
for i in range(len(mat1)):
for j in range(len(mat2[0])):
for k in range(len(mat2)):
result[i][j] += mat1[i][k] * mat2[j][k]
for r in result:
print(r) |
#
# PySNMP MIB module FILTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FILTER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:00:00 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')
(constraints_union, constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint) ... |
colors = {
"dark-blue": "#0F2080",
"pink": "#A95AA1",
"medium-blue": "#607381",
"orange": "#C47A4F",
"green": "#194D31",
"purple": "#601A4A",
"light-blue": "#7C9BA5",
"tan": "#AE9C45",
"grey": "#646464",
"black": "#000000",
}
color_arr = [
"#0F2080",
"#A95AA1",
"#607... | colors = {'dark-blue': '#0F2080', 'pink': '#A95AA1', 'medium-blue': '#607381', 'orange': '#C47A4F', 'green': '#194D31', 'purple': '#601A4A', 'light-blue': '#7C9BA5', 'tan': '#AE9C45', 'grey': '#646464', 'black': '#000000'}
color_arr = ['#0F2080', '#A95AA1', '#607381', '#C47A4F', '#194D31', '#601A4A', '#7C9BA5', '#AE9C4... |
# --------------
##File path for the file
file_path
def read_file(path):
file = open(path,'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
#Code starts here
# --------------
#Code starts here
message_1 = read_file(file_path_1)
message_2 =... | file_path
def read_file(path):
file = open(path, 'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
message_1 = read_file(file_path_1)
message_2 = read_file(file_path_2)
print(message_1, message_2)
def fuse_msg(message_a, message_b):
quotient = int(m... |
# coding=utf-8
class Constant(object):
NEW_LINE = "\n"
TAB_LINE = "\t"
DEFAULT_DEBUG_ID = "debug_0"
NPU_DEBUG_ID_1 = "debug_1"
GRAPH = "graph"
DUMP = "dump"
class Suffix(object):
JSON = '.json'
CSV = '.csv'
H5 = '.h5'
class Pattern(object):
GE_PROTO_GR... | class Constant(object):
new_line = '\n'
tab_line = '\t'
default_debug_id = 'debug_0'
npu_debug_id_1 = 'debug_1'
graph = 'graph'
dump = 'dump'
class Suffix(object):
json = '.json'
csv = '.csv'
h5 = '.h5'
class Pattern(object):
ge_proto_graph_pattern = '^g... |
class FSANode:
"""
Class for Finite State Automaton(FSA) Node. Trie node definitions inherit from this class.
"""
__slots__ = 'id', 'val', 'children', 'eow', 'count'
def __init__(self, _id, val):
""" Initialize a Finite State Automaton(FSA) Node.
Parameters
----------
... | class Fsanode:
"""
Class for Finite State Automaton(FSA) Node. Trie node definitions inherit from this class.
"""
__slots__ = ('id', 'val', 'children', 'eow', 'count')
def __init__(self, _id, val):
""" Initialize a Finite State Automaton(FSA) Node.
Parameters
----------
... |
"""Download command exceptions."""
class DownloadTemplateError(Exception):
"""Error that indicates an issue with the template.
Caused by download overwriting previously downloaded files.
"""
| """Download command exceptions."""
class Downloadtemplateerror(Exception):
"""Error that indicates an issue with the template.
Caused by download overwriting previously downloaded files.
""" |
class NetworkXZeroOne:
def reconstruct(self, message):
for e in 'xo':
s = list(message)
for i, w in enumerate(s):
if w == '?':
s[i] = e
elif w != e:
break
e = 'o' if e == 'x' else 'x'
... | class Networkxzeroone:
def reconstruct(self, message):
for e in 'xo':
s = list(message)
for (i, w) in enumerate(s):
if w == '?':
s[i] = e
elif w != e:
break
e = 'o' if e == 'x' else 'x'
... |
''' this will raise a type erro we can't iterate int object'''
'''for i in 25:
print(i)'''
''' first way it will give 1 to 25'''
print("First way")
for i in range(1,26):
print(i)
''' second way ForLoop Iterate Over List of One Element and it will print only 25'''
print("Second way")
for i in [25]:
print(i... | """ this will raise a type erro we can't iterate int object"""
'for i in 25:\n print(i)'
' first way it will give 1 to 25'
print('First way')
for i in range(1, 26):
print(i)
' second way ForLoop Iterate Over List of One Element and it will print only 25'
print('Second way')
for i in [25]:
print(i) |
class DisjSet:
def __init__(self, n):
# Constructor to create and
# initialize sets of n items
self.rank = [1] * n
self.parent = [i for i in range(n)]
# Finds set of given item x
def find(self, x):
# Finds the representative of the set
... | class Disjset:
def __init__(self, n):
self.rank = [1] * n
self.parent = [i for i in range(n)]
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
xset = self.find(x)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
def find(string = str,
substring = str,
start_indx = int,
stop_indx = int):
"""
Find the first occurence of 'substring' in 'string'
... | """
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
def find(string=str, substring=str, start_indx=int, stop_indx=int):
"""
Find the first occurence of 'substring' in 'string'
Return None if no occurences
"""
if substring in string[start_indx:stop_indx]:
return s... |
"""Custom errors for mssql_dataframe."""
class EnvironmentODBCDriverNotFound(Exception):
"""Exception for not automatically determining ODBC driver."""
pass
class UndefinedConversionRule(Exception):
"""Exception for undefined conversion rule between pandas, ODBC, and SQL."""
pass
class SQLTableD... | """Custom errors for mssql_dataframe."""
class Environmentodbcdrivernotfound(Exception):
"""Exception for not automatically determining ODBC driver."""
pass
class Undefinedconversionrule(Exception):
"""Exception for undefined conversion rule between pandas, ODBC, and SQL."""
pass
class Sqltabledoesno... |
"""
:copyright: Michael Yusko
:license: MIT, see LICENSE for more details.
"""
__author__ = 'Michael Yusko'
__version__ = '0.1.1'
| """
:copyright: Michael Yusko
:license: MIT, see LICENSE for more details.
"""
__author__ = 'Michael Yusko'
__version__ = '0.1.1' |
class Point:
def __init__(self):
self.x = 0
self.y = 0
def prompt_for_point(self):
self.x = int(input('Enter x: '))
self.y = int(input('Enter y: '))
def display(self):
print('Center:')
print('({}, {})'.format(self.x, self.y))
class Circle:
def __init__... | class Point:
def __init__(self):
self.x = 0
self.y = 0
def prompt_for_point(self):
self.x = int(input('Enter x: '))
self.y = int(input('Enter y: '))
def display(self):
print('Center:')
print('({}, {})'.format(self.x, self.y))
class Circle:
def __init_... |
"""API messages"""
SIGNUP_MSG = "New account created: %s"
LOGOUT = "Logged out successfully!"
LOGIN = "You are now logged in as %s"
REDIRECT_AFTER_LOGIN = "Redirecting user back to %s"
INVALID_LOGIN = "Invalid username or password."
NO_ITEM_IN_CATEGORY = "Oops.. Category %s does not contain any item!"
MSG_404 = "Oops... | """API messages"""
signup_msg = 'New account created: %s'
logout = 'Logged out successfully!'
login = 'You are now logged in as %s'
redirect_after_login = 'Redirecting user back to %s'
invalid_login = 'Invalid username or password.'
no_item_in_category = 'Oops.. Category %s does not contain any item!'
msg_404 = "Oops..... |
"""
This is Data access layer.
Describe here your Django models and
Django custom model managers.
Split your models module as it will grow up.
Classes from this package describe how to
access, store and manipulate on data.
DO NOT implement here business logic, only
operations with data storages.
As recommendation,... | """
This is Data access layer.
Describe here your Django models and
Django custom model managers.
Split your models module as it will grow up.
Classes from this package describe how to
access, store and manipulate on data.
DO NOT implement here business logic, only
operations with data storages.
As recommendation,... |
#escape sequence character
def escapeChar():
return "\t lorem Ipsum is simply dummy text of the printing and typesetting industry.\n \t Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,\n \t when an unknown printer took a galley of type and scrambled it to make a type specimen book."
pr... | def escape_char():
return "\t lorem Ipsum is simply dummy text of the printing and typesetting industry.\n \t Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,\n \t when an unknown printer took a galley of type and scrambled it to make a type specimen book."
print(escape_char()) |
class HnExportException(Exception):
path = "log.txt"
def __init__(self,place, arg):
self.place = place
self.arg = arg
mstr = ''
for i in arg :
mstr += str(i)
self.WriteLog(place+":"+mstr)
def __init__(self,_str):
self.WriteLog(_str)
... | class Hnexportexception(Exception):
path = 'log.txt'
def __init__(self, place, arg):
self.place = place
self.arg = arg
mstr = ''
for i in arg:
mstr += str(i)
self.WriteLog(place + ':' + mstr)
def __init__(self, _str):
self.WriteLog(_str)
def... |
#create shipping_detail class
class shipping_detail:
# define the components of the shipping class with default function
def __init__(self):
# defining components of shipping_detail class as variables
self.shipping_id = "<shipping_id>"
self.delivery_address = "<delivery_addres... | class Shipping_Detail:
def __init__(self):
self.shipping_id = '<shipping_id>'
self.delivery_address = '<delivery_address>'
self.shipping_price = '<shipping_price>'
def set_data(self, shipping_id, delivery_address, shipping_price):
self.shipping_id = shipping_id
self.del... |
### =======================================
"""Looping over lists in Python"""
### =======================================
# define the network part of our IP Add
network_part = "192.168.2."
# define the host part for each device as list
host_parts = [20, 40, 60]
# Now, we can use a for loop to iterate and combine the... | """Looping over lists in Python"""
network_part = '192.168.2.'
host_parts = [20, 40, 60]
for host in host_parts:
ip = network_part + str(host)
print('The router IP is: ' + ip)
network_part = '10.20.30.'
host_parts = [40, 50, 60]
for i in range(len(host_parts)):
ip = network_part + str(i)
print('The IP o... |
#
# Display DMD frames on console
#
# Translate bits to characters for different bits/pixel
# 4 bit is really only 3 bit
symbols = {
"wpc": [" ","*"],
"whitestar": [" ",".","o","O","*","?","?","?","?","?","?","?","?","?","?","?"],
"spike": [" "," ",".",".",".","o","o","o","O","O","O","*","*","*","#","#"]
}
class C... | symbols = {'wpc': [' ', '*'], 'whitestar': [' ', '.', 'o', 'O', '*', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?'], 'spike': [' ', ' ', '.', '.', '.', 'o', 'o', 'o', 'O', 'O', 'O', '*', '*', '*', '#', '#']}
class Consoledisplay:
def __init__(self, characterset):
self.chars = symbols[characterset]... |
n = int(input())
left_chairs = 0
enough_chairs = True
for i in range(1, n + 1):
tokens = input().split(" ")
chairs = len(tokens[0])
people = int(tokens[1])
if chairs >= people:
left_chairs += chairs - people
else:
enough_chairs = False
print(f"{people - chairs} more chairs n... | n = int(input())
left_chairs = 0
enough_chairs = True
for i in range(1, n + 1):
tokens = input().split(' ')
chairs = len(tokens[0])
people = int(tokens[1])
if chairs >= people:
left_chairs += chairs - people
else:
enough_chairs = False
print(f'{people - chairs} more chairs ne... |
#!/usr/bin/env python3
"""
Write a function called cumsum that takes a list of numbers and returns
the cumulative sum; that is, a new list where the ith element is the sum
of the first i + 1 elements from the original list
"""
def cumsum(t):
new_t = []
for i in range(len(t)):
new_t += [sum(t[:i+1]... | """
Write a function called cumsum that takes a list of numbers and returns
the cumulative sum; that is, a new list where the ith element is the sum
of the first i + 1 elements from the original list
"""
def cumsum(t):
new_t = []
for i in range(len(t)):
new_t += [sum(t[:i + 1])]
return new_t
if ... |
#!/usr/bin/env python3
def minswap (arr):
count = 0
pos = dict ()
# ~ print ('ARR:', arr)
for i in range (len (arr)):
pos[arr[i]] = i
# ~ print ('POS:', pos)
xi = 0
for n in sorted (pos):
i = pos[n]
# ~ print ('N:', n, 'XI:', xi, 'I:', i)
if xi != i:
... | def minswap(arr):
count = 0
pos = dict()
for i in range(len(arr)):
pos[arr[i]] = i
xi = 0
for n in sorted(pos):
i = pos[n]
if xi != i:
pos[arr[i]] = xi
pos[arr[xi]] = i
(arr[xi], arr[i]) = (arr[i], arr[xi])
count += 1
xi... |
# coding: utf-8
with open("test.txt", mode="r") as f:
f.read(12)
print(f.tell())
| with open('test.txt', mode='r') as f:
f.read(12)
print(f.tell()) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of tornadis library released under the MIT license.
# See the LICENSE file for more information.
class TornadisException(Exception):
"""Base Exception class."""
pass
class ConnectionError(TornadisException):
"""Exception raised when the... | class Tornadisexception(Exception):
"""Base Exception class."""
pass
class Connectionerror(TornadisException):
"""Exception raised when there is a connection error."""
pass
class Clienterror(TornadisException):
"""Exception raised when there is a client error.""" |
#
# PySNMP MIB module CISCO-IF-LINK-CONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IF-LINK-CONFIG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:01:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection) ... |
#
# PySNMP MIB module CISCO-HC-RMON-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HC-RMON-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:42:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
pattern_zero=[0.0, 0.062222222222, 0.115555555556, 0.133333333333, 0.16, 0.195555555556, 0.222222222222, 0.24, 0.248888888889, 0.266666666667, 0.293333333333, 0.328888888889, 0.355555555556, 0.373333333333, 0.382222222222, 0.4, 0.426666666667, 0.462222222222, 0.488888888889, 0.506666666667, 0.515555555556, 0.5333333333... | pattern_zero = [0.0, 0.062222222222, 0.115555555556, 0.133333333333, 0.16, 0.195555555556, 0.222222222222, 0.24, 0.248888888889, 0.266666666667, 0.293333333333, 0.328888888889, 0.355555555556, 0.373333333333, 0.382222222222, 0.4, 0.426666666667, 0.462222222222, 0.488888888889, 0.506666666667, 0.515555555556, 0.53333333... |
class Solution:
def maxPower(self, s: str) -> int:
max_count = 1
count = 1
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
count += 1
if count > max_count:
max_count = count
if s[i] != s[i + 1]:
count = 1
... | class Solution:
def max_power(self, s: str) -> int:
max_count = 1
count = 1
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
count += 1
if count > max_count:
max_count = count
if s[i] != s[i + 1]:
count = 1
... |
"""
Day 5: Poisson Distribution I
A random variable,X, follows Poisson distribution with mean of 2.5.
Find the probability with which the random variable X is equal to 5.
Author: Eda AYDIN
"""
def factorial(n):
if n == 1 or n == 0:
return 1
if n > 1:
return factorial(n - 1) *... | """
Day 5: Poisson Distribution I
A random variable,X, follows Poisson distribution with mean of 2.5.
Find the probability with which the random variable X is equal to 5.
Author: Eda AYDIN
"""
def factorial(n):
if n == 1 or n == 0:
return 1
if n > 1:
return factorial(n - 1) * n
def poisson(... |
class payload:
def __init__(self):
self.name = "openurl"
self.description = "open url through the default browser"
self.type = "native"
self.id = 117
def run(self,session,server,command):
return self.name
| class Payload:
def __init__(self):
self.name = 'openurl'
self.description = 'open url through the default browser'
self.type = 'native'
self.id = 117
def run(self, session, server, command):
return self.name |
"""
Method Resolution Order
In the multiple inheritance scenario, any specified attribute is searched first
in the current class.If not found, the search continues into parent class in depth first
left-right fashion without searching same class twice.
class LandLive():
def LandLife(self):
print("It ca... | """
Method Resolution Order
In the multiple inheritance scenario, any specified attribute is searched first
in the current class.If not found, the search continues into parent class in depth first
left-right fashion without searching same class twice.
class LandLive():
def LandLife(self):
print("It ca... |
ref = {"A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15}
def hex_to_decimal_integer(number):
if "." in number:
number = number.split('.')[0]
result = 0
for index, multiplier in enumerate(range(len(number) - 1, -1, -1)):
value = number[index]
if value in ref.keys():
... | ref = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
def hex_to_decimal_integer(number):
if '.' in number:
number = number.split('.')[0]
result = 0
for (index, multiplier) in enumerate(range(len(number) - 1, -1, -1)):
value = number[index]
if value in ref.keys():
... |
#You can return a range of characters by using the slice syntax.
#Specify the start index and the end index, separated by a colon, to return a part of the string.
#Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[5:8])
#by leaving out th... | b = 'Hello, World!'
print(b[2:5])
b = 'Hello, World!'
print(b[5:8])
b = 'Hello, World!'
print(b[:5])
b = 'Hello, World!'
print(b[:9])
b = 'Hello, World!'
print(b[2:])
b = 'Hello, World!'
print(b[4:])
b = 'Hello, World!'
print(b[-5:-2])
b = 'Hello, World!'
print(b[-9:-5]) |
class Person:
"This is a person class"
age = 10
def greet(self):
print("Hello")
# create a new object of Person class
harry = Person()
# Output: <function Person.greet>
print(Person.greet)
# Output: <bound method Person.greet of <__main__.Person object>>
print(harry.greet)
# Calling object's gr... | class Person:
"""This is a person class"""
age = 10
def greet(self):
print('Hello')
harry = person()
print(Person.greet)
print(harry.greet)
harry.greet() |
# Time: O(n)
# Space: O(1)
class Solution(object):
def averageWaitingTime(self, customers):
"""
:type customers: List[List[int]]
:rtype: float
"""
avai = wait = 0.0
for a, t in customers:
avai = max(avai, a)+t
wait += avai-a
return wa... | class Solution(object):
def average_waiting_time(self, customers):
"""
:type customers: List[List[int]]
:rtype: float
"""
avai = wait = 0.0
for (a, t) in customers:
avai = max(avai, a) + t
wait += avai - a
return wait / len(customers) |
font = CurrentFont()
for name in font.selection:
# get source glyph
source = font[name]
# get smallcap name
gn = source.name + ".num"
# make sc glyph object
glyph = font.newGlyph(gn)
# add source to sc glyph
glyph.appendGlyph(source)
# scale
glyph.prepareUndo... | font = current_font()
for name in font.selection:
source = font[name]
gn = source.name + '.num'
glyph = font.newGlyph(gn)
glyph.appendGlyph(source)
glyph.prepareUndo()
glyph.scaleBy((0.8, 0.7))
move = source.bounds[3] - glyph.bounds[3]
glyph.moveBy((0, move))
glyph.performUndo()
... |
api = {
'base_url_net': 'https://babelnet.io/v6',
'base_url_fy': 'https://babelfy.io/v1/',
'disambiguate_url': 'https://babelfy.io/v1/disambiguate',
'synsets_given_word_url': 'https://babelnet.io/v6/getSynsetIds',
'senses_given_word_url': 'https://babelnet.io/v6/getSenses',
'information_given_... | api = {'base_url_net': 'https://babelnet.io/v6', 'base_url_fy': 'https://babelfy.io/v1/', 'disambiguate_url': 'https://babelfy.io/v1/disambiguate', 'synsets_given_word_url': 'https://babelnet.io/v6/getSynsetIds', 'senses_given_word_url': 'https://babelnet.io/v6/getSenses', 'information_given_synset_url': 'https://babel... |
# Move the first letter of each word to the end of it,
# then add "ay" to the end of the word.
# Leave punctuation marks untouched.
# My Solution
def pig_it(text):
workString = text.split(" ")
resString = []
for word in workString:
if word.isalpha():
newWord = word[1:] + wor... | def pig_it(text):
work_string = text.split(' ')
res_string = []
for word in workString:
if word.isalpha():
new_word = word[1:] + word[0] + 'ay'
resString.append(newWord)
else:
resString.append(word)
return ' '.join(resString)
def pig_it(text):
lst... |
'''1. Write a Python program to count the number of arguments in a given function.
Sample Output:
0
1
2
3
4
1'''
def num_of_args(*args):
return(len(args))
print(num_of_args())
print(num_of_args(1))
print(num_of_args(1, 2))
print(num_of_args(1, 2, 3))
print(num_of_args(1, 2, 3, 4))
print(num_of_args([1, 2, 3, 4]))
#Re... | """1. Write a Python program to count the number of arguments in a given function.
Sample Output:
0
1
2
3
4
1"""
def num_of_args(*args):
return len(args)
print(num_of_args())
print(num_of_args(1))
print(num_of_args(1, 2))
print(num_of_args(1, 2, 3))
print(num_of_args(1, 2, 3, 4))
print(num_of_args([1, 2, 3, 4])) |
# The following has been generated automatically from src/core/geometry/qgsgeometry.h
QgsGeometry.BufferSide.baseClass = QgsGeometry
QgsGeometry.EndCapStyle.baseClass = QgsGeometry
QgsGeometry.JoinStyle.baseClass = QgsGeometry
| QgsGeometry.BufferSide.baseClass = QgsGeometry
QgsGeometry.EndCapStyle.baseClass = QgsGeometry
QgsGeometry.JoinStyle.baseClass = QgsGeometry |
def add(src,links,wei=1):
for a in range(len(mat[src])):
if a!=src:
if a == links:
mat[src][a]=1*wei
elif mat[src][a]!=0 and mat[src][a]!=None:
pass
else:
mat[src][a]=0
def call(a,b,w=1):
add(a,b,w)
add(b,a,w) ... | def add(src, links, wei=1):
for a in range(len(mat[src])):
if a != src:
if a == links:
mat[src][a] = 1 * wei
elif mat[src][a] != 0 and mat[src][a] != None:
pass
else:
mat[src][a] = 0
def call(a, b, w=1):
add(a, b, w)
... |
#
# PySNMP MIB module H3C-SYS-MAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-SYS-MAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:24:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, constraints_intersection, single_value_constraint) ... |
"""
RawIO for reading data from Neuralynx files.
This IO supports NCS, NEV, NSE and NTT file formats.
NCS contains the sampled signal for one channel
NEV contains events
NSE contains spikes and waveforms for mono electrodes
NTT contains spikes and waveforms for tetrodes
"""
| """
RawIO for reading data from Neuralynx files.
This IO supports NCS, NEV, NSE and NTT file formats.
NCS contains the sampled signal for one channel
NEV contains events
NSE contains spikes and waveforms for mono electrodes
NTT contains spikes and waveforms for tetrodes
""" |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... | """
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
class Solution:
def superEggDrop(self, K: int, N: int) -> int:
# @functools.lru_cache(None)
# def dfs(k,n):
# if k==1:return n
# if n==1:return 1
# return dfs(k,n-1)+dfs(k-1,n-1)+1
# for i in range(1,N+1):
# if dfs(K,i)>=N:return i
dp... | class Solution:
def super_egg_drop(self, K: int, N: int) -> int:
dp = [[0] * (N + 1) for _ in range(K + 1)]
for i in range(1, K + 1):
for j in range(1, N + 1):
dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1] + 1
if dp[K][j] >= N:
return j |
__all__ = [
'doc_matching_rules',
]
doc_matching_rules = '''
Ship transforms will commonly use a group of matching rules
to determine which ships get modified, and by how much.
* Matching rules:
- These are tuples pairing a matching rule (string) with transform
defined args, eg. ... | __all__ = ['doc_matching_rules']
doc_matching_rules = '\n Ship transforms will commonly use a group of matching rules\n to determine which ships get modified, and by how much. \n\n * Matching rules:\n - These are tuples pairing a matching rule (string) with transform\n defined args, eg. ("key va... |
fixtures = [
{"name": "+5 Dexterity Vest", "sell_in": 10,
"quality": 20, "category": "normal"},
{"name": "Aged Brie", "sell_in": 2, "quality": 0, "category": "aged_brie"},
{"name": "Elixir of the Mongoose", "sell_in": 5,
"quality": 7, "category": "normal"},
{"name": "Sulfuras, Hand of Ra... | fixtures = [{'name': '+5 Dexterity Vest', 'sell_in': 10, 'quality': 20, 'category': 'normal'}, {'name': 'Aged Brie', 'sell_in': 2, 'quality': 0, 'category': 'aged_brie'}, {'name': 'Elixir of the Mongoose', 'sell_in': 5, 'quality': 7, 'category': 'normal'}, {'name': 'Sulfuras, Hand of Ragnaros', 'sell_in': 0, 'quality':... |
def strategy(history, memory):
if history.shape[1] % 2 == 0: # even, cooperate in odd
return 1, None
else:
return 0, None | def strategy(history, memory):
if history.shape[1] % 2 == 0:
return (1, None)
else:
return (0, None) |
n = int(input())
cnt = 0
l = [int(i) for i in input().split()]
for i in range(1,n):
if l[i] < l[i-1]:
cnt = cnt + (l[i-1] - l[i])
l[i] = l[i-1]
print(cnt) | n = int(input())
cnt = 0
l = [int(i) for i in input().split()]
for i in range(1, n):
if l[i] < l[i - 1]:
cnt = cnt + (l[i - 1] - l[i])
l[i] = l[i - 1]
print(cnt) |
class class0:
var0 = ''
def __init__(self):
var1 = 0
def fun1():
return var0
def fun2():
print('useless print')
return var1 | class Class0:
var0 = ''
def __init__(self):
var1 = 0
def fun1():
return var0
def fun2():
print('useless print')
return var1 |
def handshake(code):
pass
def secret_code(actions):
pass
| def handshake(code):
pass
def secret_code(actions):
pass |
class VulnerableBySeveritySplunk:
"""Format `vulnerable_by_severity.json` for Splunk"""
def __init__(self, data):
"""
:param data: a dict() created from `data/vulnerable_by_severity.json`
"""
self.data = data
def splunk_format(self):
"""Format for splunk: Split out ... | class Vulnerablebyseveritysplunk:
"""Format `vulnerable_by_severity.json` for Splunk"""
def __init__(self, data):
"""
:param data: a dict() created from `data/vulnerable_by_severity.json`
"""
self.data = data
def splunk_format(self):
"""Format for splunk: Split out ... |
def generate_functions(function_name):
return "def {}(chat_id, message):\n\
bot = Bot(token=TELEGRAM_TOKEN)\
bot.sendMessage(chat_id=chat_id, text=message)\n\n".format(function_name)
def generate_callback(function_name):
return "def {}(ch, method, properties, body):\n\tpass\n\n".format(function_name)
... | def generate_functions(function_name):
return 'def {}(chat_id, message):\n bot = Bot(token=TELEGRAM_TOKEN) bot.sendMessage(chat_id=chat_id, text=message)\n\n'.format(function_name)
def generate_callback(function_name):
return 'def {}(ch, method, properties, body):\n\tpass\n\n'.format(function_name)
def ... |
CHARACTERS = {
0: 'Ryu',
1: 'Dictator',
2: 'Chun Li',
3: 'Ken',
4: 'Karin',
5: 'Zangief',
6: 'Dhalsim',
7: 'Nash',
8: 'Claw',
10: 'Birdie',
11: 'R. Mika',
12: 'Rashid',
13: 'Fang',
14: 'Laura',
15: 'Necalli',
16: 'Cammy',
21: 'Alex',
17: 'Guile',
... | characters = {0: 'Ryu', 1: 'Dictator', 2: 'Chun Li', 3: 'Ken', 4: 'Karin', 5: 'Zangief', 6: 'Dhalsim', 7: 'Nash', 8: 'Claw', 10: 'Birdie', 11: 'R. Mika', 12: 'Rashid', 13: 'Fang', 14: 'Laura', 15: 'Necalli', 16: 'Cammy', 21: 'Alex', 17: 'Guile'}
character_order = [12, 11, 2, 0, 14, 5, 4, 7, 3, 16, 8, 15, 1, 10, 6, 13, ... |
def _print_option_help( op, names, detailed_help, prefix, help_justification ):
help = ''
if detailed_help:
for name in names[:-1]:
help += prefix + name + ':\n'
name = names[-1]
tmp = prefix + name + ':'
help += tmp
help += ' ' * (len( help_justifica... | def _print_option_help(op, names, detailed_help, prefix, help_justification):
help = ''
if detailed_help:
for name in names[:-1]:
help += prefix + name + ':\n'
name = names[-1]
tmp = prefix + name + ':'
help += tmp
help += ' ' * (len(help_justification) - len(tmp))
h = op... |
class Solution:
def divisorGame(self, N: int) -> bool:
return not N%2
N = 2
res = Solution().divisorGame(N)
print(res) | class Solution:
def divisor_game(self, N: int) -> bool:
return not N % 2
n = 2
res = solution().divisorGame(N)
print(res) |
def insertionsort(ar,m):
i=m-1
temp=ar[i]
while(ar[i-1]>temp and i>0):
ar[i]=ar[i-1]
print(' '.join(map(str,ar)))
i-=1
ar[i]=temp
print(' '.join(map(str,ar)))
return ar
m = int(input())
ar = [int(i) for i in input().split()]
ar=insertionsort(ar,m) | def insertionsort(ar, m):
i = m - 1
temp = ar[i]
while ar[i - 1] > temp and i > 0:
ar[i] = ar[i - 1]
print(' '.join(map(str, ar)))
i -= 1
ar[i] = temp
print(' '.join(map(str, ar)))
return ar
m = int(input())
ar = [int(i) for i in input().split()]
ar = insertionsort(ar, m) |
"""
htmlx.webapi.websocket
====================================
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
"""
| """
htmlx.webapi.websocket
====================================
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
""" |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | def check_sequence_consistency(unit_test, ordered_sequence, equal=False):
for (i, el) in enumerate(ordered_sequence):
for previous in ordered_sequence[:i]:
_check_order_consistency(unit_test, previous, el, equal)
for posterior in ordered_sequence[i + 1:]:
_check_order_consist... |
class FilterParamsMissing(Exception):
"""
When some parameters are missing while initializing the Filter Node,
this exception will be raised asking for the completion of the missing
parameters
"""
def __str__(self):
return "Filter node has missing arguments. \n Use like :: " \
... | class Filterparamsmissing(Exception):
"""
When some parameters are missing while initializing the Filter Node,
this exception will be raised asking for the completion of the missing
parameters
"""
def __str__(self):
return 'Filter node has missing arguments. \n Use like :: filter(filter... |
def add(a=1, b=2):
return a+b
def sub(a=5, b=2):
return a-b
| def add(a=1, b=2):
return a + b
def sub(a=5, b=2):
return a - b |
def pagify(text, delims=["\n"], *, escape_mass_mentions=True, shorten_by=8, page_length=2000):
in_text = text
if escape_mass_mentions:
num_mentions = text.count("@here") + text.count("@everyone")
shorten_by += num_mentions
page_length -= shorten_by
while len(in_text) > page_length:
closest_delim = m... | def pagify(text, delims=['\n'], *, escape_mass_mentions=True, shorten_by=8, page_length=2000):
in_text = text
if escape_mass_mentions:
num_mentions = text.count('@here') + text.count('@everyone')
shorten_by += num_mentions
page_length -= shorten_by
while len(in_text) > page_length:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.