content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''import math #as m also can be written
a=math.pi #a=m.pi
print(a)
'''
'''
from math import pi #import only pi from math
b=2*pi
print(b)
'''
'''
from math import * #import everything from math
b=2*pi
print(b)
'''
'''
food = 'spam'
if food == 'spam':
print('Ummmm, my favourite!')
print('I feel like sa... | """import math #as m also can be written
a=math.pi #a=m.pi
print(a)
"""
'\nfrom math import pi #import only pi from math\nb=2*pi\nprint(b)\n'
'\nfrom math import * #import everything from math\nb=2*pi\nprint(b)\n'
"\nfood = 'spam'\nif food == 'spam':\n print('Ummmm, my favourite!')\nprint('I feel like sa... |
def test_post_order(client, order_payload):
res = client.post("/order", json = order_payload)
assert res.status_code == 200
def test_post_game(client, game_payload):
res = client.post("/order", json = game_payload)
assert res.status_code == 200
def test_get_order(client):
res1 = client.get("/o... | def test_post_order(client, order_payload):
res = client.post('/order', json=order_payload)
assert res.status_code == 200
def test_post_game(client, game_payload):
res = client.post('/order', json=game_payload)
assert res.status_code == 200
def test_get_order(client):
res1 = client.get('/order')
... |
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hour_deg = (hour*30)%360 + (0.5)*minutes
minute_deg = ((minutes/5)*30)%360
if(abs(hour_deg-minute_deg)>180):
return 360 - abs(hour_deg-minute_deg)
else:
return abs(hour_d... | class Solution:
def angle_clock(self, hour: int, minutes: int) -> float:
hour_deg = hour * 30 % 360 + 0.5 * minutes
minute_deg = minutes / 5 * 30 % 360
if abs(hour_deg - minute_deg) > 180:
return 360 - abs(hour_deg - minute_deg)
else:
return abs(hour_deg - mi... |
class Solution:
def findDuplicate(self, nums: list[int]) -> int:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return nums[i]
class Solution:
def findDuplicate(self, nums: list[int]) -> int:
# 'low' and 'high' represent the range of va... | class Solution:
def find_duplicate(self, nums: list[int]) -> int:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return nums[i]
class Solution:
def find_duplicate(self, nums: list[int]) -> int:
low = 1
high = len(nums) - 1
... |
num = int(input(''))
hours = int(input(''))
value = float(input(''))
print('NUMBER = {:0}\nSALARY = U$ {:.2f}'.format(num, (hours * value))) | num = int(input(''))
hours = int(input(''))
value = float(input(''))
print('NUMBER = {:0}\nSALARY = U$ {:.2f}'.format(num, hours * value)) |
"""
Unit tests for pyDEX project should all go in this module
author: officialcryptomaster@gmail.com
"""
| """
Unit tests for pyDEX project should all go in this module
author: officialcryptomaster@gmail.com
""" |
class Solution(object):
def combinationSum2(self, candidates, target):
ret = []
self.dfs(sorted(candidates), target, 0, [], ret)
return ret
def dfs(self, nums, target, idx, path, ret):
if target <= 0:
if target == 0:
ret.append(path)
r... | class Solution(object):
def combination_sum2(self, candidates, target):
ret = []
self.dfs(sorted(candidates), target, 0, [], ret)
return ret
def dfs(self, nums, target, idx, path, ret):
if target <= 0:
if target == 0:
ret.append(path)
ret... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | class Dispersionongrid:
def __init__(self, axes, polarization_npyarr, energy_npyarr):
self.axes = axes
self.polarization_npyarr = polarization_npyarr
self.energy_npyarr = energy_npyarr
return
pass
__id__ = '$Id$' |
str1 = "Udacity"
# LENGTH
print(len(str1)) # 7
# CHANGE CASE
# The `lower()` and `upper` method returns the string in lower case and upper case respectively
print(str1.lower()) # udacity
print(str1.upper()) # UDACITY
# SLICING
# string_var[lower_index : upper_index]
# Note that the upper_index is not inclusive... | str1 = 'Udacity'
print(len(str1))
print(str1.lower())
print(str1.upper())
print(str1[1:6])
print(str1[:6])
print(str1[1:])
print(str1[-6:-1])
str2 = ' Udacity '
print(str2.strip())
print(str1.replace('y', 'B'))
str3 = 'Welcome, Constance!'
print(str3.split(','))
print(str3 + ' ' + str1)
marks = 100
print(str3 + '... |
class Line:
def __init__(self,p1,p2):
if (p1[0] > p2[0]):
self.p1 = p2
self.p2 = p1
elif (p1[0] == p2[0] and p1[1] > p2[1]):
self.p1 = p2
self.p2 = p1
else:
self.p1 = p1
self.p2 = p2
print(self.p1)
prin... | class Line:
def __init__(self, p1, p2):
if p1[0] > p2[0]:
self.p1 = p2
self.p2 = p1
elif p1[0] == p2[0] and p1[1] > p2[1]:
self.p1 = p2
self.p2 = p1
else:
self.p1 = p1
self.p2 = p2
print(self.p1)
print(s... |
class Node:
pass
class SystemNode(Node):
def __init__(self, equations):
self.equations = equations
class EquationNode(Node):
def __init__(self, differential, expression):
self.differential = differential
self.expression = expression
class DifferentialNode(Node):
def __init_... | class Node:
pass
class Systemnode(Node):
def __init__(self, equations):
self.equations = equations
class Equationnode(Node):
def __init__(self, differential, expression):
self.differential = differential
self.expression = expression
class Differentialnode(Node):
def __init_... |
"""Assignment operators
@see: https://www.w3schools.com/python/python_operators.asp
Assignment operators are used to assign values to variables
"""
def test_assignment_operator():
"""Assignment operator """
assert True
# Multiple assignment.
# The variables first_variable and second_variable simul... | """Assignment operators
@see: https://www.w3schools.com/python/python_operators.asp
Assignment operators are used to assign values to variables
"""
def test_assignment_operator():
"""Assignment operator """
assert True
(first_variable, second_variable) = (0, 1)
assert first_variable == 0
assert s... |
#!/usr/bin/env python
"""Tests for `tools_1c` package."""
| """Tests for `tools_1c` package.""" |
"""Generate warnings for Machine statistics"""
def cpu_warning_generator(cpu_tuple):
# Returns boolean value false if used cycles is greater than idle cycles
used_time = cpu_tuple.user + cpu_tuple.nice + cpu_tuple.system
if used_time > cpu_tuple.idle:
return True
else:
return False
def ... | """Generate warnings for Machine statistics"""
def cpu_warning_generator(cpu_tuple):
used_time = cpu_tuple.user + cpu_tuple.nice + cpu_tuple.system
if used_time > cpu_tuple.idle:
return True
else:
return False
def memory_warning_generator(memory_tuple, threshold=524288000):
if memory_t... |
frase = str(input('Digite uma frase: '))
cont = 1
for c in frase:
if cont % 2 == 0:
print(c.upper(), end='')
else:
print(c.lower(), end='')
cont += 1
| frase = str(input('Digite uma frase: '))
cont = 1
for c in frase:
if cont % 2 == 0:
print(c.upper(), end='')
else:
print(c.lower(), end='')
cont += 1 |
# https://stackoverflow.com/questions/13979714/heap-sort-how-to-sort
swaps = 0
def heapify(arr, n, i):
global swaps
count = 0
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if... | swaps = 0
def heapify(arr, n, i):
global swaps
count = 0
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
count += 1
(arr[i], arr[largest]) = (arr[largest], ... |
class Solution:
def solve(self, words):
groups = defaultdict(list)
for word in words:
for key in groups:
if len(word)==len(key) and any(all(word[j]==key[j-i] for j in range(i,len(word))) and all(word[j]==key[len(word)-i+j] for j in range(i)) for i in range(len(word))):
... | class Solution:
def solve(self, words):
groups = defaultdict(list)
for word in words:
for key in groups:
if len(word) == len(key) and any((all((word[j] == key[j - i] for j in range(i, len(word)))) and all((word[j] == key[len(word) - i + j] for j in range(i))) for i in ra... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurantlessthan20, obj[15]: Re... | def find_decision(obj):
if obj[3] <= 3:
if obj[10] <= 20:
if obj[13] > 0.0:
if obj[2] <= 3:
if obj[12] <= 3.0:
if obj[17] > 1:
if obj[14] <= 2.0:
if obj[6] <= 4:
... |
#-- gestures supported by Otto
#-- OttDIY Python Project, 2020
OTTOHAPPY = const(0)
OTTOSUPERHAPPY = const(1)
OTTOSAD = const(2)
OTTOSLEEPING = const(3)
OTTOFART = const(4)
OTTOCONFUSED = const(5)
OTTOLOVE = const(6)
OTTOANGRY = const(7)
OTTOFRETFUL = const(8)
OTTOMAGIC = cons... | ottohappy = const(0)
ottosuperhappy = const(1)
ottosad = const(2)
ottosleeping = const(3)
ottofart = const(4)
ottoconfused = const(5)
ottolove = const(6)
ottoangry = const(7)
ottofretful = const(8)
ottomagic = const(9)
ottowave = const(10)
ottovictory = const(11)
ottofail = const(12) |
products = {}
command = input()
while command != "statistics":
command = command.split(": ")
key = command[0]
value = int(command[1])
if key not in products:
products[key] = 0
products[key] += value
command = input()
print("Products in stock:")
for k, v in products.items():
print(... | products = {}
command = input()
while command != 'statistics':
command = command.split(': ')
key = command[0]
value = int(command[1])
if key not in products:
products[key] = 0
products[key] += value
command = input()
print('Products in stock:')
for (k, v) in products.items():
print(f... |
# Simple function to add values
def aFunction():
a = 1
b = 2
c = a + b
print(c)
return c
# simple loop to count up in a range
def aLoop():
count = 0
# for each item in the range
for item in range(0, 100):
print(count)
count = count + 1
return count... | def a_function():
a = 1
b = 2
c = a + b
print(c)
return c
def a_loop():
count = 0
for item in range(0, 100):
print(count)
count = count + 1
return count
def a_func_1(my_num):
result = a_func_2(my_num)
print(result)
return result
def a_func_2(var):
var +... |
# taxes.tests
# Tax tests
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Sat Apr 14 16:36:54 2018 -0400
#
# ID: tests.py [20315d2] benjamin@bengfort.com $
"""
Tax tests
"""
##########################################################################
## Imports
########################################... | """
Tax tests
""" |
#!/usr/bin/python
# 1. Retourner VRAI si N est parfait, faux sinon
# 2. Afficher la liste des nombres parfait compris entre 1 et 10 000
def est_parfait(n):
somme = 0
for i in range(1, n):
if n % i == 0:
somme += i
if somme == n:
return True
else:
return False
fo... | def est_parfait(n):
somme = 0
for i in range(1, n):
if n % i == 0:
somme += i
if somme == n:
return True
else:
return False
for i in range(10000):
if est_parfait(i):
print(i) |
class Credentials(object):
@staticmethod
def refresh(request, **kwargs):
pass
@property
def token(self):
return "PASSWORD"
def default(scopes: list, **kwargs):
return Credentials(), "myproject"
class Request(object):
pass
| class Credentials(object):
@staticmethod
def refresh(request, **kwargs):
pass
@property
def token(self):
return 'PASSWORD'
def default(scopes: list, **kwargs):
return (credentials(), 'myproject')
class Request(object):
pass |
xCoordinate = [1,2,3,4,5,6,7,8,9,10]
xCdt = [1,2,3,4,5,6,7,8,9,10]
def setup():
size(500,500)
smooth()
noStroke()
for i in range(len(xCoordinate)):
xCoordinate[i] = 35*i + 90
for j in range(len(xCdt)):
xCdt[j] = 35*j + 90
def draw():
background(50)
for j in range(len(xCdt)):... | x_coordinate = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x_cdt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def setup():
size(500, 500)
smooth()
no_stroke()
for i in range(len(xCoordinate)):
xCoordinate[i] = 35 * i + 90
for j in range(len(xCdt)):
xCdt[j] = 35 * j + 90
def draw():
background(50)
... |
class LostFocusEventManager(WeakEventManager):
""" Provides a System.Windows.WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the System.Windows.UIElement.LostFocus or System.Windows.ContentElement.LostFocus events. """
@staticmethod
def AddHandler(sour... | class Lostfocuseventmanager(WeakEventManager):
""" Provides a System.Windows.WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the System.Windows.UIElement.LostFocus or System.Windows.ContentElement.LostFocus events. """
@staticmethod
def add_hand... |
#TeamLeague
class Team:
def __init__(self, owner, value, id1, name):
self.owner = owner
self.value = value
self.id1 = id1
self.name = name
class League:
def __init__(self, team_list, league):
self.league = league
self.team_list = team_list
def find_minimum_t... | class Team:
def __init__(self, owner, value, id1, name):
self.owner = owner
self.value = value
self.id1 = id1
self.name = name
class League:
def __init__(self, team_list, league):
self.league = league
self.team_list = team_list
def find_minimum_team_by__id... |
## Solution Challenge 10
def data_url(country):
'''
Function to build url for data retrieval
'''
BASE_URL = "http://berkeleyearth.lbl.gov/auto/Regional/TAVG/Text/"
SUFFIX_URL = "-TAVG-Trend.txt"
return(BASE_URL + country + SUFFIX_URL) | def data_url(country):
"""
Function to build url for data retrieval
"""
base_url = 'http://berkeleyearth.lbl.gov/auto/Regional/TAVG/Text/'
suffix_url = '-TAVG-Trend.txt'
return BASE_URL + country + SUFFIX_URL |
"""
The hyperexponentiation of a number
"""
def pow_mod_recursive(a, x, mod):
if x == 0 or x == 1:
return a ** x % mod
elif x % 2 == 0:
return pow_mod_recursive(a, x//2, mod) ** 2 % mod
else:
return a* pow_mod_recursive(a, x//2, mod)** 2 % mod
def pow_mod(a, x, mod):
pow_v... | """
The hyperexponentiation of a number
"""
def pow_mod_recursive(a, x, mod):
if x == 0 or x == 1:
return a ** x % mod
elif x % 2 == 0:
return pow_mod_recursive(a, x // 2, mod) ** 2 % mod
else:
return a * pow_mod_recursive(a, x // 2, mod) ** 2 % mod
def pow_mod(a, x, mod):
pow_... |
"""
ensemble module
"""
class BaseEnsembler:
def __init__(self, *args, **kwargs):
super().__init__()
def fit(self, predictions, label, identifiers, feval, *args, **kwargs):
pass
def ensemble(self, predictions, identifiers, *args, **kwargs):
pass
@classmethod
def build_en... | """
ensemble module
"""
class Baseensembler:
def __init__(self, *args, **kwargs):
super().__init__()
def fit(self, predictions, label, identifiers, feval, *args, **kwargs):
pass
def ensemble(self, predictions, identifiers, *args, **kwargs):
pass
@classmethod
def build_en... |
class Solution(object):
def hammingDistance(self, x, y):
cnt = 0
n=x^y
while n>0:
cnt += 1
n = n&(n-1)
return cnt
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: i... | class Solution(object):
def hamming_distance(self, x, y):
cnt = 0
n = x ^ y
while n > 0:
cnt += 1
n = n & n - 1
return cnt
class Solution(object):
def hamming_distance(self, x, y):
"""
:type x: int
:type y: int
:rtype: in... |
#
# PySNMP MIB module RFC1382-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/RFC1382-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:26:33 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( Octe... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection) ... |
def main(filepath):
with open(filepath) as file:
rows = [int(x.strip()) for x in file.readlines()]
rows.append(0)
rows.sort()
rows.append(rows[-1]+3)
current_volts = 0
one_volts = 0
three_volts = 0
for i in range(len(rows)):
if ro... | def main(filepath):
with open(filepath) as file:
rows = [int(x.strip()) for x in file.readlines()]
rows.append(0)
rows.sort()
rows.append(rows[-1] + 3)
current_volts = 0
one_volts = 0
three_volts = 0
for i in range(len(rows)):
if rows[i] - ... |
def find_min_max(nums):
if nums[0]<nums[1]:
min = nums[0]
max = nums[1]
else:
min = nums[1]
max = nums[0]
for i in range(len(nums)-2):
if nums[i+2] < min:
min = nums[i+2]
elif nums[i+2] > max:
max = nums[i+2]
return (min, max)
de... | def find_min_max(nums):
if nums[0] < nums[1]:
min = nums[0]
max = nums[1]
else:
min = nums[1]
max = nums[0]
for i in range(len(nums) - 2):
if nums[i + 2] < min:
min = nums[i + 2]
elif nums[i + 2] > max:
max = nums[i + 2]
return (min... |
def daily_sleeping_hours(hours=7):
return hours
print(daily_sleeping_hours(10))
print(daily_sleeping_hours()) | def daily_sleeping_hours(hours=7):
return hours
print(daily_sleeping_hours(10))
print(daily_sleeping_hours()) |
x=1
grenais = 0
inter = 0
gremio = 0
empate = 0
while x == 1:
y = input().split()
a,b=y
a=int(a)
b=int(b)
grenais = grenais + 1
if a > b:
inter = inter + 1
if a < b:
gremio = gremio + 1
if a == b:
empate = empate + 1
while True:
x = int(input('Novo g... | x = 1
grenais = 0
inter = 0
gremio = 0
empate = 0
while x == 1:
y = input().split()
(a, b) = y
a = int(a)
b = int(b)
grenais = grenais + 1
if a > b:
inter = inter + 1
if a < b:
gremio = gremio + 1
if a == b:
empate = empate + 1
while True:
x = int(inpu... |
#
# PySNMP MIB module SNR-ERD-PRO-Mini (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNR-ERD-PRO-Mini
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
class ComputeRank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for i, document in enumerate(documents, 1):
document[self.var_name] = i
return documents
def test_rank():
plugin = ComputeRank("rank")
docs = [{}, {}]... | class Computerank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for (i, document) in enumerate(documents, 1):
document[self.var_name] = i
return documents
def test_rank():
plugin = compute_rank('rank')
docs = [{}, {}... |
'''
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers
in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order.
However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible... | """
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers
in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order.
However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible... |
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
count = dict()
for words in cpdomains:
times, cpdomain = words.split(' ')
times = int(times)
keys = cpdomain.split('.')
... | class Solution:
def subdomain_visits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
count = dict()
for words in cpdomains:
(times, cpdomain) = words.split(' ')
times = int(times)
keys = cpdomain.split('.')
... |
ENTITY = "<<Entity>>"
REL = 'Rel/'
ATTR = 'Attr/'
SOME = 'SOME'
ALL = 'ALL'
GRAPH = 'GRAPH'
LIST = 'LIST'
TEXT = 'TEXT'
SHAPE = 'SHAPE'
SOME_LIMIT = 15
EXACT_MATCH = 'EXACT_MATCH'
REGEX_MATCH = 'REGEX_MATCH'
SYNONYM_MATCH = 'SYNONYM_MATCH' | entity = '<<Entity>>'
rel = 'Rel/'
attr = 'Attr/'
some = 'SOME'
all = 'ALL'
graph = 'GRAPH'
list = 'LIST'
text = 'TEXT'
shape = 'SHAPE'
some_limit = 15
exact_match = 'EXACT_MATCH'
regex_match = 'REGEX_MATCH'
synonym_match = 'SYNONYM_MATCH' |
def calculate(arr, index=0):
back = - 1 - index
if arr[index] != arr[back]:
return False
elif abs(back) == (index+1):
return True
return calculate(arr, index+1)
arr = [int(i) for i in input().split()]
print(calculate(arr))
| def calculate(arr, index=0):
back = -1 - index
if arr[index] != arr[back]:
return False
elif abs(back) == index + 1:
return True
return calculate(arr, index + 1)
arr = [int(i) for i in input().split()]
print(calculate(arr)) |
"""
Find the parant and the node to be deleted. [0]
Deleting the node means replacing its reference by something else. [1]
For the node to be deleted, if it only has no child, just remove it from the parent. Return None. [2]
If it has one child, return the child. So its parent will directly connect to its child. [3]
... | """
Find the parant and the node to be deleted. [0]
Deleting the node means replacing its reference by something else. [1]
For the node to be deleted, if it only has no child, just remove it from the parent. Return None. [2]
If it has one child, return the child. So its parent will directly connect to its child. [3]
... |
class IberException(Exception):
pass
class ResponseException(IberException):
def __init__(self, status_code):
super().__init__("Response error, code: {}".format(status_code))
class LoginException(IberException):
def __init__(self, username):
super().__init__(f'Unable to log in with user ... | class Iberexception(Exception):
pass
class Responseexception(IberException):
def __init__(self, status_code):
super().__init__('Response error, code: {}'.format(status_code))
class Loginexception(IberException):
def __init__(self, username):
super().__init__(f'Unable to log in with user ... |
v = 6.0 # velocity of seismic waves [km/s]
def earthquake_epicenter(x1, y1, t1, x2, y2, t2, x3, y3, t3):
x = 0
y = 0
# Your code goes here!
return x, y
| v = 6.0
def earthquake_epicenter(x1, y1, t1, x2, y2, t2, x3, y3, t3):
x = 0
y = 0
return (x, y) |
class Logi:
def __init__(self, email, password):
self.email = email
self.password = password
| class Logi:
def __init__(self, email, password):
self.email = email
self.password = password |
class StringFormatFlags(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies the display and layout information for text strings.
enum (flags) StringFormatFlags,values: DirectionRightToLeft (1),DirectionVertical (2),DisplayFormatControl (32),FitBlackBox (4),LineLimit (8192),MeasureTrailingSpace... | class Stringformatflags(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies the display and layout information for text strings.
enum (flags) StringFormatFlags,values: DirectionRightToLeft (1),DirectionVertical (2),DisplayFormatControl (32),FitBlackBox (4),LineLimit (8192),MeasureTrailingSpaces (204... |
requestDict = {
'instances':
[
{
"Lat": 37.4434774, "Long": -122.1652269,
"Altitude": 21.0, "Date_": "7/4/17",
"Time_": "23:37:25", "dt_": "7/4/17 23:37"
#driving meet conjestion
}... | request_dict = {'instances': [{'Lat': 37.4434774, 'Long': -122.1652269, 'Altitude': 21.0, 'Date_': '7/4/17', 'Time_': '23:37:25', 'dt_': '7/4/17 23:37'}, {'Lat': 37.429302, 'Long': -122.16145, 'Altitude': 20.0, 'Date_': '7/4/17', 'Time_': '09:37:25', 'dt_': '7/4/17 09:37'}]} |
#!/usr/local/bin/python3
class Object(object):
def __init__(self, id):
self.id = id
self.children = []
self.parent = None
root = Object("COM")
objects = {"COM": root}
def get_object(id):
if id not in objects:
objects[id] = Object(id)
return objects[id]
with open("input.tx... | class Object(object):
def __init__(self, id):
self.id = id
self.children = []
self.parent = None
root = object('COM')
objects = {'COM': root}
def get_object(id):
if id not in objects:
objects[id] = object(id)
return objects[id]
with open('input.txt') as f:
for line in f... |
def fizzbuzz(num):
if (num >= 0 and num % 3 == 0 and num % 5 == 0):
return "Fizz Buzz"
if (num >= 0 and num % 3 == 0):
return "Fizz"
if (num >= 0 and num % 5 == 0):
return "Buzz"
if (num >= 0):
return ""
| def fizzbuzz(num):
if num >= 0 and num % 3 == 0 and (num % 5 == 0):
return 'Fizz Buzz'
if num >= 0 and num % 3 == 0:
return 'Fizz'
if num >= 0 and num % 5 == 0:
return 'Buzz'
if num >= 0:
return '' |
dataset_paths = {
'ffhq': '',
'celeba_test': '',
'cars_train': '',
'cars_test': '',
'church_train': '',
'church_test': '',
'horse_train': '',
'horse_test': '',
'afhq_wild_train': '',
'afhq_wild_test': '',
'font_train': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops/pr',
'... | dataset_paths = {'ffhq': '', 'celeba_test': '', 'cars_train': '', 'cars_test': '', 'church_train': '', 'church_test': '', 'horse_train': '', 'horse_test': '', 'afhq_wild_train': '', 'afhq_wild_test': '', 'font_train': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops/pr', 'font_test': '/mnt/... |
def v(kod):
if (k == len(kod)):
print(' '.join(kod))
return
if (len(kod) != 0):
for i in range(int(kod[-1]) + 1, n + 1):
if (str(i) not in kod):
gg = kod.copy()
gg.append(str(i))
v(gg)
else:
for i in range... | def v(kod):
if k == len(kod):
print(' '.join(kod))
return
if len(kod) != 0:
for i in range(int(kod[-1]) + 1, n + 1):
if str(i) not in kod:
gg = kod.copy()
gg.append(str(i))
v(gg)
else:
for i in range(1, n + 1):
... |
'''
(0-1 Knapsack) example
The example solves the 0/1 Knapsack Problem:
how we get the maximum value, given our knapsack just can hold a maximum weight of w,
while the value of the i-th item is a1[i], and the weight of the i-th item is a2[i]?
i = total item
w = total weigh of knapsack can carry
'''
# a1: item value... | """
(0-1 Knapsack) example
The example solves the 0/1 Knapsack Problem:
how we get the maximum value, given our knapsack just can hold a maximum weight of w,
while the value of the i-th item is a1[i], and the weight of the i-th item is a2[i]?
i = total item
w = total weigh of knapsack can carry
"""
a1 = [100, 70, 50... |
administrator_user_id = 403569083402158090
reaction_message_ids = [832010993542365184, 573059396259807232]
current_year = 2021
| administrator_user_id = 403569083402158090
reaction_message_ids = [832010993542365184, 573059396259807232]
current_year = 2021 |
class NoneTypeFont(Exception):
pass
class PortraitBoolError(Exception):
pass
class NoneStringObject(Exception):
pass
class BMPvalidationError(Exception):
pass
| class Nonetypefont(Exception):
pass
class Portraitboolerror(Exception):
pass
class Nonestringobject(Exception):
pass
class Bmpvalidationerror(Exception):
pass |
default_values = {
'mode': 'train',
'net': 'resnet32_cifar',
'device': 'cuda:0',
'num_epochs': 300,
'activation_type': 'deepBspline_explicit_linear',
'spline_init': 'leaky_relu',
'spline_size': 51,
'spline_range': 4,
'save_memory': False,
'knot_threshold': 0.,
'num_hidden_lay... | default_values = {'mode': 'train', 'net': 'resnet32_cifar', 'device': 'cuda:0', 'num_epochs': 300, 'activation_type': 'deepBspline_explicit_linear', 'spline_init': 'leaky_relu', 'spline_size': 51, 'spline_range': 4, 'save_memory': False, 'knot_threshold': 0.0, 'num_hidden_layers': 2, 'num_hidden_neurons': 4, 'lipschitz... |
class Solution:
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
k=1
m=0
for i in range(1,len(nums)):
if nums[i]>nums[i-1]:
k+=1
else:
... | class Solution:
def find_length_of_lcis(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
k = 1
m = 0
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
k += 1
e... |
NONE = u'none'
OTHER = u'other'
PRIMARY = u'primary'
JUNIOR_SECONDARY = u'junior_secondary'
SECONDARY = u'secondary'
ASSOCIATES = u'associates'
BACHELORS = u'bachelors'
MASTERS = u'masters'
DOCTORATE = u'doctorate'
| none = u'none'
other = u'other'
primary = u'primary'
junior_secondary = u'junior_secondary'
secondary = u'secondary'
associates = u'associates'
bachelors = u'bachelors'
masters = u'masters'
doctorate = u'doctorate' |
class SteepshotBotError(Exception):
msg = {}
def get_msg(self, locale: str = 'en') -> str:
return self.msg.get(locale, self.msg.get('en', 'Some error occurred: ')) + str(self)
class SteepshotServerError(SteepshotBotError):
msg = {
'en': 'Some Steepshot error occurred: '
}
class Stee... | class Steepshotboterror(Exception):
msg = {}
def get_msg(self, locale: str='en') -> str:
return self.msg.get(locale, self.msg.get('en', 'Some error occurred: ')) + str(self)
class Steepshotservererror(SteepshotBotError):
msg = {'en': 'Some Steepshot error occurred: '}
class Steemerror(SteepshotBo... |
class Instrument:
insId: int
name: str
urlName: str
instrument: int
isin: str
ticker: str
yahoo: str
sectorId: int
marketId: int
branchId: int
countryId: int
listingDate: str
def __init__(self, insId, name, urlName, instrument, isin, ticker, yahoo, sectorId, marketId... | class Instrument:
ins_id: int
name: str
url_name: str
instrument: int
isin: str
ticker: str
yahoo: str
sector_id: int
market_id: int
branch_id: int
country_id: int
listing_date: str
def __init__(self, insId, name, urlName, instrument, isin, ticker, yahoo, sectorId, m... |
class WeightedUnionFind(object):
def __init__(self, n):
self.n = n
self.parents = range(n)
self.sizes = [1] * n
def find(self, p):
while p != self.parents[p]:
p = self.parents[p]
return p
def is_connected(self, p, q):
return self.find(p) == self... | class Weightedunionfind(object):
def __init__(self, n):
self.n = n
self.parents = range(n)
self.sizes = [1] * n
def find(self, p):
while p != self.parents[p]:
p = self.parents[p]
return p
def is_connected(self, p, q):
return self.find(p) == self... |
num = int(input("Enter a number: "))
iter_num = 0
pwr = 0
if num == 0:
root = 0
else:
root = 1
while root**pwr != num and root < num:
while pwr < 6:
iter_num += 1
if root**pwr == num:
print(root, "^", pwr, sep="")
break
pwr += 1
if root**pwr == num:
break
else:
pwr = 0
... | num = int(input('Enter a number: '))
iter_num = 0
pwr = 0
if num == 0:
root = 0
else:
root = 1
while root ** pwr != num and root < num:
while pwr < 6:
iter_num += 1
if root ** pwr == num:
print(root, '^', pwr, sep='')
break
pwr += 1
if root ** pwr == num:
... |
def dict_recursive_bypass(dictionary: dict, on_node: callable) -> dict:
"""
Recursive bypass dictionary
:param dictionary:
:param on_node: callable for every node, that get value of dict end node as parameters
"""
res = {}
for k, v in dictionary.items():
if isinstance(v, dict):
... | def dict_recursive_bypass(dictionary: dict, on_node: callable) -> dict:
"""
Recursive bypass dictionary
:param dictionary:
:param on_node: callable for every node, that get value of dict end node as parameters
"""
res = {}
for (k, v) in dictionary.items():
if isinstance(v, dict):
... |
expected_output = {
"route-information": {
"route-table": {
"active-route-count": "1250009",
"destination-count": "1250009",
"hidden-route-count": "0",
"holddown-route-count": "0",
"rt": {
"rt-announced-count": "1",
... | expected_output = {'route-information': {'route-table': {'active-route-count': '1250009', 'destination-count': '1250009', 'hidden-route-count': '0', 'holddown-route-count': '0', 'rt': {'rt-announced-count': '1', 'rt-destination': '10.55.0.0', 'rt-entry': {'active-tag': '*', 'age': {'#text': '4:32'}, 'announce-bits': '2... |
""" Summation puzzle
Example:
pot + pan = bib
dog + cat = pig
boy+ girl = baby
"""
def puzzle_solve(k, S, U, solutionSeq): # we have also passed puzzles solution samples to verify the configuarion
""" Input: an integer k : length of the subset made by combination of letters,
S: Sequence of unique letters ... | """ Summation puzzle
Example:
pot + pan = bib
dog + cat = pig
boy+ girl = baby
"""
def puzzle_solve(k, S, U, solutionSeq):
""" Input: an integer k : length of the subset made by combination of letters,
S: Sequence of unique letters , U: Universal Set of unique letters Example: {a, b, c} """
for element i... |
# class MyHashSet:
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self._range = 10000
# self.list = [[]]*self._range
# def _hash(self, key: int) -> int:
# return key%self._range
# def _search(self, key: int) -> int:
#... | class Myhashset(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.keyRange = 769
self.bucketArray = [bucket() for i in range(self.keyRange)]
def _hash(self, key):
return key % self.keyRange
def add(self, key):
if not sel... |
SERVER_EMAIL = 'SERVER_EMAIL'
SERVER_PASSWORD = 'SERVER_PASSWORD'
WATCHED = {
'service': ['service'],
'process': ['process'],
}
NOTIFICATION_DETAILS = {
'service': [
{
'identifiers': ['identifiers'],
'to_emails': ['nimesh.aug11@gmail.com'],
'subject': 'subject'... | server_email = 'SERVER_EMAIL'
server_password = 'SERVER_PASSWORD'
watched = {'service': ['service'], 'process': ['process']}
notification_details = {'service': [{'identifiers': ['identifiers'], 'to_emails': ['nimesh.aug11@gmail.com'], 'subject': 'subject', 'body': 'body'}], 'process': [{'identifiers': ['identifiers'], ... |
print("HelloWorld")
print(len("HelloWorld"))
a_string = "Hello"
b_string = "World"
print("a_string + b_string: ", a_string+b_string)
c_string = "abcdefghijklmnopqrstuvwxyz"
print("num of letters from a to z", len(c_string))
print(c_string[:3]) #abc
print(c_string[23:]) #xyz
#step count reverse
print(c_string[::-1])
#st... | print('HelloWorld')
print(len('HelloWorld'))
a_string = 'Hello'
b_string = 'World'
print('a_string + b_string: ', a_string + b_string)
c_string = 'abcdefghijklmnopqrstuvwxyz'
print('num of letters from a to z', len(c_string))
print(c_string[:3])
print(c_string[23:])
print(c_string[::-1])
print(c_string[::2])
print(c_st... |
def substituter(seq, substitutions):
for item in seq:
if item in substitutions:
yield substitutions[item]
else:
yield item
| def substituter(seq, substitutions):
for item in seq:
if item in substitutions:
yield substitutions[item]
else:
yield item |
a = input()
b = input()
ans = 0
while True:
s = a.find(b)
if s < 0:
break
ans += 1
a = a[s+len(b):]
print(ans)
| a = input()
b = input()
ans = 0
while True:
s = a.find(b)
if s < 0:
break
ans += 1
a = a[s + len(b):]
print(ans) |
"""Externalized strings for better structure and easier localization"""
setup_greeting = """
Dwarf - First run configuration
Insert your bot's token, or enter 'cancel' to cancel the setup:"""
not_a_token = "Invalid input. Restart Dwarf and repeat the configuration process."
choose_prefix = """Choose a prefix. A pr... | """Externalized strings for better structure and easier localization"""
setup_greeting = "\nDwarf - First run configuration\n\nInsert your bot's token, or enter 'cancel' to cancel the setup:"
not_a_token = 'Invalid input. Restart Dwarf and repeat the configuration process.'
choose_prefix = 'Choose a prefix. A prefix is... |
# Lecture 5, Problem 9
def semordnilapWrapper(str1, str2):
# A single-length string cannot be semordnilap.
if len(str1) == 1 or len(str2) == 1:
return False
# Equal strings cannot be semordnilap.
if str1 == str2:
return False
return semordnilap(str1, str2)
def semordnilap(str1, s... | def semordnilap_wrapper(str1, str2):
if len(str1) == 1 or len(str2) == 1:
return False
if str1 == str2:
return False
return semordnilap(str1, str2)
def semordnilap(str1, str2):
"""
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap;
... |
#!/usr/bin/env python
# Monitoring the Mem usage of a Sonicwall
# Herward Cooper <coops@fawk.eu> - 2012
# Uses OID 1.3.6.1.4.1.8741.1.3.1.4.0
sonicwall_mem_default_values = (35, 40)
def inventory_sonicwall_mem(checkname, info):
inventory=[]
inventory.append( (None, None, "sonicwall_mem_default_values") )
... | sonicwall_mem_default_values = (35, 40)
def inventory_sonicwall_mem(checkname, info):
inventory = []
inventory.append((None, None, 'sonicwall_mem_default_values'))
return inventory
def check_sonicwall_mem(item, params, info):
(warn, crit) = params
state = int(info[0][0])
perfdata = [('cpu', st... |
title = 'Projects'
class Card:
def __init__(self, section, url, name, description, image):
self.section = section; self.url = url;
self.image = image; self.name = name; self.description = description
cards = [
Card('2018', 'resources/projects/awg_highres.jpg', 'Automatic Nanomanipulation Platform'... | title = 'Projects'
class Card:
def __init__(self, section, url, name, description, image):
self.section = section
self.url = url
self.image = image
self.name = name
self.description = description
cards = [card('2018', 'resources/projects/awg_highres.jpg', 'Automatic Nanoman... |
class LastPassError(Exception):
def __init__(self, output):
self.output = output
class CliNotInstalledException(Exception):
pass
| class Lastpasserror(Exception):
def __init__(self, output):
self.output = output
class Clinotinstalledexception(Exception):
pass |
def grad_tmp(temp, lat: np.ndarray, lon: np.ndarray) -> np.ndarray:
"""grad_eqv_ptntl_tmp.
calcureta gradient of temperature [K/100km]
Args:
eqv_ptntl_t:
lat (np.ndarray): lat
lon (np.ndarray): lon
Returns:
np.ndarray:
"""
# horizontal equivalent_potential_temp... | def grad_tmp(temp, lat: np.ndarray, lon: np.ndarray) -> np.ndarray:
"""grad_eqv_ptntl_tmp.
calcureta gradient of temperature [K/100km]
Args:
eqv_ptntl_t:
lat (np.ndarray): lat
lon (np.ndarray): lon
Returns:
np.ndarray:
"""
de_dx = [np.array((temp[i][j] - temp[i]... |
n=int(input())
arr=[int(x) for x in input().split()]
brr=[int(x) for x in input().split()]
my_list=[]
for i in arr[1:]:
my_list.append(i)
for i in brr[1:]:
my_list.append(i)
for i in range(1,n+1):
if i in my_list:
if i == n:
print("I become the guy.")
break
else:
... | n = int(input())
arr = [int(x) for x in input().split()]
brr = [int(x) for x in input().split()]
my_list = []
for i in arr[1:]:
my_list.append(i)
for i in brr[1:]:
my_list.append(i)
for i in range(1, n + 1):
if i in my_list:
if i == n:
print('I become the guy.')
break
... |
'''
Need 3 temporary variables to find the longest substring: start, maxLength,
and usedChars.
Start by walking through string of characters, one at a time.
Check if the current character is in the usedChars map, this would mean we
have already seen it and have stored it's corresponding index.
If it's in there and the ... | """
Need 3 temporary variables to find the longest substring: start, maxLength,
and usedChars.
Start by walking through string of characters, one at a time.
Check if the current character is in the usedChars map, this would mean we
have already seen it and have stored it's corresponding index.
If it's in there and the ... |
class APICONTROLLERNAMEController(apicontrollersbase.APIOperationBase):
def __init__(self, apirequest):
super(APICONTROLLERNAMEController, self).__init__(apirequest)
return
def validaterequest(self):
logging.debug('performing custom validation..')
#validate required ... | class Apicontrollernamecontroller(apicontrollersbase.APIOperationBase):
def __init__(self, apirequest):
super(APICONTROLLERNAMEController, self).__init__(apirequest)
return
def validaterequest(self):
logging.debug('performing custom validation..')
return
def getrequesttype... |
class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
# write your code here
if nums == None or len(nums) <= 1:
return
pl = 0
pr = len(nums) - 1
i = 0
while i <= pr:
if... | class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sort_colors(self, nums):
if nums == None or len(nums) <= 1:
return
pl = 0
pr = len(nums) - 1
i = 0
while i <= pr:
if nums[i] == 0:
... |
# Leo colorizer control file for c mode.
# This file is in the public domain.
# Properties for c mode.
properties = {
"commentEnd": "*/",
"commentStart": "/*",
"doubleBracketIndent": "false",
"indentCloseBrackets": "}",
"indentNextLine": "\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|... | properties = {'commentEnd': '*/', 'commentStart': '/*', 'doubleBracketIndent': 'false', 'indentCloseBrackets': '}', 'indentNextLine': '\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)', 'indentOpenBrackets': '{', 'lineComment': '//', 'lineUpClosingBracket': 'true', 'wordBreakChars': ',+-=<>/?^... |
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
intervals.sort(key = lambda interval : interval[1])
res = 0
prev = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] < prev:
res +=1
else:
prev = intervals[i][1... | class Solution:
def erase_overlap_intervals(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
intervals.sort(key=lambda interval: interval[1])
res = 0
prev = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] < pr... |
#https://www.interviewbit.com/problems/max-distance/
def maximumGap(A):
left = [A[0]]
right = [A[-1]]
n = len(A)
for i in range(1,n):
left.append(min(left[-1], A[i]))
for i in range(n-2, -1, -1):
right.insert(0, max(right[0], A[i]))
i,j,gap = 0, 0, -1
while (i < n and j < n):... | def maximum_gap(A):
left = [A[0]]
right = [A[-1]]
n = len(A)
for i in range(1, n):
left.append(min(left[-1], A[i]))
for i in range(n - 2, -1, -1):
right.insert(0, max(right[0], A[i]))
(i, j, gap) = (0, 0, -1)
while i < n and j < n:
if left[i] < right[j]:
g... |
'''
Created on May 24, 2012
@author: newatv2user
'''
PIANO_RPC_HOST = "tuner.pandora.com"
PIANO_ONE_HOST = "internal-tuner.pandora.com"
PIANO_RPC_PATH = "/services/json/?"
class PianoUserInfo:
def __init__(self):
self.listenerId = ''
self.authToken = ''
class PianoStation:
def __init... | """
Created on May 24, 2012
@author: newatv2user
"""
piano_rpc_host = 'tuner.pandora.com'
piano_one_host = 'internal-tuner.pandora.com'
piano_rpc_path = '/services/json/?'
class Pianouserinfo:
def __init__(self):
self.listenerId = ''
self.authToken = ''
class Pianostation:
def __init__(self... |
class Emplacement:
"""
documentation
"""
def __init__(self, id, line, n):
self.id = id
line = line.split(' ')
distances = {}
i = 0
for elt in line:
if elt != '':
i+=1
if i != id:
distances[i] = int(e... | class Emplacement:
"""
documentation
"""
def __init__(self, id, line, n):
self.id = id
line = line.split(' ')
distances = {}
i = 0
for elt in line:
if elt != '':
i += 1
if i != id:
distances[i] = int... |
"""
Streamlined python project setup and build system.
"""
__version__ = "0.2"
DESCRIPTION = __doc__
__all__ = ['__init__', '__main__', 'parsers']
| """
Streamlined python project setup and build system.
"""
__version__ = '0.2'
description = __doc__
__all__ = ['__init__', '__main__', 'parsers'] |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... | class Error(object):
@staticmethod
def exceeded_maximum_metric_capacity():
return 'ErrorExceededMaximumMetricCapacity'
@staticmethod
def missing_attribute():
return 'ErrorMissingAttributes'
@staticmethod
def is_not_lower():
return 'ErrorNotLowerCase'
@staticmethod... |
class Singleton(type):
def __new__(meta, name, bases, attrs):
attrs["_instance"] = None
return super().__new__(meta, name, bases, attrs)
def __call__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
| class Singleton(type):
def __new__(meta, name, bases, attrs):
attrs['_instance'] = None
return super().__new__(meta, name, bases, attrs)
def __call__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: template_deploy
short_description: Manage TemplateDeploy objects of ConfigurationTemplates
description:
- Deploys... | documentation = "\n---\nmodule: template_deploy\nshort_description: Manage TemplateDeploy objects of ConfigurationTemplates\ndescription:\n- Deploys a template.\n- Returns the status of a deployed template.\nversion_added: '1.0.0'\nauthor: Rafael Campos (@racampos)\noptions:\n forcePushTemplate:\n description:\n ... |
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/gaogaotiantian/pygictower/blob/master/NOTICE
__version__ = "0.0.1"
| __version__ = '0.0.1' |
def countBits(n: int) -> list[int]:
result = [0]
for i in range(1,n+1):
count = 0
test = ~(i - 1)
while test & 1 == 0:
test >>= 1
count += 1
result.append(result[i-1] - count + 1)
return result | def count_bits(n: int) -> list[int]:
result = [0]
for i in range(1, n + 1):
count = 0
test = ~(i - 1)
while test & 1 == 0:
test >>= 1
count += 1
result.append(result[i - 1] - count + 1)
return result |
class Predicate(object):
def test(self, obj):
raise NotImplementedError()
def __call__(self, obj):
return self.test(obj)
def __eq__(self, obj):
return self.test(obj)
def __ne__(self, obj):
return not self == obj
def __and__(self, other):
return And(self, ... | class Predicate(object):
def test(self, obj):
raise not_implemented_error()
def __call__(self, obj):
return self.test(obj)
def __eq__(self, obj):
return self.test(obj)
def __ne__(self, obj):
return not self == obj
def __and__(self, other):
return and(self... |
# Copyright 2018 Jianfei Gao, Leonardo Teixeira, Bruno Ribeiro.
#
# 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
#
# Unle... | """Summer Time Period
Set summer time period for stratux data to shift time zone.
"""
summer = {2017: ((3, 12), (11, 5)), 2018: ((3, 11), (11, 4)), 2019: ((3, 10), (11, 3))}
'Minimum Ground Speed\n\nSet minimum ground speed, above which will be regarded as flight.\nThe default class embedded value is 0.0005, and is e... |
def increment(dictionary, k1, k2):
"""
dictionary[k1][k2]++
:param dictionary: Dictionary of dictionary of integers.
:param k1: First key.
:param k2: Second key.
:return: same dictionary with incremented [k1][k2]
"""
if k1 not in dictionary:
dictionary[k1] = {}
if 0 not in ... | def increment(dictionary, k1, k2):
"""
dictionary[k1][k2]++
:param dictionary: Dictionary of dictionary of integers.
:param k1: First key.
:param k2: Second key.
:return: same dictionary with incremented [k1][k2]
"""
if k1 not in dictionary:
dictionary[k1] = {}
if 0 not in d... |
# Solution to Advent of Code 2020 day 6
# Read data
with open("input.txt") as inFile:
groups = inFile.read().split("\n\n")
# Part 1
yesAnswers = sum([len(set(group.replace("\n", ""))) for group in groups])
print("Solution for part 1:", yesAnswers)
# Part 2
yesAnswers = 0
for group in groups:
persons = group.... | with open('input.txt') as in_file:
groups = inFile.read().split('\n\n')
yes_answers = sum([len(set(group.replace('\n', ''))) for group in groups])
print('Solution for part 1:', yesAnswers)
yes_answers = 0
for group in groups:
persons = group.split('\n')
same_answers = set(persons[0])
for person in perso... |
DOCARRAY_PULL_NAME = "fashion-product-images-clip-all"
DATA_DIR = "../data/images" # Where are the files?
CSV_FILE = "../data/styles.csv" # Where's the metadata?
WORKSPACE_DIR = "../embeddings"
DIMS = 512 # This should be same shape as vector embedding
| docarray_pull_name = 'fashion-product-images-clip-all'
data_dir = '../data/images'
csv_file = '../data/styles.csv'
workspace_dir = '../embeddings'
dims = 512 |
def Instagram_scroller(driver,command):
print('In scroller function')
while True:
while True:
l0 = ["scroll up","call down","call don","scroll down","up","down","exit","roll down","croll down","roll up","croll up"]
if len([i for i in l0 if i in command]) != 0:
... | def instagram_scroller(driver, command):
print('In scroller function')
while True:
while True:
l0 = ['scroll up', 'call down', 'call don', 'scroll down', 'up', 'down', 'exit', 'roll down', 'croll down', 'roll up', 'croll up']
if len([i for i in l0 if i in command]) != 0:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def _is_tensor(x):
return hasattr(x, "__len__")
| def _is_tensor(x):
return hasattr(x, '__len__') |
# initial based on FreeCAD 0.17dev
#last edit: 2019-08
SourceFolder=[
("Base","Foundamental classes for FreeCAD",
"""import as FreeCAD in Python, see detailed description in later section"""),
("App","nonGUI code: Document, Property and DocumentObject",
"""import as FreeCAD in Python, see detailed description in late... | source_folder = [('Base', 'Foundamental classes for FreeCAD', 'import as FreeCAD in Python, see detailed description in later section'), ('App', 'nonGUI code: Document, Property and DocumentObject', 'import as FreeCAD in Python, see detailed description in later section'), ('Gui', 'Qt-based GUI code: macro-recording, ... |
"""
Manipulating lists
"""
# numlist = [1, 2, 3, 4, 5]
#
# print(numlist)
#
# numlist.reverse()
# print(numlist)
#
# numlist.sort()
# print(numlist)
#
# for num in numlist:
# print(str(num))
#
# mystring = 'julian'
# mystring_list = list(mystring)
# print(mystring_list)
#
# print(mystring_list[4])
# print(mystring... | """
Manipulating lists
"""
'\nImmutability(cannot be changed) and Tuples -- cannot be edited since are immutable\n'
'\nDictionaries\n-- no guarantee that the data will remain in order (they are unordered)\n' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.