content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def get_int(prompt, int_range):
i = 0
while True:
try:
i = int(input(prompt))
if i in int_range:
break
except ValueError:
pass
return i
| def get_int(prompt, int_range):
i = 0
while True:
try:
i = int(input(prompt))
if i in int_range:
break
except ValueError:
pass
return i |
fights = int(input())
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
shield_counter = 0
expenses = 0
for fight in range(1, fights + 1):
if fight % 2 == 0:
expenses += helmet_price
if fight % 3 == 0:
expenses +=... | fights = int(input())
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
shield_counter = 0
expenses = 0
for fight in range(1, fights + 1):
if fight % 2 == 0:
expenses += helmet_price
if fight % 3 == 0:
expenses += sword_price
... |
output = '''
Using interface 'wlan0'
bssid=14:d6:4d:ec:1e:88
ssid=AU Test Network
id=1
mode=station
pairwise_cipher=CCMP
group_cipher=CCMP
key_mgmt=WPA2-PSK
wpa_state=COMPLETED
ip_address=192.168.20.70
p2p_device_address=e0:cb:1d:3d:84:71
address=e0:cb:1d:3d:84:71
'''
mac = "e0:cb:1d:3d:84:71"
ip = "19... | output = "\nUsing interface 'wlan0'\nbssid=14:d6:4d:ec:1e:88\nssid=AU Test Network\nid=1\nmode=station\npairwise_cipher=CCMP\ngroup_cipher=CCMP\nkey_mgmt=WPA2-PSK\nwpa_state=COMPLETED\nip_address=192.168.20.70\np2p_device_address=e0:cb:1d:3d:84:71\naddress=e0:cb:1d:3d:84:71\n"
mac = 'e0:cb:1d:3d:84:71'
ip = '192.168.20... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
MONGO_URL = 'localhost'
MONGO_DB = 'huawei'
MONGO_TABLE = 'huawei_product'
| mongo_url = 'localhost'
mongo_db = 'huawei'
mongo_table = 'huawei_product' |
class Solution:
def minInsertions(self, s: str) -> int:
# use stack
stack = []
count = 0
i=0
while i < len(s):
if s[i] == '(':
stack.append(s[i])
i += 1
else:
# when facing empty stack
if ... | class Solution:
def min_insertions(self, s: str) -> int:
stack = []
count = 0
i = 0
while i < len(s):
if s[i] == '(':
stack.append(s[i])
i += 1
elif not stack:
if i + 1 < len(s) and s[i + 1] == ')':
... |
# ===============================================================================
# Copyright 2011 Jake Ross
#
# 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/licens... | """
Color generator methods
utility functions for creating a series of colors
"""
colors8i = dict(black=(0, 0, 0), red=(255, 0, 0), maroon=(127, 0, 0), yellow=(255, 255, 0), olive=(127, 127, 0), limegreen=(0, 255, 0), green=(0, 127, 0), gray=(127, 127, 127), aquamarine=(0, 255, 255), teal=(0, 127, 127), blue=(0, 0, 255... |
"""
:synopsis: Supported loss functions to use with NPU API for training.
.. moduleauthor:: Naval Bhandari <naval@neuro-ai.co.uk>
"""
# CrossEntropyLoss = "CrossEntropyLoss" #:
SparseCrossEntropyLoss = "SparseCrossEntropyLoss" #:
MSELoss = "MSELoss" #:
# CTCLoss = "CTCLoss" #:
L1Loss = "L1Loss" #:
# NLLLoss = "NL... | """
:synopsis: Supported loss functions to use with NPU API for training.
.. moduleauthor:: Naval Bhandari <naval@neuro-ai.co.uk>
"""
sparse_cross_entropy_loss = 'SparseCrossEntropyLoss'
mse_loss = 'MSELoss'
l1_loss = 'L1Loss'
smooth_l1_loss = 'SmoothL1Loss'
sigmoid_bce_loss = 'SigmoidBCELoss'
softmax_cross_entropy_los... |
def test_loop(num):
for a in num:
print ("a : ", a)
yield a
num = [1, 2, 3]
tl = test_loop(num)
for aa in tl:
print ("aa : ", aa)
| def test_loop(num):
for a in num:
print('a : ', a)
yield a
num = [1, 2, 3]
tl = test_loop(num)
for aa in tl:
print('aa : ', aa) |
class SchedulerNoam(object):
def __init__(self, warmup: int, model_size: int):
super().__init__()
self.warmup = warmup
self.model_size = model_size
def get_learning_rate(self, step: int):
step = max(1, step)
return self.model_size ** (-0.5) * min(step ** (-0.5), step ... | class Schedulernoam(object):
def __init__(self, warmup: int, model_size: int):
super().__init__()
self.warmup = warmup
self.model_size = model_size
def get_learning_rate(self, step: int):
step = max(1, step)
return self.model_size ** (-0.5) * min(step ** (-0.5), step * ... |
names=['yash','manan','jahnavi','rahul','rutu','Harry']
print(names[0])
names[1]='Manan Sanghavi'
print(names[1])
names[1]=3
print(names[1])
print(type(names))
| names = ['yash', 'manan', 'jahnavi', 'rahul', 'rutu', 'Harry']
print(names[0])
names[1] = 'Manan Sanghavi'
print(names[1])
names[1] = 3
print(names[1])
print(type(names)) |
class Solution:
def numFactoredBinaryTrees(self, A: 'List[int]') -> 'int':
ids = {x : i for i, x in enumerate(A)}
g = {x : [] for x in A}
A.sort()
for i in range(len(A)):
for j in range(len(A)):
if A[j] % A[i] == 0 and (A[j] // A[i]) in ids:
... | class Solution:
def num_factored_binary_trees(self, A: 'List[int]') -> 'int':
ids = {x: i for (i, x) in enumerate(A)}
g = {x: [] for x in A}
A.sort()
for i in range(len(A)):
for j in range(len(A)):
if A[j] % A[i] == 0 and A[j] // A[i] in ids:
... |
# Python does not have built-in support for Arrays,
# but Python Lists can be used instead.
def showArrays():
cars = ["Ford", "Volvo", "BMW"]
for car in cars:
print("Car Type : ", car)
# Add some new cars
cars.append("Mercedes")
cars.append("Maruti")
print("All cars : ", cars)... | def show_arrays():
cars = ['Ford', 'Volvo', 'BMW']
for car in cars:
print('Car Type : ', car)
cars.append('Mercedes')
cars.append('Maruti')
print('All cars : ', cars)
for i in cars:
car_index = cars.index(i)
print(i + '<=========>' + str(carIndex))
print('Size of the ... |
data = open("input.txt", "r").readlines()
fold = []
points = []
for line in data:
if len(line.strip()) == 0:
continue
elif line.startswith("fold"):
[x_or_y, value] = line.replace("fold along ", "").split("=")
fold.append((int(value) if x_or_y == "x" else 0,
int(valu... | data = open('input.txt', 'r').readlines()
fold = []
points = []
for line in data:
if len(line.strip()) == 0:
continue
elif line.startswith('fold'):
[x_or_y, value] = line.replace('fold along ', '').split('=')
fold.append((int(value) if x_or_y == 'x' else 0, int(value) if x_or_y == 'y' el... |
# #Q1
def eh_quadrada(mat):
null=[]
l=len(mat)
if mat == null or l == len(mat[0]):
return True
for i in range(l):
if mat[i] == null:
return True
else:
return False
#Q2
def conta_numero(n,mat):
ls=[]
l=len(mat)
if mat == ls:
return 0
for i i... | def eh_quadrada(mat):
null = []
l = len(mat)
if mat == null or l == len(mat[0]):
return True
for i in range(l):
if mat[i] == null:
return True
else:
return False
def conta_numero(n, mat):
ls = []
l = len(mat)
if mat == ls:
return 0
for i i... |
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
if val > root.val:
root.right = self.insertIntoBST(root.right, val)
else:
root.left = self.insertIntoBST(root.left, val)
r... | class Solution:
def insert_into_bst(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return tree_node(val)
if val > root.val:
root.right = self.insertIntoBST(root.right, val)
else:
root.left = self.insertIntoBST(root.left, val)
return roo... |
def MinerTransaction():
"""
:return:
"""
return b'\x00'
def IssueTransaction():
"""
:return:
"""
return b'\x01'
def ClaimTransaction():
"""
:return:
"""
return b'\x02'
def EnrollmentTransaction():
"""
:return:
"""
return b'\x20'
def VotingTran... | def miner_transaction():
"""
:return:
"""
return b'\x00'
def issue_transaction():
"""
:return:
"""
return b'\x01'
def claim_transaction():
"""
:return:
"""
return b'\x02'
def enrollment_transaction():
"""
:return:
"""
return b' '
def voting_transac... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Difference of Volumes of Cuboids
#Problem level: 8 kyu
def find_difference(a, b):
return abs((a[0]*a[1]*a[2])-(b[0]*b[1]*b[2]))
| def find_difference(a, b):
return abs(a[0] * a[1] * a[2] - b[0] * b[1] * b[2]) |
class AnalyticalRigidLinksOption(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies how Rigid Links will be made for the Analytical Model.
enum AnalyticalRigidLinksOption,values: Disabled (1),Enabled (0),FromColumn (2)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==... | class Analyticalrigidlinksoption(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies how Rigid Links will be made for the Analytical Model.
enum AnalyticalRigidLinksOption,values: Disabled (1),Enabled (0),FromColumn (2)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) ... |
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
"""String.
Running time: O(nlogn) where n == len(s1).
"""
s1 = sorted(s1)
s2 = sorted(s2)
s1bs2, s2bs1 = True, True
for i in range(len(s1)):
if s1[i] < s2[i]:
s1b... | class Solution:
def check_if_can_break(self, s1: str, s2: str) -> bool:
"""String.
Running time: O(nlogn) where n == len(s1).
"""
s1 = sorted(s1)
s2 = sorted(s2)
(s1bs2, s2bs1) = (True, True)
for i in range(len(s1)):
if s1[i] < s2[i]:
... |
# constants #
team_number = 0
# flags #
# simulation
sim_enable_flag = False
sim_activate_flag = False
# telemetry transmission
cx_flag = False
sp1x_flag = False
sp2x_flag = False
# mqtt
mqtt_flag = False
# payload deployment
sp1_deployed_flag = False
sp2_deployed_flag = False | team_number = 0
sim_enable_flag = False
sim_activate_flag = False
cx_flag = False
sp1x_flag = False
sp2x_flag = False
mqtt_flag = False
sp1_deployed_flag = False
sp2_deployed_flag = False |
class BasePermission(object):
def __init__(self, queryset, lookup_field):
self.queryset = queryset
self.lookup_field = lookup_field
def has_permission(self, user, action, pk):
pass
class AllowAny(BasePermission):
def has_permission(self, user, action, pk):
return T... | class Basepermission(object):
def __init__(self, queryset, lookup_field):
self.queryset = queryset
self.lookup_field = lookup_field
def has_permission(self, user, action, pk):
pass
class Allowany(BasePermission):
def has_permission(self, user, action, pk):
return True
cl... |
class ModelObjectFactory(object):
# no doc
@staticmethod
def GetCorrectInstance(
model, identifier, modelObjectType=None, modelObjectSubType=None
):
"""
GetCorrectInstance(model: Model,identifier: Identifier,modelObjectType: ModelObjectEnum,modelObjectSubType: int) -> ModelObjec... | class Modelobjectfactory(object):
@staticmethod
def get_correct_instance(model, identifier, modelObjectType=None, modelObjectSubType=None):
"""
GetCorrectInstance(model: Model,identifier: Identifier,modelObjectType: ModelObjectEnum,modelObjectSubType: int) -> ModelObject
GetCorrectInstance(model: ... |
items = []
class ItemsModel():
def __init__(self):
self.items = items
def add_item(self, name, price, image, quantity):
self.item_id = len(items)+1
item = {
"item_id": self.item_id,
"name": name,
"price": price,
"image": image,
... | items = []
class Itemsmodel:
def __init__(self):
self.items = items
def add_item(self, name, price, image, quantity):
self.item_id = len(items) + 1
item = {'item_id': self.item_id, 'name': name, 'price': price, 'image': image, 'quantity': quantity}
self.items.append(item)
... |
def returnyield(x):
"""Using return in generator"""
yield x
# available only in python3!!!
return "Hi there"
if __name__ == '__main__':
# create generator
ry = returnyield(5)
print(ry)
# advance to next value
print(next(ry))
# this call throws StopIteration error with return's ... | def returnyield(x):
"""Using return in generator"""
yield x
return 'Hi there'
if __name__ == '__main__':
ry = returnyield(5)
print(ry)
print(next(ry))
print(next(ry)) |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
ret, mn = 0, float('inf')
for price in prices:
if price < mn:
mn = price
if price - mn > ret:
ret = price-mn
return ret
| class Solution:
def max_profit(self, prices: List[int]) -> int:
(ret, mn) = (0, float('inf'))
for price in prices:
if price < mn:
mn = price
if price - mn > ret:
ret = price - mn
return ret |
# Gerard Hanlon, 2018-13-02
# Factorial number is the number multiplied by all of the numbers smaller than it
def sumall(upto):
sumupto = 0
for i in range(1, upto + 1):
sumupto = sumupto + i
return sumupto
print("The Factorial Number of the number 5 is: ", sumall(5))
print("The Factorial Number o... | def sumall(upto):
sumupto = 0
for i in range(1, upto + 1):
sumupto = sumupto + i
return sumupto
print('The Factorial Number of the number 5 is: ', sumall(5))
print('The Factorial Number of the number 7 is: ', sumall(7))
print('The Factorial Number of the number 10 is: ', sumall(10)) |
#
# PySNMP MIB module A3COM-HUAWEI-EFM-COMMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-EFM-COMMON-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:49:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (h3c_epon,) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'h3cEpon')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_inters... |
# encoding=utf-8
# General Header Fields
CACHE_CONTROL = b"Cache-Control".lower()
CONNECTION = b"Connection".lower()
DATE = b"Date".lower()
PRAGMA = b"Pragma".lower()
TRAILER = b"Trailer".lower()
TRANSFER_ENCODING = b"Transfer-Encoding".lower()
UPGRADE = b"Upgrade".lower()
VIA = b"Via".lower()
WARNING = b"Warning".lo... | cache_control = b'Cache-Control'.lower()
connection = b'Connection'.lower()
date = b'Date'.lower()
pragma = b'Pragma'.lower()
trailer = b'Trailer'.lower()
transfer_encoding = b'Transfer-Encoding'.lower()
upgrade = b'Upgrade'.lower()
via = b'Via'.lower()
warning = b'Warning'.lower()
accept = b'Accept'.lower()
accept_cha... |
"""
Author WG 2019
ESP32 Micropython module for the Maxim MAX44009 sensor.
https://datasheets.maximintegrated.com/en/ds/MAX44009.pdf
The MIT License (MIT)
Usage:
import max44009
from machine import I2C, Pin
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000)
max44009 = max44009.MAX44009(i2c)
lux = max... | """
Author WG 2019
ESP32 Micropython module for the Maxim MAX44009 sensor.
https://datasheets.maximintegrated.com/en/ds/MAX44009.pdf
The MIT License (MIT)
Usage:
import max44009
from machine import I2C, Pin
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000)
max44009 = max44009.MAX44009(i2c)
lux = max... |
def anonymize_phone_number(phone_number: str) -> str:
public_digits_num = 6
phone_number = phone_number.replace("-", "")
public_digits = phone_number[:public_digits_num]
number_of_private_digits = len(phone_number) - public_digits_num
private_digits = "-" * number_of_private_digits
return f"{pub... | def anonymize_phone_number(phone_number: str) -> str:
public_digits_num = 6
phone_number = phone_number.replace('-', '')
public_digits = phone_number[:public_digits_num]
number_of_private_digits = len(phone_number) - public_digits_num
private_digits = '-' * number_of_private_digits
return f'{pub... |
'''
This place-holder module makes the extensions directory
into a Python "package", so that external user-specific
modules can act as umbrella modules, and, for example:
import structural_dhcp_rst2pdf.extensions.vectorpdf_r2p
to bring in the PDF extension.
'''
| """
This place-holder module makes the extensions directory
into a Python "package", so that external user-specific
modules can act as umbrella modules, and, for example:
import structural_dhcp_rst2pdf.extensions.vectorpdf_r2p
to bring in the PDF extension.
""" |
for number in [0, 1, 2, 3, 4]:
print(number)
for number in range(5):
print(number)
| for number in [0, 1, 2, 3, 4]:
print(number)
for number in range(5):
print(number) |
# FILE MODES:
# Example:
# with open(name, 'w+') as f:
# f.write(data)
# "r"
# Read from file - YES
# Write to file - NO
# Create file if not exists - NO
# Truncate file to zero length - NO
# Cursor position - BEGINNING
#
# "r+"
# Read from file - YES
# Write to file - YES
# Create file if not exists - NO
# Trunc... | myfile = open('/media/cicek/D/DDownloads/example.txt', 'w+')
print('---------------------------------------------------------------------')
open('/media/cicek/D/DDownloads/example.txt', 'w')
open('/media/cicek/D/DDownloads/example.txt', 'r')
open('/media/cicek/D/DDownloads/example.txt', 'wb')
open('/media/cicek/D/DDown... |
_base_ = [
"../_base_/models/cascade_rcnn_r50_fpn.py",
"../_base_/datasets/coco_detection.py",
"../_base_/schedules/schedule_1x.py",
"../_base_/default_runtime.py",
]
pretrained = "https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_small_patch4_window7_224.pth"
model = dict(
ba... | _base_ = ['../_base_/models/cascade_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_small_patch4_window7_224.pth'
model = dict(backbone=dict(_delete_=Tru... |
class Event:
def __init__(self, name, **kwargs):
self.name = name
self.args = kwargs
def __str__(self):
return f"Event(name='{self.name}', args={self.args})"
| class Event:
def __init__(self, name, **kwargs):
self.name = name
self.args = kwargs
def __str__(self):
return f"Event(name='{self.name}', args={self.args})" |
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
def kSum(nums: List[int], target: int, k: int) -> List[List[int]]:
res = []
if len(nums) == 0 or nums[0] * k > target or target > nums[-1] * k:
return res
if k == 2:
... | class Solution:
def four_sum(self, nums: List[int], target: int) -> List[List[int]]:
def k_sum(nums: List[int], target: int, k: int) -> List[List[int]]:
res = []
if len(nums) == 0 or nums[0] * k > target or target > nums[-1] * k:
return res
if k == 2:
... |
'''
Exercise 2 for Day 5 of 100 Days of Python
In this exercise, we are going to find out the highest score from a given list of scores of a certain number of students
We are going to discuss 2 methods of finding the maximum
'''
def find_maximum_score(scores):
''' METHOD 1
Using the inbuilt max() function, ... | """
Exercise 2 for Day 5 of 100 Days of Python
In this exercise, we are going to find out the highest score from a given list of scores of a certain number of students
We are going to discuss 2 methods of finding the maximum
"""
def find_maximum_score(scores):
""" METHOD 1
Using the inbuilt max() function, w... |
class Registry(object):
def __init__(self):
self.models = []
def add(self, model):
"""Register a model as a valid comment target"""
self.models.append(model)
def __contains__(self, model):
"""Check if a model (or one of its parent classes) is registered"""
return an... | class Registry(object):
def __init__(self):
self.models = []
def add(self, model):
"""Register a model as a valid comment target"""
self.models.append(model)
def __contains__(self, model):
"""Check if a model (or one of its parent classes) is registered"""
return a... |
def dfsUtil(G, visited, travel, s):
if(visited[s]):
return
visited[s] = True
for u in G[s]:
if(not visited[u]):
dfsUtil(G, visited, travel, u)
travel.append(s)
def dfs(G, s=1):
visited = {k: False for k in G.nodes}
travel = []
for u in G.nodes:
if(not vi... | def dfs_util(G, visited, travel, s):
if visited[s]:
return
visited[s] = True
for u in G[s]:
if not visited[u]:
dfs_util(G, visited, travel, u)
travel.append(s)
def dfs(G, s=1):
visited = {k: False for k in G.nodes}
travel = []
for u in G.nodes:
if not vis... |
# Given a non-empty string s and an abbreviation abbr,
# return whether the string matches with the given abbreviation.
# A string such as "word" contains only the following valid abbreviations:
# ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d",
# "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
# ... | class Solution(object):
def valid_word_abbreviation(self, word, abbr):
"""
:type word: str
:type abbr: str
:rtype: bool
"""
i = j = 0
while i < len(word) and j < len(abbr):
if word[i] == abbr[j]:
i += 1
j += 1
... |
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return str(bin(int(a, 2) + int(b, 2))[2:])
def test_add_binary():
s = Solution()
assert "100" == s.addBinary("11", "1")
assert "10101" == s.addBinary("1010",... | class Solution(object):
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return str(bin(int(a, 2) + int(b, 2))[2:])
def test_add_binary():
s = solution()
assert '100' == s.addBinary('11', '1')
assert '10101' == s.addBinary('1010'... |
def double(x):
return x*2
# Lambda Functions
# In Python, you can declare a variable of type function, where implementations can be simply assigned
# In some use cases, you may have to function pointer to a function for some processing logic
# Best Scenario: Callback scenarios
# A mechnism of defining a method i... | def double(x):
return x * 2
new_double = lambda x: x * 2
print(double(10))
print(new_double(200))
def get_value():
return 10
result = get_value()
print(new_double(result))
print((lambda x: x * x)(10))
formatter = lambda x, y, z='X': '{}, {}, {}'.format(x, y, z)
print(formatter('R', 'J'))
formatter2 = lambda x,... |
#
# PySNMP MIB module DLSW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLSW-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:07:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection) ... |
'''
Play with numbers
You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.
First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers ... | """
Play with numbers
You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.
First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers ... |
def glyphs():
return 97
_font =\
b'\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a'\
b'\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a'\
b'\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a'\
b'\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a\x00\x4a\x5a'\
b'\x00\x4a\x5a\x00\x4a\x5... | def glyphs():
return 97
_font = b'\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x00JZ\x11KYQKNLLNKQKSLVNXQYSYVXXVYSYQXNVLSKQK\x05LXLLLXXXXLLL\x04KYRJKVYVRJ\x05LXRHLRR\\X... |
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
if A == B:
seen = set()
for char in A:
if char in seen:
return True
seen.add(char)
return False
... | class Solution:
def buddy_strings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
if A == B:
seen = set()
for char in A:
if char in seen:
return True
seen.add(char)
return False
... |
# ------------------------------
# 560. Subarray Sum Equals K
#
# Description:
# Given an array of integers and an integer k, you need to find the total number of
# continuous subarrays whose sum equals to k.
#
# Example 1:
# Input:nums = [1,1,1], k = 2
# Output: 2
#
# Note:
# The length of the array is in range [1... | class Solution:
def subarray_sum(self, nums: List[int], k: int) -> int:
pre_sum = 0
count = 0
sum_dict = {0: 1}
for n in nums:
pre_sum += n
if preSum - k in sumDict:
count += sumDict[preSum - k]
sumDict[preSum] = sumDict.get(preSum... |
# testSIF = "123456789012"
testSIF = open("input.txt", 'r').read()
# testSIF = "0222112222120000"
x_size = 25
y_size = 6
layer_count = len(testSIF) // (x_size * y_size)
layers = []
index = 0
for z in range(layer_count):
layer = []
for y in range(y_size):
for x in range(x_size):
layer += tes... | test_sif = open('input.txt', 'r').read()
x_size = 25
y_size = 6
layer_count = len(testSIF) // (x_size * y_size)
layers = []
index = 0
for z in range(layer_count):
layer = []
for y in range(y_size):
for x in range(x_size):
layer += testSIF[index]
index += 1
layers.append(layer... |
class Object:
## Lisp apply() to `that` object in context
def apply(self, env, that):
raise NotImplementedError(['apply', self, env, that])
| class Object:
def apply(self, env, that):
raise not_implemented_error(['apply', self, env, that]) |
loop = 1
while (loop < 10):
noun1 = input("Choose a noun: ")
plur_noun = input("Choose a plural noun: ")
noun2 = input("Choose a noun: ")
place = input("Name a place: ")
adjective = input("Choose an adjective (Describing word): ")
noun3 = input("Choose a noun: ")
print ("--------... | loop = 1
while loop < 10:
noun1 = input('Choose a noun: ')
plur_noun = input('Choose a plural noun: ')
noun2 = input('Choose a noun: ')
place = input('Name a place: ')
adjective = input('Choose an adjective (Describing word): ')
noun3 = input('Choose a noun: ')
print('-----------------------... |
def aumentar(n,p,formatar=False):
v = n + (n * p / 100)
if formatar:
return moeda(v)
else:
return v
def diminuir(n,p,formatar=False):
v = n - (n * p / 100)
if formatar:
return moeda(v)
else:
return v
def dobro(n,formatar=False):
v = n*2
if... | def aumentar(n, p, formatar=False):
v = n + n * p / 100
if formatar:
return moeda(v)
else:
return v
def diminuir(n, p, formatar=False):
v = n - n * p / 100
if formatar:
return moeda(v)
else:
return v
def dobro(n, formatar=False):
v = n * 2
if formatar:
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Product Availability',
'category': 'Website/Website',
'summary': 'Manage product inventory & availability',
'description': """
Manage the inventory of your products and display their availabili... | {'name': 'Product Availability', 'category': 'Website/Website', 'summary': 'Manage product inventory & availability', 'description': '\nManage the inventory of your products and display their availability status in your eCommerce store.\nIn case of stockout, you can decide to block further sales or to keep selling.\nA ... |
#!/usr/bin/env python3
"""
Advent of Code!
--- Day 2: Dive! ---
Now doing advent of code day 2 in-between working on finals...
I sure hope the puzzles don't ramp up too much the first few days!
"""
def process_input(input_name):
with open(input_name) as input:
return input.readlines()
def calculate_pos(inp... | """
Advent of Code!
--- Day 2: Dive! ---
Now doing advent of code day 2 in-between working on finals...
I sure hope the puzzles don't ramp up too much the first few days!
"""
def process_input(input_name):
with open(input_name) as input:
return input.readlines()
def calculate_pos(input, has_aim=False):... |
"""
Base class implementing class level locking capability.
MIT License
(C) Copyright [2020] Hewlett Packard Enterprise Development LP
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 res... | """
Base class implementing class level locking capability.
MIT License
(C) Copyright [2020] Hewlett Packard Enterprise Development LP
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 res... |
"""
Given an integer array nums sorted in non-decreasing order,
remove the duplicates in-place such that each unique element appears only once.
The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages,
you must instead have the result be plac... | """
Given an integer array nums sorted in non-decreasing order,
remove the duplicates in-place such that each unique element appears only once.
The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages,
you must instead have the result be plac... |
# coding:utf-8
"""
Simplized version of 0-1 knapSack method.
Donghui Chen, Wangmeng Song
May 15, 2017
Wangmeng Song
August 16, 2017
"""
def zeros(rows, cols):
row = []
data = []
for i in range(cols):
row.append(0)
for i in range(rows):
data.append(row[:])
return data
def getIte... | """
Simplized version of 0-1 knapSack method.
Donghui Chen, Wangmeng Song
May 15, 2017
Wangmeng Song
August 16, 2017
"""
def zeros(rows, cols):
row = []
data = []
for i in range(cols):
row.append(0)
for i in range(rows):
data.append(row[:])
return data
def get_items_used(w, c):
... |
""" Think of something you could store in a list.
Write a program that creates a list containing these items """
start = True
languages = []
while start:
name = input('Hi, what\'s your name?: ')
print(f'Welcome {name.title()}')
fav_language = input('What is your favorite programming language?:\n')
lan... | """ Think of something you could store in a list.
Write a program that creates a list containing these items """
start = True
languages = []
while start:
name = input("Hi, what's your name?: ")
print(f'Welcome {name.title()}')
fav_language = input('What is your favorite programming language?:\n')
langua... |
numbers = [54, 23, 66, 12]
sumEle = numbers[1] + numbers[2]
print(sumEle) | numbers = [54, 23, 66, 12]
sum_ele = numbers[1] + numbers[2]
print(sumEle) |
class Solution:
def search(self, nums: List[int], target: int) -> int:
#start pointers
low = 0
high = len(nums) - 1
# iterate trought the array
while low <= high:
# define middle of array
mid = low + (high - low) // 2
# if position == tar... | class Solution:
def search(self, nums: List[int], target: int) -> int:
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
... |
#-*- coding: utf-8 -*-
#!/usr/bin/env python
## dummy class to replace usbio class
class I2C(object):
def __init__(self,module,slave):
pass
def searchI2CDev(self,begin,end):
pass
def write_register(self, reg, data):
pass
# def I2C(self,mo... | class I2C(object):
def __init__(self, module, slave):
pass
def search_i2_c_dev(self, begin, end):
pass
def write_register(self, reg, data):
pass
def autodetect():
pass
def setup():
pass |
# Variables representing the number of candies collected by alice, bob, and carol
alice_candies = 121
bob_candies = 77
carol_candies = 109
# Your code goes here! Replace the right-hand side of this assignment with an expression
# involving alice_candies, bob_candies, and carol_candies
total = (alice_candies + bob_cand... | alice_candies = 121
bob_candies = 77
carol_candies = 109
total = alice_candies + bob_candies + carol_candies
print(total % 3) |
class ProfileDoesNotExist(Exception):
def __init__(self, message, info={}):
self.message = message
self.info = info
class ScraperError(Exception):
def __init__(self, message, info={}):
self.message = message
self.info = info
| class Profiledoesnotexist(Exception):
def __init__(self, message, info={}):
self.message = message
self.info = info
class Scrapererror(Exception):
def __init__(self, message, info={}):
self.message = message
self.info = info |
field_size = 40
snakeTailX = [40,80,120]
snakeTailY = [0,0,0 ]
Xhead, Yhead, Xfood, Yfood = 120,0,-40,- 40
snakeDirection = 'R'
foodkey = True
snakeLeight = 2
deadKey = False
score = 0
def setup():
global img
smooth()
size(1024,572)
img = loadImage("gameover.jpg")
size(1024,572)
... | field_size = 40
snake_tail_x = [40, 80, 120]
snake_tail_y = [0, 0, 0]
(xhead, yhead, xfood, yfood) = (120, 0, -40, -40)
snake_direction = 'R'
foodkey = True
snake_leight = 2
dead_key = False
score = 0
def setup():
global img
smooth()
size(1024, 572)
img = load_image('gameover.jpg')
size(1024, 572)
... |
#function with default parameter
def describe_pet(pet_name,animal_type='dog'):
"""Displays information about a pet."""
print(f"I have a {animal_type}")
print(f"My {animal_type}'s name is {pet_name.title()}")
#a dog named willie
describe_pet('willie')
#a hamster named harry
describe_pet('harry','hamster')... | def describe_pet(pet_name, animal_type='dog'):
"""Displays information about a pet."""
print(f'I have a {animal_type}')
print(f"My {animal_type}'s name is {pet_name.title()}")
describe_pet('willie')
describe_pet('harry', 'hamster')
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name=... |
"""
Utility functions for handling price data
"""
def get_min_prices(assets: list) -> list:
min_price = min([asset.get("price") for asset in assets])
return [asset for asset in assets if asset.get("price") == min_price]
def get_average_price(assets: list) -> float:
num_assets = len(assets)
return sum... | """
Utility functions for handling price data
"""
def get_min_prices(assets: list) -> list:
min_price = min([asset.get('price') for asset in assets])
return [asset for asset in assets if asset.get('price') == min_price]
def get_average_price(assets: list) -> float:
num_assets = len(assets)
return sum_... |
class AncapBotError(Exception):
pass
class InsufficientFundsError(AncapBotError):
pass
class NonexistentUserError(AncapBotError):
pass
| class Ancapboterror(Exception):
pass
class Insufficientfundserror(AncapBotError):
pass
class Nonexistentusererror(AncapBotError):
pass |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Build Tower
#Problem level: 6 kyu
def tower_builder(n_floors):
return [' '*(n_floors-x)+'*'*(2*x-1)+' '*(n_floors-x) for x in range(1,n_floors+1)]
| def tower_builder(n_floors):
return [' ' * (n_floors - x) + '*' * (2 * x - 1) + ' ' * (n_floors - x) for x in range(1, n_floors + 1)] |
class Solution:
def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:
def dfs(y, x):
if y < 0 or y > m-1 or x < 0 or x > n-1 or grid[y][x]!=1:
return 0
grid[y][x] =2
ret = 1
return ret + sum(dfs(y+shift_y, x+shift_x) f... | class Solution:
def hit_bricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:
def dfs(y, x):
if y < 0 or y > m - 1 or x < 0 or (x > n - 1) or (grid[y][x] != 1):
return 0
grid[y][x] = 2
ret = 1
return ret + sum((dfs(y + shif... |
class Handler:
def __init__(self):
self.trace = []
def handle(self, data):
self.trace.append(f'HANDLE {data}')
return data
| class Handler:
def __init__(self):
self.trace = []
def handle(self, data):
self.trace.append(f'HANDLE {data}')
return data |
description = 'Verify that the user cannot log in if username value is missing'
pages = ['login']
def setup(data):
pass
def test(data):
go_to('http://localhost:8000/')
send_keys(login.password_input, 'admin')
click(login.login_button)
capture('Verify the correct error message is shown')
veri... | description = 'Verify that the user cannot log in if username value is missing'
pages = ['login']
def setup(data):
pass
def test(data):
go_to('http://localhost:8000/')
send_keys(login.password_input, 'admin')
click(login.login_button)
capture('Verify the correct error message is shown')
verify... |
__description__ = 'lamuda common useful tools'
__license__ = 'MIT'
__uri__ = 'https://github.com/hanadumal/lamud'
__version__ = '21.6.28'
__author__ = 'hanadumal'
__email__ = 'hanadumal@outlook.com'
| __description__ = 'lamuda common useful tools'
__license__ = 'MIT'
__uri__ = 'https://github.com/hanadumal/lamud'
__version__ = '21.6.28'
__author__ = 'hanadumal'
__email__ = 'hanadumal@outlook.com' |
# Just taken from terminal_service.py for Seeker
# Will modify based on this as a template
#from xmlrpc.client import Fault
class TerminalService:
"""
A service that handles terminal operations.
The responsibility of a TerminalService is to provide input and output operations for the
terminal.
... | class Terminalservice:
"""
A service that handles terminal operations.
The responsibility of a TerminalService is to provide input and output operations for the
terminal.
def read_a_character(self, prompt):
def _is_alphabetic_letter(self, letter, num = 1):
def write_text(self, text):
"... |
{
"includes": [
"common.gypi",
],
"targets": [
{
"target_name": "colony",
"product_name": "colony",
"type": "executable",
'cflags': [ '-Wall', '-Wextra', '-Werror' ],
"sources": [
'<(runtime_path)/colony/cli.c',
],
'xcode_settings': {
'OTHER_LDFL... | {'includes': ['common.gypi'], 'targets': [{'target_name': 'colony', 'product_name': 'colony', 'type': 'executable', 'cflags': ['-Wall', '-Wextra', '-Werror'], 'sources': ['<(runtime_path)/colony/cli.c'], 'xcode_settings': {'OTHER_LDFLAGS': ['-pagezero_size', '10000', '-image_base', '100000000']}, 'include_dirs': ['<(ru... |
def int_to_bytes(n, num_bytes):
return n.to_bytes(num_bytes, 'big')
def int_from_bytes(bites):
return int.from_bytes(bites, 'big')
class fountain_header:
length = 6
def __init__(self, encode_id, total_size=None, chunk_id=None):
if total_size is None:
self.encode_id, self.total_... | def int_to_bytes(n, num_bytes):
return n.to_bytes(num_bytes, 'big')
def int_from_bytes(bites):
return int.from_bytes(bites, 'big')
class Fountain_Header:
length = 6
def __init__(self, encode_id, total_size=None, chunk_id=None):
if total_size is None:
(self.encode_id, self.total_si... |
'''
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... |
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
def _maybe(repo_rule, name, **kwargs):
if name not in native.existing_rules():
repo_rule(name = name, **kwargs)
def load_bark():
_maybe(
native.local_repository,
name = "bark_project",
path="/home/chenyang/bark",
)
#_... | load('@bazel_tools//tools/build_defs/repo:git.bzl', 'git_repository')
def _maybe(repo_rule, name, **kwargs):
if name not in native.existing_rules():
repo_rule(name=name, **kwargs)
def load_bark():
_maybe(native.local_repository, name='bark_project', path='/home/chenyang/bark') |
#then look for the enumerated Intel Movidius NCS Device();quite program if none found.
devices = mvnc.EnumerateDevice();
if len(devices) == 0:
print("No any Devices found");
quit;
#Now get a handle to the first enumerated device and open it.
device = mvnc.Device(devices[0]);
device.OpenDevice();
| devices = mvnc.EnumerateDevice()
if len(devices) == 0:
print('No any Devices found')
quit
device = mvnc.Device(devices[0])
device.OpenDevice() |
def mirror(text):
words = text.split(" ")
nwords = []
for w in words:
nw = w[::-1]
nwords.append(nw)
return " ".join(nwords)
print(mirror("s'tI suoregnad ot eb thgir nehw eht tnemnrevog si .gnorw"))
| def mirror(text):
words = text.split(' ')
nwords = []
for w in words:
nw = w[::-1]
nwords.append(nw)
return ' '.join(nwords)
print(mirror("s'tI suoregnad ot eb thgir nehw eht tnemnrevog si .gnorw")) |
UNK_TOKEN = '<unk>'
PAD_TOKEN = '<pad>'
BOS_TOKEN = '<s>'
EOS_TOKEN = '<\s>'
PAD, UNK, BOS, EOS = [0, 1, 2, 3]
LANGUAGE_TOKENS = {lang: '<%s>' % lang
for lang in sorted(['en', 'de', 'fr', 'he'])}
| unk_token = '<unk>'
pad_token = '<pad>'
bos_token = '<s>'
eos_token = '<\\s>'
(pad, unk, bos, eos) = [0, 1, 2, 3]
language_tokens = {lang: '<%s>' % lang for lang in sorted(['en', 'de', 'fr', 'he'])} |
"""This is a test script."""
def hello_world():
"""Function that prints Hello World."""
print("Hello World")
if __name__ == "__main__":
hello_world()
| """This is a test script."""
def hello_world():
"""Function that prints Hello World."""
print('Hello World')
if __name__ == '__main__':
hello_world() |
class Argument(object):
def __init__(self, name=None, names=(), kind=bool, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise TypeError(msg)
if not (name or names):
raise TypeError("An Argument must have at lea... | class Argument(object):
def __init__(self, name=None, names=(), kind=bool, default=None):
if name and names:
msg = "Cannot give both 'name' and 'names' arguments! Pick one."
raise type_error(msg)
if not (name or names):
raise type_error('An Argument must have at ... |
# The Pipelines section. Pipelines group related components together by piping the output
# of one component into the input of another. This is a good place to write your
# package / unit tests as well as initialize your flags. Package tests check that the input
# received by a component is of the right specification... | flags.set('pf_settings', [100, 'PF'])
flags.set('inv_pf_settings', [100, 'InvPF'])
flags.set('rr_fifo_settings', [100, 'RR_FIFO'])
flags.set('rr_random_settings', [100, 'RR_random'])
flags.set('hybrid_inv_pf_fifo_settings', [100, 'Hybrid_InvPF_FIFO'])
flags.set('broadcast_settings', [1000, 5])
flags.set('run_interval',... |
#List comprehension
"""
The concept of list comprehension takes in three parameters
- expression
- iteration
- codition (This usually optional)
syntax of list comprehension
list_of_numbers_from_1_to_10 = [expression iteration condition]
"""
#example of list comprehension with without condition
list_of_num... | """
The concept of list comprehension takes in three parameters
- expression
- iteration
- codition (This usually optional)
syntax of list comprehension
list_of_numbers_from_1_to_10 = [expression iteration condition]
"""
list_of_numbers_from_1_to_10 = [number for number in range(11)]
list1 = [x / 2 for x i... |
""" append and extend"""
first_line = [1,2,3,4,5]
first_line.append(6)
print(first_line)
# first_line.append(7,8,9) #doesn't work
first_line.append([7,8,9])
print(first_line)
correct_list = [1,2,3,4,5]
correct_list.extend([6,7,8,9,10])
print(correct_list)
""" insert """
print()
correct_list.insert(0, 100)
print(... | """ append and extend"""
first_line = [1, 2, 3, 4, 5]
first_line.append(6)
print(first_line)
first_line.append([7, 8, 9])
print(first_line)
correct_list = [1, 2, 3, 4, 5]
correct_list.extend([6, 7, 8, 9, 10])
print(correct_list)
' insert '
print()
correct_list.insert(0, 100)
print(correct_list)
' remove '
print()
first... |
pjesma = '''\
Programiranje je zabava
Kada je posao gotov
ako zelis da ti posao bude razbirbriga
korisit Python!
'''
f = open("pjesma.txt", "w") #otvara fajl sa w-pisanje
f.write(pjesma) #upisuje tekst u fajl
f.close() #zatvara fajl
f = open("pjesma.txt") #ako nismo naveli podazumjevno je r-citanje fajla
while True:
... | pjesma = 'Programiranje je zabava\nKada je posao gotov\nako zelis da ti posao bude razbirbriga\nkorisit Python!\n'
f = open('pjesma.txt', 'w')
f.write(pjesma)
f.close()
f = open('pjesma.txt')
while True:
linija = f.readline()
if len(linija) == 0:
break
print(linija, end=' ')
f.close() |
# from __future__ import division
class WarheadTypeEnum(object):
UNDEFINED = 0
CONE_WARHEAD = 1
ARC_WARHEAD = 2
CARMEN_WARHEAD = 3
class SternTypeEnum(object):
UNDEFINED = 0
CONE_STERN = 1
ARC_STERN = 2
class BaseMissile(object):
def __init__(self):
self.para_dict = {'type_... | class Warheadtypeenum(object):
undefined = 0
cone_warhead = 1
arc_warhead = 2
carmen_warhead = 3
class Sterntypeenum(object):
undefined = 0
cone_stern = 1
arc_stern = 2
class Basemissile(object):
def __init__(self):
self.para_dict = {'type_warhead': WarheadTypeEnum.UNDEFINED, ... |
CREATED_AT_KEY = "created_at"
TITLE_KEY = "title"
DESCRIPTION_KEY = "description"
PUBLISHED_AT = "published_at"
LIMIT_KEY = "limit"
OFFSET_KEY = "offset"
# Data query limiters
DEFAULT_OFFSET = 0
DEFAULT_PER_PAGE_LIMIT = 20
INDEX_KEY = "video_index"
VIDEO_ID_KEY = "video_id"
VIDEOS_SEARCH_QUERY_KEY = "video_search_q... | created_at_key = 'created_at'
title_key = 'title'
description_key = 'description'
published_at = 'published_at'
limit_key = 'limit'
offset_key = 'offset'
default_offset = 0
default_per_page_limit = 20
index_key = 'video_index'
video_id_key = 'video_id'
videos_search_query_key = 'video_search_query' |
"""
contest 12/21/2019
"""
class Solution:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
freq = {}
count_dict = {}
def count_letters(word):
if word in count_dict:
return count_dict[word]
unq = {}
for i... | """
contest 12/21/2019
"""
class Solution:
def max_freq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
freq = {}
count_dict = {}
def count_letters(word):
if word in count_dict:
return count_dict[word]
unq = {}
for ite... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module contains project version information."""
__version__ = "v22.03.4"
| """This module contains project version information."""
__version__ = 'v22.03.4' |
# Longest Name.
# Create a program that takes an unknown amount of names and outputs the longest name. You will know that the inputs are done when the user has inputted a string of X
user_input = '' # Empty string
longest_name = ''
length = 0
while user_input != 'X':
user_input = input('Enter a name: ')
i... | user_input = ''
longest_name = ''
length = 0
while user_input != 'X':
user_input = input('Enter a name: ')
if user_input != 'X':
current_length = len(user_input)
if current_length > length:
length = current_length
longest_name = user_input
print(longest_name, 'was the lon... |
# This program is open source. For license terms, see the LICENSE file.
class Movie():
"""Creates a Movie object with the possibility to define information about
its title, poster URL and YouTube trailer.
Attributes:
title: The title of the movie.
poster_image_url: URL to the poster of t... | class Movie:
"""Creates a Movie object with the possibility to define information about
its title, poster URL and YouTube trailer.
Attributes:
title: The title of the movie.
poster_image_url: URL to the poster of the movie.
trailer_youtube_url: URL to the trailer in YouTube.
"""... |
# -*- coding: utf-8 -*-
{
"name": "WeCom Portal",
"author": "RStudio",
"website": "https://gitee.com/rainbowstudio/wecom",
"sequence": 608,
"installable": True,
"application": True,
"auto_install": False,
"category": "WeCom/WeCom",
"version": "15.0.0.1",
"summary": """
We... | {'name': 'WeCom Portal', 'author': 'RStudio', 'website': 'https://gitee.com/rainbowstudio/wecom', 'sequence': 608, 'installable': True, 'application': True, 'auto_install': False, 'category': 'WeCom/WeCom', 'version': '15.0.0.1', 'summary': '\n WeCom Portal\n ', 'description': '\n\n\n ', 'depends':... |
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MAX_INT = 0x7FFFFFFF
MIN_INT = 0x80000000
MASK = 0x100000000
while b:
a, b = (a ^ b) % MASK, ((a & b) << 1) % MASK
return a if a <... | class Solution(object):
def get_sum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
max_int = 2147483647
min_int = 2147483648
mask = 4294967296
while b:
(a, b) = ((a ^ b) % MASK, ((a & b) << 1) % MASK)
return a i... |
# Container for information about the project
class Project(object):
def __init__(self, origin='', commit='', owner='', name=''):
self.origin = origin
self.commit = commit
self.owner = owner
self.name = name
def _asdict(self):
return self.__dict__
def __dir__(self)... | class Project(object):
def __init__(self, origin='', commit='', owner='', name=''):
self.origin = origin
self.commit = commit
self.owner = owner
self.name = name
def _asdict(self):
return self.__dict__
def __dir__(self):
return ['origin', 'commit', 'owner',... |
with open("my_files_ex1.txt") as f:
file = f.read()
print(file)
| with open('my_files_ex1.txt') as f:
file = f.read()
print(file) |
class NewsModel:
title = None
url = None
def __init__(self, __title__, __url__):
self.title = __title__
self.url = __url__
def __str__(self):
return '''["%s", "%s"]''' % (self.title, self.url)
| class Newsmodel:
title = None
url = None
def __init__(self, __title__, __url__):
self.title = __title__
self.url = __url__
def __str__(self):
return '["%s", "%s"]' % (self.title, self.url) |
class Operation:
__slots__ = ['session', '_sql', '_table', '_stable', '_col_lst', '_tag_lst', '_operation_history']
def __init__(self, session):
self.session = session
self._sql = []
self._table = None
self._stable = None
self._col_lst = None
self._tag_lst = None... | class Operation:
__slots__ = ['session', '_sql', '_table', '_stable', '_col_lst', '_tag_lst', '_operation_history']
def __init__(self, session):
self.session = session
self._sql = []
self._table = None
self._stable = None
self._col_lst = None
self._tag_lst = None... |
"""
The Data recording and processing program with the use of a derived class of `list` data structure.
"""
# Classes:
class Athlete(list):
def __init__(self, arg_name, arg_dob=None, arg_times=[]):
"""
:param arg_name: The name of the athlete
:param arg_dob: The Date of birth of the athlete
:param arg_time... | """
The Data recording and processing program with the use of a derived class of `list` data structure.
"""
class Athlete(list):
def __init__(self, arg_name, arg_dob=None, arg_times=[]):
"""
:param arg_name: The name of the athlete
:param arg_dob: The Date of birth of the athlete
:param arg_times:... |
def main():
space = " "
item = "o"
buffer = ""
for x in range(2):
spacing = ""
for y in range(50):
spacing += space
buffer = spacing + item
print(buffer)
for z in range(50):
spacing -= space
buffer = item + spacin... | def main():
space = ' '
item = 'o'
buffer = ''
for x in range(2):
spacing = ''
for y in range(50):
spacing += space
buffer = spacing + item
print(buffer)
for z in range(50):
spacing -= space
buffer = item + spacing
... |
__name__ = "ratter"
__version__ = "0.1.0-a0"
__author__ = "Fabian Meyer"
__maintainer__ = "Fabian Meyer"
__email__ = "fabian.meyer@ise.fraunhofer.de"
__copyright__ = "Copyright 2020, Fraunhofer ISE"
__license__ = "BSD 3-clause"
__url__ = "https://github.com/fa-me/ratter"
__summary__ = """calculate reflection, absorptio... | __name__ = 'ratter'
__version__ = '0.1.0-a0'
__author__ = 'Fabian Meyer'
__maintainer__ = 'Fabian Meyer'
__email__ = 'fabian.meyer@ise.fraunhofer.de'
__copyright__ = 'Copyright 2020, Fraunhofer ISE'
__license__ = 'BSD 3-clause'
__url__ = 'https://github.com/fa-me/ratter'
__summary__ = 'calculate reflection, absorption ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.