content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class MomentumGradientDescent(GradientDescent):
def __init__(self, params, lr=0.1, momentum=.9):
super(MomentumGradientDescent, self).__init__(params, lr)
self.momentum = momentum
self.velocities = [torch.zeros_like(param, requires_grad=False)
for param in params]... | class Momentumgradientdescent(GradientDescent):
def __init__(self, params, lr=0.1, momentum=0.9):
super(MomentumGradientDescent, self).__init__(params, lr)
self.momentum = momentum
self.velocities = [torch.zeros_like(param, requires_grad=False) for param in params]
def step(self):
... |
self.description = "Install a package with a missing dependency (nodeps)"
p = pmpkg("dummy")
p.files = ["bin/dummy",
"usr/man/man1/dummy.1"]
p.depends = ["dep1"]
self.addpkg(p)
self.args = "-Udd %s" % p.filename()
self.addrule("PACMAN_RETCODE=0")
self.addrule("PKG_EXIST=dummy")
self.addrule("PKG_DEPENDS=d... | self.description = 'Install a package with a missing dependency (nodeps)'
p = pmpkg('dummy')
p.files = ['bin/dummy', 'usr/man/man1/dummy.1']
p.depends = ['dep1']
self.addpkg(p)
self.args = '-Udd %s' % p.filename()
self.addrule('PACMAN_RETCODE=0')
self.addrule('PKG_EXIST=dummy')
self.addrule('PKG_DEPENDS=dummy|dep1')
fo... |
"""Loads the atlas library"""
# Sanitize a dependency so that it works correctly from code that includes
# Apollo as a submodule.
def clean_dep(dep):
return str(Label(dep))
# Installed via atlas-dev
def repo():
# atlas
native.new_local_repository(
name = "atlas",
build_file = clean_dep("//... | """Loads the atlas library"""
def clean_dep(dep):
return str(label(dep))
def repo():
native.new_local_repository(name='atlas', build_file=clean_dep('//third_party/atlas:atlas.BUILD'), path='/usr/include') |
# dictionary fundamentals
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
# assigning a dictionary value to a variable
new_points = alien_0['points']
print("You just earn " + str(new_points) + " points!")
# adding more values to a dictionary
# original dict
print(alien_0)... | alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print('You just earn ' + str(new_points) + ' points!')
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
alien_o = {}
alien_o['color'] = 'green'
alien_o['points'] = ... |
# Changes - 7/25/01 - RDS
# -Added 'label' item to Menu and MenuItem definitions.
# -StaticText.label => StaticText.text
#
{
'application':
{
'type':'Application',
'name':'SourceForgeTracker',
'menubar':
{
'type':'MenuBar',
'menus':
[
{'type'... | {'application': {'type': 'Application', 'name': 'SourceForgeTracker', 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu', 'name': 'menuFile', 'label': '&File', 'items': [{'type': 'MenuItem', 'name': 'menuFileExit', 'label': 'E&xit\tAlt+X', 'command': 'exit'}]}]}, 'backgrounds': [{'type': 'Background', 'name': 'bg... |
class NoFreeRobots(Exception):
pass
class UnavailableRobot(Exception):
pass
| class Nofreerobots(Exception):
pass
class Unavailablerobot(Exception):
pass |
# Bit Manipulation
# Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
#
# Example:
#
# Input: [1,2,1,3,2,5]
# Output: [3,5]
# Note:
#
# The order of the result is not important. So in the above ... | class Solution(object):
def single_number(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num_set = set()
for x in nums:
if x not in numSet:
numSet.add(x)
else:
numSet.remove(x)
return list(... |
expected_output = {
"slot": {
"1": {
"ip_version": {
"IPv4": {
"route_table": {
"default/base": {
"prefix": {
"1.1.1.1/32": {
"next_hop": {
... | expected_output = {'slot': {'1': {'ip_version': {'IPv4': {'route_table': {'default/base': {'prefix': {'1.1.1.1/32': {'next_hop': {'1.1.1.1': {'interface': 'loopback0', 'is_best': True}}}, '1.1.1.2/32': {'next_hop': {'1.1.1.2': {'interface': 'loopback1', 'is_best': False}}}, '2.2.2.2/32': {'next_hop': {'fe80::a111:2222:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Defines classes related to 2D polygons.
"""
class Vertex:
def __init__(self, coordinates, **kwargs):
self.coordinates = coordinates
if 'prev' in kwargs:
self.set_prev(kwargs['prev'])
if 'next' in kwargs:
self.set_ne... | """Defines classes related to 2D polygons.
"""
class Vertex:
def __init__(self, coordinates, **kwargs):
self.coordinates = coordinates
if 'prev' in kwargs:
self.set_prev(kwargs['prev'])
if 'next' in kwargs:
self.set_next(kwargs['next'])
def x(self):
ret... |
{
"targets": [
{
"target_name": "readpath",
"sources": [ "src/dirread.cc", "src/async.cc" ],
"include_dirs" : [
"<!(node -e \"require('nan')\")"
]
}
],
}
| {'targets': [{'target_name': 'readpath', 'sources': ['src/dirread.cc', 'src/async.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]} |
class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = defaultdict(TrieNode)
self.word: Optional[str] = None
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
m = len(board)
n = len(board[0])
ans = []
root = TrieNode()
def in... | class Trienode:
def __init__(self):
self.children: Dict[str, TrieNode] = defaultdict(TrieNode)
self.word: Optional[str] = None
class Solution:
def find_words(self, board: List[List[str]], words: List[str]) -> List[str]:
m = len(board)
n = len(board[0])
ans = []
... |
# This is a list of modules which are not required to build
# in order to test out this extension. Mostly useful for CI.
module_arkit_enabled = "no"
module_assimp_enabled = "no"
module_fbx_enabled = "no"
module_bmp_enabled = "no"
module_bullet_enabled = "no"
module_camera_enabled = "no"
module_csg_enabled = "no"
modul... | module_arkit_enabled = 'no'
module_assimp_enabled = 'no'
module_fbx_enabled = 'no'
module_bmp_enabled = 'no'
module_bullet_enabled = 'no'
module_camera_enabled = 'no'
module_csg_enabled = 'no'
module_cvtt_enabled = 'no'
module_dds_enabled = 'no'
module_enet_enabled = 'no'
module_etc_enabled = 'no'
module_gdnative_enabl... |
class LegMovement(object):
"""Represents a leg movement."""
def __init__(self):
"""Initializes a new instance of the LegMovement class."""
self.empty = False
self.coxa = 0.0
self.tibia = 0.0
self.femur = 0.0
self.coxaSpeed = 0.0
self.tibiaSpeed = 0.0
... | class Legmovement(object):
"""Represents a leg movement."""
def __init__(self):
"""Initializes a new instance of the LegMovement class."""
self.empty = False
self.coxa = 0.0
self.tibia = 0.0
self.femur = 0.0
self.coxaSpeed = 0.0
self.tibiaSpeed = 0.0
... |
"""Problem 009
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
ans = next(a * b * c
for a in range(1, 500)
for... | """Problem 009
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
ans = next((a * b * c for a in range(1, 500) for b in range(1, 500) fo... |
TEST_DATA = [(
'donation_page',
'https://adblockplus.org/donate',
), (
'update_page',
'https://new.adblockplus.org/update',
), (
'first_run_page',
'https://welcome.adblockplus.org/installed'
)]
| test_data = [('donation_page', 'https://adblockplus.org/donate'), ('update_page', 'https://new.adblockplus.org/update'), ('first_run_page', 'https://welcome.adblockplus.org/installed')] |
"""
Author: Ramiz Raja
Created on: 29/02/2020
"""
def fibonnoci_sum():
rangeEnd = 10_000
prev_prev_fibonnoci = 0
prev_fibonnoci = 1
total_sum = 1
next_fibonnoci = 1
while next_fibonnoci < rangeEnd:
if next_fibonnoci % 2 != 0:
total_sum += next_fibonnoci
prev_prev_f... | """
Author: Ramiz Raja
Created on: 29/02/2020
"""
def fibonnoci_sum():
range_end = 10000
prev_prev_fibonnoci = 0
prev_fibonnoci = 1
total_sum = 1
next_fibonnoci = 1
while next_fibonnoci < rangeEnd:
if next_fibonnoci % 2 != 0:
total_sum += next_fibonnoci
prev_prev_fib... |
set_name(0x800A2AB8, "VID_OpenModule__Fv", SN_NOWARN)
set_name(0x800A2B78, "InitScreens__Fv", SN_NOWARN)
set_name(0x800A2C68, "MEM_SetupMem__Fv", SN_NOWARN)
set_name(0x800A2C94, "SetupWorkRam__Fv", SN_NOWARN)
set_name(0x800A2D24, "SYSI_Init__Fv", SN_NOWARN)
set_name(0x800A2E30, "GM_Open__Fv", SN_NOWARN)
set_name(0x800A... | set_name(2148149944, 'VID_OpenModule__Fv', SN_NOWARN)
set_name(2148150136, 'InitScreens__Fv', SN_NOWARN)
set_name(2148150376, 'MEM_SetupMem__Fv', SN_NOWARN)
set_name(2148150420, 'SetupWorkRam__Fv', SN_NOWARN)
set_name(2148150564, 'SYSI_Init__Fv', SN_NOWARN)
set_name(2148150832, 'GM_Open__Fv', SN_NOWARN)
set_name(214815... |
class SpatialElementTag(Element, IDisposable):
""" A tag attached to an SpatialElement (room,space or area) in Autodesk Revit. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def getBoundingBox(self, *args):
""" getBoundingBox(self: Element,view: View) ... | class Spatialelementtag(Element, IDisposable):
""" A tag attached to an SpatialElement (room,space or area) in Autodesk Revit. """
def dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def get_bounding_box(self, *args):
""" getBoundingBox(self: Element,view: View) -> Bou... |
# basic stack implementation
# author: D1N3SHh
# https://github.com/D1N3SHh/algorithms
class StackOverflowError(BaseException):
pass
class StackEmptyError(BaseException):
pass
class Stack():
def __init__(self, max_size = 10):
self.max_size = max_size
self.s = []
def __repr__(self):... | class Stackoverflowerror(BaseException):
pass
class Stackemptyerror(BaseException):
pass
class Stack:
def __init__(self, max_size=10):
self.max_size = max_size
self.s = []
def __repr__(self):
return str(self.s)
def push(self, x):
if len(self.s) < self.max_size:
... |
class UniquenessError(ValueError):
def __init__(self, index_name):
ValueError.__init__(self, index_name)
class NotFoundError(KeyError):
pass
| class Uniquenesserror(ValueError):
def __init__(self, index_name):
ValueError.__init__(self, index_name)
class Notfounderror(KeyError):
pass |
"""
The module implements exceptions for Zserio python runtime library.
"""
class PythonRuntimeException(Exception):
"""
Exception thrown in case of an error in Zserio python runtime library.
"""
| """
The module implements exceptions for Zserio python runtime library.
"""
class Pythonruntimeexception(Exception):
"""
Exception thrown in case of an error in Zserio python runtime library.
""" |
# encoding: utf-8
# module System.Collections.Generic calls itself Generic
# from mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Microsoft.Bcl.AsyncInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b... | class Comparer(object, IComparer, IComparer[T]):
def compare(self, x, y):
""" Compare(self: Comparer[T], x: T, y: T) -> int """
pass
@staticmethod
def create(comparison):
""" Create(comparison: Comparison[T]) -> Comparer[T] """
pass
def __cmp__(self, *args):
""... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Resellers',
'category': 'Sales',
'website': 'https://www.odoo.com/page/website-builder',
'summary': 'Publish Your Channel of Resellers',
'version': '1.0',
'description': """
Publish and... | {'name': 'Resellers', 'category': 'Sales', 'website': 'https://www.odoo.com/page/website-builder', 'summary': 'Publish Your Channel of Resellers', 'version': '1.0', 'description': '\nPublish and Assign Partner\n==========================\n ', 'depends': ['base_geolocalize', 'crm', 'account', 'portal', 'website_p... |
class DataTemplate(FrameworkTemplate,INameScope,ISealable,IHaveResources,IQueryAmbient):
"""
Describes the visual structure of a data object.
DataTemplate()
DataTemplate(dataType: object)
"""
def ValidateTemplatedParent(self,*args):
"""
ValidateTemplatedParent(self: DataTemplate,templatedParent:... | class Datatemplate(FrameworkTemplate, INameScope, ISealable, IHaveResources, IQueryAmbient):
"""
Describes the visual structure of a data object.
DataTemplate()
DataTemplate(dataType: object)
"""
def validate_templated_parent(self, *args):
"""
ValidateTemplatedParent(self: DataTemplate,templ... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'market_platform_backend',
'USER': 'postgres',
'HOST': 'postgres',
'PORT': '5432',
'PASSWORD': ''
}
}
CELERY_BROKER_URL = 'redis://redis:6379'
CELERY_RESULT_BACKEND = 'redis://redis:637... | databases = {'default': {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'market_platform_backend', 'USER': 'postgres', 'HOST': 'postgres', 'PORT': '5432', 'PASSWORD': ''}}
celery_broker_url = 'redis://redis:6379'
celery_result_backend = 'redis://redis:6379'
debug = False |
numero = int(input("Digite um numero para calcular tabuada: "))
tab = 0
while (tab <= 10):
print (tab ,"X",numero,"=", numero * tab)
tab +=1
| numero = int(input('Digite um numero para calcular tabuada: '))
tab = 0
while tab <= 10:
print(tab, 'X', numero, '=', numero * tab)
tab += 1 |
SPACE = 20
def print_stand_species(summary_stand):
formatted = ['STAND METRICS']
for i, row in enumerate(summary_stand):
formatted.append(''.join([j + (' ' * (SPACE - len(j))) for j in row]))
if i == 0 or i == len(summary_stand) - 2:
formatted.append('-' * (SPACE * len(row)))
r... | space = 20
def print_stand_species(summary_stand):
formatted = ['STAND METRICS']
for (i, row) in enumerate(summary_stand):
formatted.append(''.join([j + ' ' * (SPACE - len(j)) for j in row]))
if i == 0 or i == len(summary_stand) - 2:
formatted.append('-' * (SPACE * len(row)))
re... |
def hashadNum(num):
digitSum = sum([int(k) for k in str(num)])
if num % digitSum == 0:
return True
else:
return False
n = int(input())
while not (hashadNum(n)):
n += 1
print(n) | def hashad_num(num):
digit_sum = sum([int(k) for k in str(num)])
if num % digitSum == 0:
return True
else:
return False
n = int(input())
while not hashad_num(n):
n += 1
print(n) |
'''
Matrix:
Count the number of islands in a matrix
'''
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def getIsland(i,j):
if 0<=i<len(grid) and 0<=j<len(grid[0]) and grid[i][j]=='1':
grid[i][j]='0'
... | """
Matrix:
Count the number of islands in a matrix
"""
class Solution:
def num_islands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def get_island(i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and (grid[i][j] == '1'):
g... |
def parseExpression(expression):
operators = ['**', '+', '-', '*', '/', '%']
operator = '+'
for currOperator in operators:
if expression.__contains__(currOperator):
operator = currOperator
break
if bool(operator):
operands = expression.split(operator)
... | def parse_expression(expression):
operators = ['**', '+', '-', '*', '/', '%']
operator = '+'
for curr_operator in operators:
if expression.__contains__(currOperator):
operator = currOperator
break
if bool(operator):
operands = expression.split(operator)
return... |
# -*- coding: utf-8 -*-
# --- Slack configuration ---
# get your own at https://api.slack.com/docs/oauth-test-tokens
SLACK_TOKEN = "xoxp-XXX"
# the channel Slasher will send its messages to
SLACK_CHANNEL = "#random"
# Slasher's username
SLACK_USERNAME = "Slasher"
# Slasher's icon
SLACK_USER_EMOJI = ":robot_face:"
#... | slack_token = 'xoxp-XXX'
slack_channel = '#random'
slack_username = 'Slasher'
slack_user_emoji = ':robot_face:'
giphy_tags = ['fireworks', 'guitar'] |
S = input().split()
N = int(input())
print(*S)
for _ in range(N):
next_S = input().split()
for i in range(4):
p = i // 2
q = i % 2
if S[p] == next_S[q]:
next_S[q] = S[p^1]
S = next_S
print(*S)
break
else:
assert(False)
| s = input().split()
n = int(input())
print(*S)
for _ in range(N):
next_s = input().split()
for i in range(4):
p = i // 2
q = i % 2
if S[p] == next_S[q]:
next_S[q] = S[p ^ 1]
s = next_S
print(*S)
break
else:
assert False |
"""Websocket errors"""
class WebSocketInternalError(Exception):
"""Exception raised for a WebSocket internal error"""
| """Websocket errors"""
class Websocketinternalerror(Exception):
"""Exception raised for a WebSocket internal error""" |
class User:
"""
class that generates new instances of user
"""
user_list=[]
def __init__(self,first_name,last_name,create_pw,confirm_pw):
'''
__init__ method that helps us define properties for our objects.
Args:
first_name: New user first name.
... | class User:
"""
class that generates new instances of user
"""
user_list = []
def __init__(self, first_name, last_name, create_pw, confirm_pw):
"""
__init__ method that helps us define properties for our objects.
Args:
first_name: New user first name.
... |
"""
Problem:
Given an array L with n elements. Inversion occurs when L[i] > L[j] when 0 < i < j < n.
Example:
count_inversions([1,3,5,2,4,6]) -> 3
Explanation: 3 pairs of inversions (3,2), (5,3), (5,4)
"""
def count_inversions(elems: list[any]) -> int:
# return the number of inversions in the array without mutati... | """
Problem:
Given an array L with n elements. Inversion occurs when L[i] > L[j] when 0 < i < j < n.
Example:
count_inversions([1,3,5,2,4,6]) -> 3
Explanation: 3 pairs of inversions (3,2), (5,3), (5,4)
"""
def count_inversions(elems: list[any]) -> int:
return _count(elems)[1]
def _count(elems: list[any]) -> tuple... |
#!/usr/bin/env python
# coding: utf-8
# p677
class MapSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self._kv = dict() # type: dict
self._prefix = dict() # type: dict
def insert(self, key, val):
"""
:type key: str
:type ... | class Mapsum:
def __init__(self):
"""
Initialize your data structure here.
"""
self._kv = dict()
self._prefix = dict()
def insert(self, key, val):
"""
:type key: str
:type val: int
:rtype: void
"""
dv = val - self._kv.get(... |
def start() :
driverType = irr.driverChoiceConsole();
if driverType == irr.EDT_COUNT :
return 1;
device = irr.createDevice(driverType, irr.dimension2d_u32(640, 480));
if device == None :
return 1;
driver = device.getVideoDriver();
smgr = device.getSceneManager();
device.getFileSystem().addZi... | def start():
driver_type = irr.driverChoiceConsole()
if driverType == irr.EDT_COUNT:
return 1
device = irr.createDevice(driverType, irr.dimension2d_u32(640, 480))
if device == None:
return 1
driver = device.getVideoDriver()
smgr = device.getSceneManager()
device.getFileSystem... |
class Node():
def __init__(self, name):
self.name = name
self.possValues = []
self.value = ""
self.parents = []
self.children = []
self.CPD = {}
# variables for use in Variable Elimination
self.inDeg = 0
self.used = False
| class Node:
def __init__(self, name):
self.name = name
self.possValues = []
self.value = ''
self.parents = []
self.children = []
self.CPD = {}
self.inDeg = 0
self.used = False |
# first development commit
# first feature commit
my_str_var = ""
new_var_feature = ""
another_var_feature = ""
def some_function(mylist=[]):
_mylist = mylist
for x in _mylist:
print(f"x is {x}")
mylist = ['one', 'two', 'three', 'four']
# here is another section
a_var = 0
b_var = 1
c_var = a_var + b... | my_str_var = ''
new_var_feature = ''
another_var_feature = ''
def some_function(mylist=[]):
_mylist = mylist
for x in _mylist:
print(f'x is {x}')
mylist = ['one', 'two', 'three', 'four']
a_var = 0
b_var = 1
c_var = a_var + b_var
print(f'c_var {c_var}')
d_var = 4
e_var = 1
f_var = d_var - e_var
print(f'... |
def convert24(time):
if time[-2:] == "AM" and time[:2] == "12":
return "00" + time[2:-2]
elif time[-2:] == "AM":
return time[:-2]
elif time[-2:] == "PM" and time[:2] == "12":
return time[:-2]
else:
return str(int(time[:2]) + 12) + tim... | def convert24(time):
if time[-2:] == 'AM' and time[:2] == '12':
return '00' + time[2:-2]
elif time[-2:] == 'AM':
return time[:-2]
elif time[-2:] == 'PM' and time[:2] == '12':
return time[:-2]
else:
return str(int(time[:2]) + 12) + time[2:6]
tc = int(input())
while tc > 0:... |
# encoding: utf-8
class Config(object):
# Number of results to fetch from API
RESULT_COUNT = 9
# How long to cache results for
CACHE_MAX_AGE = 20 # seconds
ICON = "2B939AF4-1A27-4D41-96FE-E75C901C780F.png"
GOOGLE_ICON = "google.png"
# Algolia credentials
ALGOLIA_APP_ID = "BH4D9OD16A"
... | class Config(object):
result_count = 9
cache_max_age = 20
icon = '2B939AF4-1A27-4D41-96FE-E75C901C780F.png'
google_icon = 'google.png'
algolia_app_id = 'BH4D9OD16A'
algolia_search_only_api_key = '1d8534f83b9b0cfea8f16498d19fbcab'
algolia_search_index = 'material-ui' |
############################ data loading ########################################
train_subject_ids = [1,6,7,8,9,11]
""" training subject ids """
test_subject_ids = [5]
"""test subject id"""
omit_one_hot = False
"""one-hot encoding when loading human3.6m dataset"""
############################ model #############... | train_subject_ids = [1, 6, 7, 8, 9, 11]
' training subject ids '
test_subject_ids = [5]
'test subject id'
omit_one_hot = False
'one-hot encoding when loading human3.6m dataset'
architecture = 'basic'
'architecture version: Seq2seq architecture to use: [basic, tied]'
human_size = 54
'human size'
source_seq_len = 50
'inp... |
'''input
100 4 16
4554
'''
'''input
20 2 5
84
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem B
def sum_digit(number):
string = str(number)
array = list(map(int, list(string)))
return sum(array)
if __name__ == '__main__':
N, A, B = list(map(int, input().split... | """input
100 4 16
4554
"""
'input\n20 2 5\n84\n'
def sum_digit(number):
string = str(number)
array = list(map(int, list(string)))
return sum(array)
if __name__ == '__main__':
(n, a, b) = list(map(int, input().split()))
total = 0
for number in range(1, N + 1):
if A <= sum_digit(number) <... |
SITE_TITLE = "Awesome Boilerplates"
FRAMEWORK_TITLE = ""
RESTRICT_PACKAGE_EDITORS = False
RESTRICT_GRID_EDITORS = False
ADMINS = [
("Vinta", "awesomeboilerplates@vinta.com.br"),
]
| site_title = 'Awesome Boilerplates'
framework_title = ''
restrict_package_editors = False
restrict_grid_editors = False
admins = [('Vinta', 'awesomeboilerplates@vinta.com.br')] |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def store_inorder(root, inorder):
if root is None:
return
store_inorder(root.left, inorder)
inorder.append(root.data)
store_inorder(root.right, inorder)
def count_nodes(root):... | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def store_inorder(root, inorder):
if root is None:
return
store_inorder(root.left, inorder)
inorder.append(root.data)
store_inorder(root.right, inorder)
def count_nodes(root):
... |
# To store registered users
registered_users = {}
# To store User staus Ture for Login & False for Logout
user_status = {}
user_account = {}
def total_users():
return len(registered_users)
| registered_users = {}
user_status = {}
user_account = {}
def total_users():
return len(registered_users) |
grid = [
['W', 'L', 'W', 'W', 'W'],
['W', 'L', 'W', 'W', 'W'],
['W', 'W', 'W', 'L', 'W'],
['W', 'W', 'L', 'L', 'W'],
['L', 'W', 'W', 'L', 'L'],
['L', 'L', 'W', 'W', 'W'],
]
visited_land = []
def minimum_island(grid):
min = 100
for i in range(0, len(grid)):
for j in range(0, l... | grid = [['W', 'L', 'W', 'W', 'W'], ['W', 'L', 'W', 'W', 'W'], ['W', 'W', 'W', 'L', 'W'], ['W', 'W', 'L', 'L', 'W'], ['L', 'W', 'W', 'L', 'L'], ['L', 'L', 'W', 'W', 'W']]
visited_land = []
def minimum_island(grid):
min = 100
for i in range(0, len(grid)):
for j in range(0, len(grid[0])):
coun... |
params = dict()
class Param(object):
def __init__(self, name, value=None):
self._name = name
self._value = value
params[self.format()] = self
@property
def name(self):
return self._name
def format(self):
string = self.name
if self.value is not None:
... | params = dict()
class Param(object):
def __init__(self, name, value=None):
self._name = name
self._value = value
params[self.format()] = self
@property
def name(self):
return self._name
def format(self):
string = self.name
if self.value is not None:
... |
def _expand_batchnorm_weights(model_dict, state_dict, num_splits):
"""Expands the weights of the BatchNorm2d to the size of SplitBatchNorm.
"""
running_mean = 'running_mean'
running_var = 'running_var'
for key, item in model_dict.items():
# not batchnorm -> continue
if not runnin... | def _expand_batchnorm_weights(model_dict, state_dict, num_splits):
"""Expands the weights of the BatchNorm2d to the size of SplitBatchNorm.
"""
running_mean = 'running_mean'
running_var = 'running_var'
for (key, item) in model_dict.items():
if not running_mean in key and (not running_var in... |
# Databricks notebook source
BGBQHOWGGFSMHPYXGTO
NZPBFOKMJLRQHTARPERJDKKJQZPZKYQCWGGKJLOJJGHLJABIYDVAYNJVEYPYNYHIEWTJHFMDBEJXY
YGPGFWXAJUKFLCXFPXDGXTEVNVRFKDXIYKLYACCVXBWTDQOQHXDNIJXRLNXBFSLJYR
EDQHGMWXXKNBGRPVWTVEYCIQJCENTCTADVYPELTBKBMSXQNCRTZGCMFGGEJIGIVKMIEBSWQPJOGQNEXRUEGOALGKVKQPTOZMLVQKCNKLQHNWIZOPPYI
VPOCQGWW... | BGBQHOWGGFSMHPYXGTO
NZPBFOKMJLRQHTARPERJDKKJQZPZKYQCWGGKJLOJJGHLJABIYDVAYNJVEYPYNYHIEWTJHFMDBEJXY
YGPGFWXAJUKFLCXFPXDGXTEVNVRFKDXIYKLYACCVXBWTDQOQHXDNIJXRLNXBFSLJYR
EDQHGMWXXKNBGRPVWTVEYCIQJCENTCTADVYPELTBKBMSXQNCRTZGCMFGGEJIGIVKMIEBSWQPJOGQNEXRUEGOALGKVKQPTOZMLVQKCNKLQHNWIZOPPYI
VPOCQGWWXEJUUXXEUDYXOQBBKBEUUDRGYWHKMGJ... |
def test_correct_message():
pass
def test_incorrect_field():
pass
| def test_correct_message():
pass
def test_incorrect_field():
pass |
class Edge:
def __init__(self, v1: int, v2: int, f1: int, f2: int, p1: int, p2: int):
self.v1 = v1
self.v2 = v2
self.f1 = f1
self.f2 = f2
self.p1 = p1
self.p2 = p2
def __repr__(self):
return f'<Edge v=({self.v1}, {self.v2}) f=({self.f1}, {self.f2}) p=({se... | class Edge:
def __init__(self, v1: int, v2: int, f1: int, f2: int, p1: int, p2: int):
self.v1 = v1
self.v2 = v2
self.f1 = f1
self.f2 = f2
self.p1 = p1
self.p2 = p2
def __repr__(self):
return f'<Edge v=({self.v1}, {self.v2}) f=({self.f1}, {self.f2}) p=({s... |
"""
Copyright 2020 InfAI (CC SES)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in... | """
Copyright 2020 InfAI (CC SES)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in... |
def min_max_from_inputV2():
inp_list = []
while True:
string_num = input('Enter a number: ')
if string_num == 'done':
break
try:
num = int(string_num)
except:
print('Invalid input')
continue
inp_list.append(num)
... | def min_max_from_input_v2():
inp_list = []
while True:
string_num = input('Enter a number: ')
if string_num == 'done':
break
try:
num = int(string_num)
except:
print('Invalid input')
continue
inp_list.append(num)
maximum... |
""" Quiz: Create Usernames
Write a for loop that iterates over the names list to create a usernames list. To create a username for each name, make everything lowercase and replace spaces with underscores. Running your for loop over the list:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"... | """ Quiz: Create Usernames
Write a for loop that iterates over the names list to create a usernames list. To create a username for each name, make everything lowercase and replace spaces with underscores. Running your for loop over the list:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"... |
"""
TESTS is a dict with all you tests.
Keys for this will be categories' names.
Each test is dict with
"input" -- input data for user function
"answer" -- your right answer
"explanation" -- not necessary key, it's using for additional info in animation.
"""
TESTS = {
"Basics": [
{
... | """
TESTS is a dict with all you tests.
Keys for this will be categories' names.
Each test is dict with
"input" -- input data for user function
"answer" -- your right answer
"explanation" -- not necessary key, it's using for additional info in animation.
"""
tests = {'Basics': [{'input': [3, 2], 'answer': 5... |
#
# PySNMP MIB module RFC-HIPPI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC-HIPPI-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:56:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, constraints_union, value_range_constraint) ... |
n,k=list(map(int,input().split()))
s=list(map(int,input().split()))
ans=int(len([i for i in s if 5-i>=k])/3)
print(ans)
| (n, k) = list(map(int, input().split()))
s = list(map(int, input().split()))
ans = int(len([i for i in s if 5 - i >= k]) / 3)
print(ans) |
def add(a, b):
return a + b
add()
def add(a, b):
print(a+b)
def say_hello():
print("hello")
say_hello()
| def add(a, b):
return a + b
add()
def add(a, b):
print(a + b)
def say_hello():
print('hello')
say_hello() |
"""Common utilities for creating J2CL targets and providers."""
load(":j2cl_transpile.bzl", "J2CL_TRANSPILE_ATTRS", "j2cl_transpile")
load(":j2cl_js_common.bzl", "J2CL_JS_ATTRS", "JS_PROVIDER_NAME", "j2cl_js_provider")
# Constructor for the Bazel provider for J2CL.
# Note that data under "_private_" considered privat... | """Common utilities for creating J2CL targets and providers."""
load(':j2cl_transpile.bzl', 'J2CL_TRANSPILE_ATTRS', 'j2cl_transpile')
load(':j2cl_js_common.bzl', 'J2CL_JS_ATTRS', 'JS_PROVIDER_NAME', 'j2cl_js_provider')
j2cl_info = provider(fields=['_private_'])
def _impl_j2cl_library(ctx):
js_srcs = []
java_sr... |
class Goods(object):
__slots__ = ('id', 'name', 'price')
def __init__(self,id,name,price):
self.id=id
self.name=name
self.price=price | class Goods(object):
__slots__ = ('id', 'name', 'price')
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price |
# configuration file for interface "jms_1"
# this file exists as a reference for configuring JMS interfaces
#
# copy this file to your own cage, possibly renaming into
# config_interface_YOUR_INTERFACE_NAME.py, then modify the copy
#
# this particular configuration works with OpenMQ and file-based JNDI
config = dict \... | config = dict(protocol='jms', java='C:\\JDK\\BIN\\java.exe', arguments=('-Dfile.encoding=windows-1251',), classpath='c:\\pythomnic3k\\lib;c:\\pythomnic3k\\lib\\jms.jar;c:\\pythomnic3k\\lib\\imq.jar;c:\\pythomnic3k\\lib\\fscontext.jar', jndi={'java.naming.factory.initial': 'com.sun.jndi.fscontext.RefFSContextFactory', '... |
class RecordBatchUpdate:
""" Event generated each time when record is created/update with new release """
def __init__(self, request, records):
self.request = request
self.records = records
| class Recordbatchupdate:
""" Event generated each time when record is created/update with new release """
def __init__(self, request, records):
self.request = request
self.records = records |
'''
Created on May 1, 2016
@author: Drew
'''
PlayBtnPos = (0, 0, 0.0)
PlayBtnHidePos = (0, 0, -1.1)
OptionsBtnPos = (-.9, 0, -0.6)
OptionsBtnHidePos = (-.9, 0, -1.7)
DiscordBtnPos = (-.3, 0, -0.6)
DiscordBtnHidePos = (-.3, 0, -1.7)
CreditsBtnPos = (.3, 0, -0.6)
CreditsBtnHidePos = (.3, 0, -1.7)
QuitBtnPos = (.9, ... | """
Created on May 1, 2016
@author: Drew
"""
play_btn_pos = (0, 0, 0.0)
play_btn_hide_pos = (0, 0, -1.1)
options_btn_pos = (-0.9, 0, -0.6)
options_btn_hide_pos = (-0.9, 0, -1.7)
discord_btn_pos = (-0.3, 0, -0.6)
discord_btn_hide_pos = (-0.3, 0, -1.7)
credits_btn_pos = (0.3, 0, -0.6)
credits_btn_hide_pos = (0.3, 0, -1.... |
# @Author: Ozan YILDIZ@2022
# Boolean Variable Literal Examples
booleanTrue = True
booleanFalse = False
four = True + 3
two = False - 0
trueResult = (four == 4)
falseResult = (two == 3)
if __name__ == '__main__':
print("Boolean True (True)", booleanTrue)
print("Boolean False (False)", booleanFalse)
print("F... | boolean_true = True
boolean_false = False
four = True + 3
two = False - 0
true_result = four == 4
false_result = two == 3
if __name__ == '__main__':
print('Boolean True (True)', booleanTrue)
print('Boolean False (False)', booleanFalse)
print('Four:', four)
print('Two:', two)
print('True result:', tr... |
# -*- coding: utf-8 -*-
# Copyright 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | _ip_address_schema = {'type': 'string', 'format': 'ipv4'}
_net_address_schema = {'type': 'string', 'pattern': '^(({octet}\\.){{3}}{octet})({prefix})?$'.format(octet='(2(5[0-5]|[0-4][0-9])|[01]?[0-9][0-9]?)', prefix='/(3[012]|[12]?[0-9])')}
_mac_address_schema = {'type': 'string', 'pattern': '^([0-9A-Fa-f]{2}[:-]){5}([0... |
#! /usr/bin/env python3
# Largest product in a series
# Problem 8
# Find the greatest product of five consecutive digits in the 1000-digit number.
digits = """
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540... | digits = '\n73167176531330624919225119674426574742355349194934\n96983520312774506326239578318016984801869478851843\n85861560789112949495459501737958331952853208805511\n12540698747158523863050715693290963295227443043557\n66896648950445244523161731856403098711121722383113\n622298934233803081353362766142828064444866452387... |
# Employees salute when they "cross".
# Hallway exits do not count.
# Key algorithms: regular expression, counting, indexing
# For each > (right-going employee),
# count < (left-going employee).
# Then double the total encounters (because they greet "each other").
# string.count("char")
# list.index(element)
# stri... | example_salute = '--->-><-><-->-'
test_salute1 = '>----<'
test_salute2 = '<<>><'
def solution(s):
hall = s.replace('-', '')
crosses = 0
for (i, char) in enumerate(hall):
if char == '>':
crosses += hall[i:].count('<')
salutes = crosses * 2
return salutes
print(solution(example_sa... |
tweet_at = '@Attribution'
tweet_url = 'https://example.com/additional-url'
tweet_hashtag = '#MyHashtag'
tweet_data = [
{ 'image': 'https://example.com/image.jpg',
'id': 'image_id',
'title': 'Example title',
'desc': 'Example description with lots of text that probably goes well over the 280 character lim... | tweet_at = '@Attribution'
tweet_url = 'https://example.com/additional-url'
tweet_hashtag = '#MyHashtag'
tweet_data = [{'image': 'https://example.com/image.jpg', 'id': 'image_id', 'title': 'Example title', 'desc': 'Example description with lots of text that probably goes well over the 280 character limit. The python scr... |
def rabbit_pairs(n,k):
if(n==1):
return 1
if(n==2):
return 1
else:
return k*rabbit_pairs(n-2,k)+rabbit_pairs(n-1,k)
def main():
with open('datasets/rosalind_fib.txt') as input_data:
n,k=map(int,input_data.read().strip().split())
# n=5
# k=3
pairs=str... | def rabbit_pairs(n, k):
if n == 1:
return 1
if n == 2:
return 1
else:
return k * rabbit_pairs(n - 2, k) + rabbit_pairs(n - 1, k)
def main():
with open('datasets/rosalind_fib.txt') as input_data:
(n, k) = map(int, input_data.read().strip().split())
pairs = str(rabbit_... |
def digits_product(product):
if product<10:
return 10+product
res=factorization(product)
for i in res:
if i>=10:
return -1
reduce(res)
total=0
for i,j in enumerate(res):
total+=10**(len(res)-i-1)*j
return total
def factorization(n):
res=[]
factor=2... | def digits_product(product):
if product < 10:
return 10 + product
res = factorization(product)
for i in res:
if i >= 10:
return -1
reduce(res)
total = 0
for (i, j) in enumerate(res):
total += 10 ** (len(res) - i - 1) * j
return total
def factorization(n):... |
a=10
b=20
a+b #addition
a/b #divde
a-b #substraction
a*b #multiplication
a%b #reminder
a**b #exponent
a//b #floor devision
| a = 10
b = 20
a + b
a / b
a - b
a * b
a % b
a ** b
a // b |
NEW_FEATURES = [3, 5, 6, 7]
FEATURES = [
1, # L
2, # S
4, # B
8, # A
3, # LS
5, # LB
6, # SB
9, # LA
9, # LA
9, # LA
9, # LA
9, # LA
10, # SA
10, # SA
10, # SA
10, # SA
10, # SA
12, # BA
12, # BA
12, # BA
12, # BA
... | new_features = [3, 5, 6, 7]
features = [1, 2, 4, 8, 3, 5, 6, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 12, 12, 12, 12, 12, 7, 11, 11, 11, 11, 13, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 15]
new_weights = [None, None, None, None]
weights = [None, None, None, None, [0.3, 0.7], [0.3, 0.7], [0.3, 0.7], None, [0.6, 0.4], [... |
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
res = []
if not nums:
return nums
nums = nums + [nums[-1]+2]
head = nums[0]
for i in range(1,len(nums)):
if nums[i]-nums[i-1]>1:
if head ==nums[i-1]:
... | class Solution:
def summary_ranges(self, nums: List[int]) -> List[str]:
res = []
if not nums:
return nums
nums = nums + [nums[-1] + 2]
head = nums[0]
for i in range(1, len(nums)):
if nums[i] - nums[i - 1] > 1:
if head == nums[i - 1]:
... |
"""
Class which holds loop data regarding stamp names and accumulated times
on a per-iteration basis.
"""
class Loop(object):
"""Hold info for name checking and assigning."""
def __init__(self, name=None, rgstr_stamps=None, save_itrs=True):
self.name = None if name is None else str(name)
sel... | """
Class which holds loop data regarding stamp names and accumulated times
on a per-iteration basis.
"""
class Loop(object):
"""Hold info for name checking and assigning."""
def __init__(self, name=None, rgstr_stamps=None, save_itrs=True):
self.name = None if name is None else str(name)
self.... |
class Solution:
"""
@param candidates: A list of integers
@param target: An integer
@return: A list of lists of integers
"""
def combinationSum(self, candidates, target):
candidates.sort()
n = len(candidates)
solutions = []
self.dfs(candidates, n, 0, target, [], s... | class Solution:
"""
@param candidates: A list of integers
@param target: An integer
@return: A list of lists of integers
"""
def combination_sum(self, candidates, target):
candidates.sort()
n = len(candidates)
solutions = []
self.dfs(candidates, n, 0, target, [],... |
#!/usr/bin
# -*- coding: utf-8 -*-
"""
DelftStack Python Tkinter Tutorial
Author: Jinku Hu
URL: https://www.delftstack.com/tutorial/python-3-basic-tutorial/namescape-and-scope/
Website: https://www.delftstack.com
"""
x = 1
y = 2
stringX = "String X"
def globalTest():
for (key, value) in globals().items():
... | """
DelftStack Python Tkinter Tutorial
Author: Jinku Hu
URL: https://www.delftstack.com/tutorial/python-3-basic-tutorial/namescape-and-scope/
Website: https://www.delftstack.com
"""
x = 1
y = 2
string_x = 'String X'
def global_test():
for (key, value) in globals().items():
print('{} - {}'.format(key, valu... |
"""
27 Petya and Strings - https://codeforces.com/problemset/problem/112/A
"""
one = input().lower()
two = input().lower()
if one < two:
print("-1")
elif one > two:
print("1")
else:
print("0")
| """
27 Petya and Strings - https://codeforces.com/problemset/problem/112/A
"""
one = input().lower()
two = input().lower()
if one < two:
print('-1')
elif one > two:
print('1')
else:
print('0') |
def quick_sort(arr, a, b):
if a >= b: return
pivot = arr[(a+b)//2]
left = a
right = b
while True:
while arr[left] < pivot: left += 1
while pivot < arr[right]: right -= 1
if left >= right: break
arr[left], arr[right] = arr[right], arr[left]
left += 1
... | def quick_sort(arr, a, b):
if a >= b:
return
pivot = arr[(a + b) // 2]
left = a
right = b
while True:
while arr[left] < pivot:
left += 1
while pivot < arr[right]:
right -= 1
if left >= right:
break
(arr[left], arr[right]) = ... |
# This file serves as an example for what's needed in your secrets.py file.
# You can make a copy of this and rename it secrets.py.
# Create an application at https://discord.com/developers/applications
# Then go to the `bot` section of your app and see the token.
DISCORD_TOKEN = 'YOUR TOKEN HERE'
# Create a client ... | discord_token = 'YOUR TOKEN HERE'
blizzard_client_id = 'YOUR TOKEN HERE'
blizzard_client_secret = 'YOUR TOKEN HERE' |
class Curve_Colors():
##!
##! Set colors
##!
def Curve_Colors_Take(self,colordefs):
bcolor=self.BackGround_Color()
for color in colordefs.keys():
self.Color_Schemes[ bcolor ][ color ]=colordefs[ color ]
##!
##! Sets Analytical Evolute colors.
##!
... | class Curve_Colors:
def curve__colors__take(self, colordefs):
bcolor = self.BackGround_Color()
for color in colordefs.keys():
self.Color_Schemes[bcolor][color] = colordefs[color]
def evolute__analytical__colors(self):
bcolor = self.BackGround_Color()
self.Curve_Colo... |
valores = []
while True:
valores.append(int(input('Digite um valor:')))
resp = str(input('Quer continuar: ')).upper()[0]
if resp == 'N':
break
pares = []
impares = []
for v in valores:
if v % 2 == 0:
pares.append(v)
else:
impares.append(v)
print(f'Os valores digitados foram {... | valores = []
while True:
valores.append(int(input('Digite um valor:')))
resp = str(input('Quer continuar: ')).upper()[0]
if resp == 'N':
break
pares = []
impares = []
for v in valores:
if v % 2 == 0:
pares.append(v)
else:
impares.append(v)
print(f'Os valores digitados foram {... |
# SWEA 2050
string = input()
for c in string:
print(ord(c) - ord("A") + 1, end=" ")
| string = input()
for c in string:
print(ord(c) - ord('A') + 1, end=' ') |
'''
Write a Python function named printAsterisks that is passed a positive integer value n, and prints
out a line of n asterisks. If n is greater than 75, then only 75 asterisks should be displayed.
'''
def printAsterix(n):
return '*'*(n if n<75 else 75)
print(printAsterix(int(input("Enter number: "))))
| """
Write a Python function named printAsterisks that is passed a positive integer value n, and prints
out a line of n asterisks. If n is greater than 75, then only 75 asterisks should be displayed.
"""
def print_asterix(n):
return '*' * (n if n < 75 else 75)
print(print_asterix(int(input('Enter number: ')))) |
def consecutive_elements_opt(arr,k):
window_sum=0
for i in range(k):
window_sum+=arr[i]
max_sum=window_sum
for j in range(k,len(arr)):
window_sum=window_sum-arr[j-k]+arr[j]
print(arr[j-k],arr[j])
max_sum=max(max_sum,window_sum)
return max_sum
... | def consecutive_elements_opt(arr, k):
window_sum = 0
for i in range(k):
window_sum += arr[i]
max_sum = window_sum
for j in range(k, len(arr)):
window_sum = window_sum - arr[j - k] + arr[j]
print(arr[j - k], arr[j])
max_sum = max(max_sum, window_sum)
return max_sum
inp... |
"""
FILE: assign02.py
AUTHOR: Carlos W. Mercado
PROCESSING:
- Informs the average commercial rate in a file.
- Informs data about the utility companies with
the highest and lowest commercial rates.
"""
def average_comm_rate(filename):
'''
INPUT: The name of a file.
PROCESSING:
... | """
FILE: assign02.py
AUTHOR: Carlos W. Mercado
PROCESSING:
- Informs the average commercial rate in a file.
- Informs data about the utility companies with
the highest and lowest commercial rates.
"""
def average_comm_rate(filename):
"""
INPUT: The name of a file.
PROCESSING:
... |
#
# PySNMP MIB module REDSTONE-TEMPLATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDSTONE-TEMPLATE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:55:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection, constraints_union) ... |
"""Script containing the base detector kernel class."""
class KernelDetector(object):
"""Docstring
"""
def __init__(self, master_kernel):
"""DocString
"""
self.master_kernel = master_kernel
self.kernel_api = None
def pass_api(self, kernel_api):
"""DocString
... | """Script containing the base detector kernel class."""
class Kerneldetector(object):
"""Docstring
"""
def __init__(self, master_kernel):
"""DocString
"""
self.master_kernel = master_kernel
self.kernel_api = None
def pass_api(self, kernel_api):
"""DocString
... |
# --------------
def palindrome(num):
if num < 9:
num = num+1
return num
else:
while(str(num) != str(num)[::-1]):
num = num + 1
return int(num)
palindrome(13456)
# --------------
def a_scramble(str_1,str_2):
result=True
for i in (str_2.lower()):
... | def palindrome(num):
if num < 9:
num = num + 1
return num
else:
while str(num) != str(num)[::-1]:
num = num + 1
return int(num)
palindrome(13456)
def a_scramble(str_1, str_2):
result = True
for i in str_2.lower():
if i not in str_1.lower():
... |
class Auth(object):
def __init__(self, values=None):
self.values = values or {}
def __setattr__(self, name, value):
if name != "values":
self.values[name] = value
else:
super().__setattr__(name, value)
def __getattribute__(self, key):
if key != "valu... | class Auth(object):
def __init__(self, values=None):
self.values = values or {}
def __setattr__(self, name, value):
if name != 'values':
self.values[name] = value
else:
super().__setattr__(name, value)
def __getattribute__(self, key):
if key != 'val... |
d = int(input())
a, b = map(int, input().split())
result = 10 ** 15
for i in range(d + 1):
result = min(result, i * a + (d - i) * b)
print(result)
| d = int(input())
(a, b) = map(int, input().split())
result = 10 ** 15
for i in range(d + 1):
result = min(result, i * a + (d - i) * b)
print(result) |
# import sys
# print(sys.version)
ok_result = ['to','be','or','not','to','be','that','is','the','question']
initial = [ 'not','to','be', 'is','that','the','question']
# add missing
result=['to','be','or']
result.extend(initial)
# miss.reverse()
# for m in miss:
# result.insert(0,m)
# flip 6,7
flip=result[6]
resul... | ok_result = ['to', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'the', 'question']
initial = ['not', 'to', 'be', 'is', 'that', 'the', 'question']
result = ['to', 'be', 'or']
result.extend(initial)
flip = result[6]
result[6] = result[7]
result[7] = flip
print(result) |
"""
worldcup2014.mat
It is the playing ground model of soccer.
points: N * 2, points in the model, for example, line intersections
line_segment_index: N * 2, line segment start/end point index
grid_points: a group of 2D points uniformly sampled inside of the playing ground.
It is used to approximate the a... | """
worldcup2014.mat
It is the playing ground model of soccer.
points: N * 2, points in the model, for example, line intersections
line_segment_index: N * 2, line segment start/end point index
grid_points: a group of 2D points uniformly sampled inside of the playing ground.
It is used to approximate the a... |
"""
PUP Plugin defining Windows packaging stages.
"""
class Steps:
@staticmethod
def usable_in(ctx):
return (
(ctx.pkg_platform == 'win32') and
(ctx.tgt_platform == 'win32')
)
def __call__(self, ctx, _dsp):
return (
'pup.python-runtime',
... | """
PUP Plugin defining Windows packaging stages.
"""
class Steps:
@staticmethod
def usable_in(ctx):
return ctx.pkg_platform == 'win32' and ctx.tgt_platform == 'win32'
def __call__(self, ctx, _dsp):
return ('pup.python-runtime', 'win.distribution-layout', 'pup.pip-install', 'pup.install-c... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
DATA_HEAD_LENGTH = 16
def encode_image_array(image_shape=None):
if image_shape is not None:
# TODO:
return None
return None
def data_receive_length(data_head=None):
if data_head is not None:
# TODO:
return 0
return 0
def de... | data_head_length = 16
def encode_image_array(image_shape=None):
if image_shape is not None:
return None
return None
def data_receive_length(data_head=None):
if data_head is not None:
return 0
return 0
def decode_image_array(image_array=None, data_head=None):
if image_array is not ... |
##########################
# 141. Linked List Cycle
##########################
# # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# class Solution(object):
# def hasCycle(self, head):
# """
# :type head: Li... | class Minstack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = float('inf')
def push(self, x):
"""
:type x: int
:rtype: void
"""
if self.stack == []:
self.min = floa... |
class Solution:
def Rob(self, nums, m, n) -> int:
prev, curr = nums[m], max(nums[m], nums[m + 1])
for i in range(m + 2, n):
prev, curr = curr, max(prev + nums[i], curr)
return curr
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
... | class Solution:
def rob(self, nums, m, n) -> int:
(prev, curr) = (nums[m], max(nums[m], nums[m + 1]))
for i in range(m + 2, n):
(prev, curr) = (curr, max(prev + nums[i], curr))
return curr
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return ... |
# TODO
def test_DAI(DAI, accounts):
assert DAI.decimals() == 18
DAI._mint_for_testing(10000000, {'from': accounts[0]})
assert DAI.balanceOf(accounts[0]) == 10000000
tx = DAI.transfer(accounts[1], 1000, {'from': accounts[0]})
assert tx.return_value is True
def test_USDT(USDT, accounts):
as... | def test_dai(DAI, accounts):
assert DAI.decimals() == 18
DAI._mint_for_testing(10000000, {'from': accounts[0]})
assert DAI.balanceOf(accounts[0]) == 10000000
tx = DAI.transfer(accounts[1], 1000, {'from': accounts[0]})
assert tx.return_value is True
def test_usdt(USDT, accounts):
assert USDT.dec... |
# HTML tag to default to if no prefix is found
md_default_tag = "p"
# Markdown to HTML key
md_html = [
("#", "h1"),
("##", "h2"),
("###", "h3"),
("####", "h4"),
("#####", "h5"),
("######", "h6"),
("`", "code"),
("*", "i"),
("**", "strong"),
("~~", "strike"),
("-", "li")
... | md_default_tag = 'p'
md_html = [('#', 'h1'), ('##', 'h2'), ('###', 'h3'), ('####', 'h4'), ('#####', 'h5'), ('######', 'h6'), ('`', 'code'), ('*', 'i'), ('**', 'strong'), ('~~', 'strike'), ('-', 'li')] |
def solve(string):
z, o = 0, 0
for c in string:
if c == '0':
z+=1
else:
o+=1
if z == 1 or o == 1:
return "Yes"
else:
return "No"
if __name__ == "__main__":
T = int(input())
for t in range(0,T):
D = input()
print(solve(D))... | def solve(string):
(z, o) = (0, 0)
for c in string:
if c == '0':
z += 1
else:
o += 1
if z == 1 or o == 1:
return 'Yes'
else:
return 'No'
if __name__ == '__main__':
t = int(input())
for t in range(0, T):
d = input()
print(sol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.