content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def judgeCircle(self, moves: str) -> bool:
h_pos = 0
v_pos = 0
for move in moves:
if move == 'U':
v_pos += 1
elif move == 'D':
v_pos -= 1
elif move == 'L':
h_pos -= 1
elif... | class Solution:
def judge_circle(self, moves: str) -> bool:
h_pos = 0
v_pos = 0
for move in moves:
if move == 'U':
v_pos += 1
elif move == 'D':
v_pos -= 1
elif move == 'L':
h_pos -= 1
elif move =... |
morning = {'Java', 'C', 'Ruby', 'Lisp', 'C#'}
afternoon = {'Python', 'C#', 'Java', 'C', 'Ruby'}
print(morning ^ afternoon)
print(morning.symmetric_difference(afternoon))
| morning = {'Java', 'C', 'Ruby', 'Lisp', 'C#'}
afternoon = {'Python', 'C#', 'Java', 'C', 'Ruby'}
print(morning ^ afternoon)
print(morning.symmetric_difference(afternoon)) |
"""
DO NOT COMMIT THIS FILE WITH INFORMATION FILLED OUT!
DO NOT COMMIT THIS FILE WITH INFORMATION FILLED OUT!
DO NOT COMMIT THIS FILE WITH INFORMATION FILLED OUT!
DO NOT COMMIT THIS FILE WITH INFORMATION FILLED OUT!
"""
DB_USERNAME = ''
DB_PASSWORD = ''
SECRET_KEY = ''
| """
DO NOT COMMIT THIS FILE WITH INFORMATION FILLED OUT!
DO NOT COMMIT THIS FILE WITH INFORMATION FILLED OUT!
DO NOT COMMIT THIS FILE WITH INFORMATION FILLED OUT!
DO NOT COMMIT THIS FILE WITH INFORMATION FILLED OUT!
"""
db_username = ''
db_password = ''
secret_key = '' |
# https://www.hackerrank.com/challenges/equal-stacks
def equal_stacks(stacks):
stacks_size = [sum(stack) for stack in stacks]
while len(set(stacks_size)) > 1:
higher = stacks_size.index(max(stacks_size))
poped = stacks[higher].pop(0)
stacks_size[higher] -= poped
return stacks_size... | def equal_stacks(stacks):
stacks_size = [sum(stack) for stack in stacks]
while len(set(stacks_size)) > 1:
higher = stacks_size.index(max(stacks_size))
poped = stacks[higher].pop(0)
stacks_size[higher] -= poped
return stacks_size[0]
(n1, n2, n3) = map(int, input().strip().split(' '))
... |
#!/usr/env/bin python3
#
#-----------------------------------------------------------------------
#
# Mathematical and physical constants.
#
#-----------------------------------------------------------------------
#
# Pi.
pi_geom = 3.14159265358979323846264338327
# Degrees per radian.
degs_per_radian = 360.0 / (2.0 ... | pi_geom = 3.141592653589793
degs_per_radian = 360.0 / (2.0 * pi_geom)
radius__earth = 6371200.0
valid_vals_boolean = [True, False] |
#!/usr/local/bin/python3.4
"""
## Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO [, ANY ADDITIONAL AFFILIATION]
## ALL RIGHTS RESERVED.
##
## 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
##
##... | """
## Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO [, ANY ADDITIONAL AFFILIATION]
## ALL RIGHTS RESERVED.
##
## 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/l... |
# common.py
#
# Module common infrastructure
#
_FORMATTERS = dict()
def register_formatter(descriptor):
"""Decorator that registers a formatter class"""
def passthrough(cls):
_FORMATTERS[descriptor] = cls
return cls
return passthrough
def get_formatter(descriptor):
if not descriptor i... | _formatters = dict()
def register_formatter(descriptor):
"""Decorator that registers a formatter class"""
def passthrough(cls):
_FORMATTERS[descriptor] = cls
return cls
return passthrough
def get_formatter(descriptor):
if not descriptor in _FORMATTERS:
print('descriptor must b... |
x = 1
for i in range (0, 5):
y = 7
for j in range (0, 3):
print(f"I={x} J={y}")
y -= 1
x += 2
| x = 1
for i in range(0, 5):
y = 7
for j in range(0, 3):
print(f'I={x} J={y}')
y -= 1
x += 2 |
n = int(input("enter a no: "))
for i in range (n*10, n-1 ,-n):
print(i)
| n = int(input('enter a no: '))
for i in range(n * 10, n - 1, -n):
print(i) |
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
bad = set()
for index, c in enumerate(s):
if c == "(":
stack.append(index)
elif c == ")":
if len(stack) > 0:
stack.pop()
els... | class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
stack = []
bad = set()
for (index, c) in enumerate(s):
if c == '(':
stack.append(index)
elif c == ')':
if len(stack) > 0:
stack.pop()
... |
#
# Copyright (C) 2018 The Android Open Source Project
#
# 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 la... | layout = bool_scalar('layout', False)
i1 = input('op1', 'TENSOR_FLOAT32', '{1, 3, 3, 2}')
f1 = parameter('op2', 'TENSOR_FLOAT32', '{1, 2, 2, 4}', [0.25, 0.0, 0.2, 0.0, 0.25, 0.0, 0.0, 0.3, 0.25, 0.0, 0.0, 0.0, 0.25, 0.1, 0.0, 0.0])
b1 = parameter('op3', 'TENSOR_FLOAT32', '{4}', [1, 2, 3, 4])
o1 = output('op4', 'TENSOR_... |
class Arrival:
def __init__(self, time_from_stop, dist_from_stop):
self.time_from_stop = time_from_stop
self.dist_from_stop = dist_from_stop
def __repr__(self):
return f'''{self.__class__.__name__}(
{self.time_from_stop!r}, {self.dist_from_stop!r})'''
def __str__(self)... | class Arrival:
def __init__(self, time_from_stop, dist_from_stop):
self.time_from_stop = time_from_stop
self.dist_from_stop = dist_from_stop
def __repr__(self):
return f'{self.__class__.__name__}(\n {self.time_from_stop!r}, {self.dist_from_stop!r})'
def __str__(self):
... |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-cord_cell'
ES_DOC_TYPE = 'cell'
API_PREFIX = 'cord_cell'
API_VERSION = ''
| es_host = 'localhost:9200'
es_index = 'pending-cord_cell'
es_doc_type = 'cell'
api_prefix = 'cord_cell'
api_version = '' |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@author : zzw
@time : 2019/8/3 14:33
@file : __init__.py
@description :
"""
__version__ = "0.1.0"
| """
@author : zzw
@time : 2019/8/3 14:33
@file : __init__.py
@description :
"""
__version__ = '0.1.0' |
num1 = 11
num2 = 22
num3 = 33
num4 = 44
num5 = 55
num6 = 66
num7 = 77
num8 = 88
num10 = 100
numm11 = 111
| num1 = 11
num2 = 22
num3 = 33
num4 = 44
num5 = 55
num6 = 66
num7 = 77
num8 = 88
num10 = 100
numm11 = 111 |
def make_style_sheet():
style = """
body {
font-family: Helvetica, arial, sans-serif;
font-size: 14px;
line-height: 1.6;
padding-top: 10px;
padding-bottom: 10px;
background-color: white;
padding: 30px;
color: #333;
}
body > *:first-child {
margin-... | def make_style_sheet():
style = '\n body {\n font-family: Helvetica, arial, sans-serif;\n font-size: 14px;\n line-height: 1.6;\n padding-top: 10px;\n padding-bottom: 10px;\n background-color: white;\n padding: 30px;\n color: #333;\n }\n\n body > *:first-child {\n ... |
class Instrumentable (object):
def __init__(self):
self.instrumentation = []
def add_instrumentation(self, ins):
self.instrumentation.append(ins)
def get_context(self):
return []
def initialize_instrumentation(self):
for i in self.instrumentation: i.ini... | class Instrumentable(object):
def __init__(self):
self.instrumentation = []
def add_instrumentation(self, ins):
self.instrumentation.append(ins)
def get_context(self):
return []
def initialize_instrumentation(self):
for i in self.instrumentation:
i.initial... |
model = dict(
type='FasterRCNN',
pretrained='open-mmlab://msra/hrnetv2_w32',
backbone=dict(
type='HRNet',
extra=dict(
stage1=dict(
num_modules=1,
num_branches=1,
block='BOTTLENECK',
num_blocks=(4, ),
... | model = dict(type='FasterRCNN', pretrained='open-mmlab://msra/hrnetv2_w32', backbone=dict(type='HRNet', extra=dict(stage1=dict(num_modules=1, num_branches=1, block='BOTTLENECK', num_blocks=(4,), num_channels=(64,)), stage2=dict(num_modules=1, num_branches=2, block='BASIC', num_blocks=(4, 4), num_channels=(32, 64)), sta... |
# Create by Zwlin
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print(' '.join(parts))
data = ['ACME', 50, 91.1]
print(','.join(str(d) for d in data))
print('a','b','c',sep=":")
def sample():
yield 'Is'
yield 'Chicago'
yield 'Not'
yield 'Chicago?'
print(' '.join(sample()))
def combine(source,maxsi... | parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print(' '.join(parts))
data = ['ACME', 50, 91.1]
print(','.join((str(d) for d in data)))
print('a', 'b', 'c', sep=':')
def sample():
yield 'Is'
yield 'Chicago'
yield 'Not'
yield 'Chicago?'
print(' '.join(sample()))
def combine(source, maxsize):
parts = ... |
bot1_wieght_layer_one = [[0.9236090789486788, 0.9210637151227483, 0.16119690767556938, 0.8891669007445379, 0.7530696859511529, 0.9684743676682231, 0.9140001906787625, 0.5462343790375778, 0.4625067913831683, 0.10294585839313619, 0.4659734634943964, 0.673851063496881, 0.4119975257359164, 0.4119836779033137, 0.78659108761... | bot1_wieght_layer_one = [[0.9236090789486788, 0.9210637151227483, 0.16119690767556938, 0.8891669007445379, 0.7530696859511529, 0.9684743676682231, 0.9140001906787625, 0.5462343790375778, 0.4625067913831683, 0.10294585839313619, 0.4659734634943964, 0.673851063496881, 0.4119975257359164, 0.4119836779033137, 0.78659108761... |
# Copyright (c) 2018, WSO2 Inc. (http://wso2.com) All Rights Reserved.
#
# 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 ap... | ns = {'d': 'http://maven.apache.org/POM/4.0.0'}
zip_file_extension = '.zip'
carbon_name = 'carbon.zip'
wso2_server = 'bin/wso2server'
value_tag = '{http://maven.apache.org/POM/4.0.0}value'
surface_plugin_artifact_id = 'maven-surefire-plugin'
product_storage_dir_name = 'storage'
deployment_property_file_name = 'deployme... |
class A:
def __init__(self):
self.l=[1,2,3,4,5,6,7,8,9]
def __getitem__(self,i):
if isinstance(i,int):
return self.l[i]
else:
print(i.start,i.stop,i.step)
return self.l[i]
a=A()
#for i in a.l:
# print(i,end='\t')
print(a[4])
print(a[:])
print(a[2:])
print(a[:5])
print(a[3:8])
print(a[::2])
print(a[:4... | class A:
def __init__(self):
self.l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def __getitem__(self, i):
if isinstance(i, int):
return self.l[i]
else:
print(i.start, i.stop, i.step)
return self.l[i]
a = a()
print(a[4])
print(a[:])
print(a[2:])
print(a[:5])
print(... |
NAME = 'diary.py'
ORIGINAL_AUTHORS = [
'Angelo Giacco'
]
ABOUT = '''
Keeps a record of your diary
'''
COMMANDS = '''
>>>.diary record <diary entry>
Adds to that day's diary entry
>>>.diary show <date>
Will show the diary entry of specified date (can also accept "today", "yesterday")
>>>.diary delete
Will delet... | name = 'diary.py'
original_authors = ['Angelo Giacco']
about = '\nKeeps a record of your diary\n'
commands = '\n>>>.diary record <diary entry>\nAdds to that day\'s diary entry\n\n>>>.diary show <date>\nWill show the diary entry of specified date (can also accept "today", "yesterday")\n\n>>>.diary delete\nWill delete to... |
#
# PySNMP MIB module DLINK-3100-SOCKET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-SOCKET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:49:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint, constraints_union) ... |
class DirectedEdge:
def __init__(self, v, w, weight):
self.v = v
self.w = w
self.weight = weight
def from_v(self):
return self.v
def to_v(self):
return self.w
def get_weight(self):
return self.weight
def compare_to(self, that):
return self... | class Directededge:
def __init__(self, v, w, weight):
self.v = v
self.w = w
self.weight = weight
def from_v(self):
return self.v
def to_v(self):
return self.w
def get_weight(self):
return self.weight
def compare_to(self, that):
return self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------------------
#
# ,--.
# | |-. ,---. ,---. ,--.--.,--,--,
# | .-. '| .-. :| .-. || .--'| \
# | `-' |\ --.' '-' '| | ... | __author__ = 'Peter Antoine'
__copyright__ = 'Copyright 2014-2021, Peter Antoine'
__credits__ = ['Peter Antoine']
__license__ = 'MIT'
__version__ = '1.5.0'
__maintainer__ = 'Peter Antoine'
__email__ = 'github@peterantoine.me.uk'
__url__ = 'https://github.com/PAntoine/BeornLib'
__status__ = 'Development' |
# Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module provides the global variable options_for_unittests.
This is set to a BrowserOptions object by the test harness, or None
if unit tests are not... | """This module provides the global variable options_for_unittests.
This is set to a BrowserOptions object by the test harness, or None
if unit tests are not running.
This allows multiple unit tests to use a specific
browser, in face of multiple options."""
_options = []
def push(options):
_options.append(options... |
# Ali
# Adobis's Mission I: The Room of Tragedy
# not sure what function this room has but it has no portals
sm.sendNext("Why are you here? You shouldn't be here..")
sm.warp(211000000) # warps to El Nath | sm.sendNext("Why are you here? You shouldn't be here..")
sm.warp(211000000) |
class DuplicateCategoryException(Exception):
"""Exception indicating a Category of the same name exists."""
class DuplicateTallyException(Exception):
"""Exception for creating a tally that exists under the same category."""
| class Duplicatecategoryexception(Exception):
"""Exception indicating a Category of the same name exists."""
class Duplicatetallyexception(Exception):
"""Exception for creating a tally that exists under the same category.""" |
# Input
boss = {'h': 58, 'd': 9}
play = {'h': 50, 'm': 500}
spell = [
{'m': 53, 'd': 4, 'a': 0, 't': 1, 'h': 0},
{'m': 73, 'd': 2, 'a': 0, 't': 1, 'h': 2},
{'m': 113, 'd': 0, 'a': 7, 't': 6, 'h': 0},
{'m': 173, 'd': 3, 'a': 0, 't': 6, 'h': 0},
{'m': 229, 'd': 0, 'a': 0, 't': 5, 'h': 101}
]... | boss = {'h': 58, 'd': 9}
play = {'h': 50, 'm': 500}
spell = [{'m': 53, 'd': 4, 'a': 0, 't': 1, 'h': 0}, {'m': 73, 'd': 2, 'a': 0, 't': 1, 'h': 2}, {'m': 113, 'd': 0, 'a': 7, 't': 6, 'h': 0}, {'m': 173, 'd': 3, 'a': 0, 't': 6, 'h': 0}, {'m': 229, 'd': 0, 'a': 0, 't': 5, 'h': 101}] |
def permutations(s):
if len(s) == 1:
return [s]
result = []
for char in s:
tail_list = permutations(s.replace(char, ''))
mapped = list(map(lambda x : char + x, tail_list))
result += mapped
return result
if __name__ == '__main__':
print(permutations('abc')) | def permutations(s):
if len(s) == 1:
return [s]
result = []
for char in s:
tail_list = permutations(s.replace(char, ''))
mapped = list(map(lambda x: char + x, tail_list))
result += mapped
return result
if __name__ == '__main__':
print(permutations('abc')) |
load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
load("//dotnet/private:copy_files.bzl", "copy_files")
load(
"//dotnet:selenium-dotnet-version.bzl",
"SUPPORTED_NET_FRAMEWORKS",
"SUPPORTED_NET_STANDARD_VERSIONS",
)
def _nuget_push_impl(ctx):
args = [
"push",
]
apikey... | load('@bazel_skylib//rules:common_settings.bzl', 'BuildSettingInfo')
load('//dotnet/private:copy_files.bzl', 'copy_files')
load('//dotnet:selenium-dotnet-version.bzl', 'SUPPORTED_NET_FRAMEWORKS', 'SUPPORTED_NET_STANDARD_VERSIONS')
def _nuget_push_impl(ctx):
args = ['push']
apikey = ctx.attr.api_key[BuildSettin... |
# Copyright 2011 Google Inc. All Rights Reserved.
#
# 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 a... | subinclude('//javascript/externs/builddefs:BUILD')
subinclude('//javascript/closure/builddefs:BUILD')
debug_compiler_defs = CLOSURE_COMPILER_FLAGS_UNOBFUSCATED + ['--generate_exports']
optimized_compiler_defs = CLOSURE_COMPILER_FLAGS_STRICT + ['--generate_exports']
compiler_defs = DEBUG_COMPILER_DEFS + ['--aggressive_v... |
encoded_colors = {
'black': 0,
'brown': 1,
'red': 2,
'orange': 3,
'yellow': 4,
'green': 5,
'blue': 6,
'violet': 7,
'grey': 8,
'white': 9
}
def color_code(color):
"""
Resistors have color coded bands, where each color maps to a... | encoded_colors = {'black': 0, 'brown': 1, 'red': 2, 'orange': 3, 'yellow': 4, 'green': 5, 'blue': 6, 'violet': 7, 'grey': 8, 'white': 9}
def color_code(color):
"""
Resistors have color coded bands, where each color maps to a number.
The first 2 bands of a resistor have a simple encoding scheme:
each co... |
def get_conclusion_page_number(doc):
for i in reversed(range(doc.pageCount)):
page = doc.loadPage(i)
text = page.getText()
text_lowered = text.lower()
if 'conclusion' in text_lowered:
return i
else:
# Page before the last page which is usually the Printing Sp... | def get_conclusion_page_number(doc):
for i in reversed(range(doc.pageCount)):
page = doc.loadPage(i)
text = page.getText()
text_lowered = text.lower()
if 'conclusion' in text_lowered:
return i
else:
return doc.pageCount - 1 |
'''
Created on Feb 26, 2014
@author: efarhan
'''
physics_events = []
def add_physics_event(event):
global physics_events
physics_events.append(event)
def get_physics_event():
global physics_events
return physics_events
def clear_physics_event():
global physics_events
del physics_events[:]
cl... | """
Created on Feb 26, 2014
@author: efarhan
"""
physics_events = []
def add_physics_event(event):
global physics_events
physics_events.append(event)
def get_physics_event():
global physics_events
return physics_events
def clear_physics_event():
global physics_events
del physics_events[:]
c... |
class SumRow(object):
"""A list that keeps track of tableQa info: db, name, type, statistics, and error status."""
def __init__(self, db, table, tableType):
if tableType == None:
tableType = 'none'
self.__row = [db, table, tableType, '', 'n/a', 'n/a', 'no']
def __repr__(self):
... | class Sumrow(object):
"""A list that keeps track of tableQa info: db, name, type, statistics, and error status."""
def __init__(self, db, table, tableType):
if tableType == None:
table_type = 'none'
self.__row = [db, table, tableType, '', 'n/a', 'n/a', 'no']
def __repr__(self):... |
def sum(a):
if a <= 1:
return 1
else:
return a+sum(a-1)
print(sum(5))
| def sum(a):
if a <= 1:
return 1
else:
return a + sum(a - 1)
print(sum(5)) |
# class Solution:
# ## with division
# def productExceptSelf(self, nums: List[int]) -> List[int]:
# N = len(nums)
# # traverse the list
# ## 1st pass, get the total product
# total_prod = 1
# zero_counter = 0
# for num in nums:
# if zero_count... | class Solution:
def product_except_self(self, nums: List[int]) -> List[int]:
n = len(nums)
output = []
zero_counter = 0
for idx in range(N):
if nums[idx] == 0:
zero_counter += 1
if zero_counter > 1:
return [0 for i in range(N)]... |
#!/usr/bin/env python3
def read_list_from_file(file_name):
f = open(file_name)
list = []
dict={}
for x in f:
list.append(x.strip())
f.close()
i=0
while i< len(list):
dict[list[i]] = list[i+1]
i=i+2
return dict
def is_verified(vin, password) -> bool:
dict = rea... | def read_list_from_file(file_name):
f = open(file_name)
list = []
dict = {}
for x in f:
list.append(x.strip())
f.close()
i = 0
while i < len(list):
dict[list[i]] = list[i + 1]
i = i + 2
return dict
def is_verified(vin, password) -> bool:
dict = read_list_from... |
class KaraboException(Exception):
"""
Base Exception thrown by the Karabo Pipeline
"""
| class Karaboexception(Exception):
"""
Base Exception thrown by the Karabo Pipeline
""" |
class Solution(object):
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
seen = set()
for em in emails:
local,domain = em.split("@")
local = local.split("+")[0].replace(".","")
seen.add(local+"@"+domain... | class Solution(object):
def num_unique_emails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
seen = set()
for em in emails:
(local, domain) = em.split('@')
local = local.split('+')[0].replace('.', '')
seen.add(local + '... |
class StringHash:
def __init__(self, text, base=997, mod=10 ** 18 + 3):
n = len(text)
self.text = text
self.base = base
self.mod = mod
self.power = [1] * (n + 2)
self.prefix_hash = [0] * (n + 2)
for i in range(1, n + 1):
self.power[i] = self.powe... | class Stringhash:
def __init__(self, text, base=997, mod=10 ** 18 + 3):
n = len(text)
self.text = text
self.base = base
self.mod = mod
self.power = [1] * (n + 2)
self.prefix_hash = [0] * (n + 2)
for i in range(1, n + 1):
self.power[i] = self.power... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-09-23 22:21:37
# Description:
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
m, n = len(matrix), len(
matrix[0]) # For general, the matrix need not be a square
def countLessO... | class Solution:
def kth_smallest(self, matrix: List[List[int]], k: int) -> int:
(m, n) = (len(matrix), len(matrix[0]))
def count_less_or_equal(x):
cnt = 0
c = n - 1
for r in range(m):
while c >= 0 and matrix[r][c] > x:
c -= 1
... |
# John McDonough
# github - movinalot
# Advent of Code 2015
testing = 0
debug = 0
day = "02"
year = "2015"
part = "1"
answer = None
with open("puzzle_data_" + day + "_" + year + ".txt") as f:
puzzle_data = f.read()
if testing:
puzzle_data = "2x3x4\n"\
"1x1x10\n"
if de... | testing = 0
debug = 0
day = '02'
year = '2015'
part = '1'
answer = None
with open('puzzle_data_' + day + '_' + year + '.txt') as f:
puzzle_data = f.read()
if testing:
puzzle_data = '2x3x4\n1x1x10\n'
if debug:
print(puzzle_data)
puzzle_data = puzzle_data.splitlines()
wrapping_paper = 0
for dimensions in puzz... |
class UserProfile:
def __init__(self, name: str = None):
self.name = name
def __str__(self):
return f"name:{self.name}" | class Userprofile:
def __init__(self, name: str=None):
self.name = name
def __str__(self):
return f'name:{self.name}' |
# Guess the encoding in .sav files created with SPSS v14 or earlier.
# Encoding information was added to the .sav file header in SPSS v15. Unicode support appeared in SPSS v16
# If the file is created on Windows [1], with SPSS v14 or older [2], and then opened on Linux/MacOS, the dict
# below is used to look up the Wi... | locale2codepage = {'af': '1252', 'af_ZA': '1252', 'am_ET': None, 'ar': '1256', 'arn_CL': '1252', 'ar_AE': '1256', 'ar_BH': '1256', 'ar_DZ': '1256', 'ar_EG': '1256', 'ar_IQ': '1256', 'ar_JO': '1256', 'ar_KW': '1256', 'ar_LB': '1256', 'ar_LY': '1256', 'ar_MA': '1256', 'ar_OM': '1256', 'ar_QA': '1256', 'ar_SA': '1256', 'a... |
#!/usr/bin/env python3
"""
Program purpose: Splits a string on ' ' and join same string with '-'
Program author : Happi Yvan
Author email :
"""
def split_and_join(some_str):
_list = some_str.split(' ')
return '-'.join(_list)
def main():
data = input("\n\tEnter a string: ")
data_joi... | """
Program purpose: Splits a string on ' ' and join same string with '-'
Program author : Happi Yvan
Author email :
"""
def split_and_join(some_str):
_list = some_str.split(' ')
return '-'.join(_list)
def main():
data = input('\n\tEnter a string: ')
data_joined = split_and_join(data)
... |
class Result:
def __init__(self, text, value):
self.text = text
self.value = value
| class Result:
def __init__(self, text, value):
self.text = text
self.value = value |
# Small alphabet r using fucntion
def for_r():
""" *'s printed in the shape of r """
for row in range(5):
for col in range(5):
if col ==1 and row !=0 or row ==0 and col in (0,2,3) or row ==1 and col ==4:
print('*',end=' ')
else:
print(' ',e... | def for_r():
""" *'s printed in the shape of r """
for row in range(5):
for col in range(5):
if col == 1 and row != 0 or (row == 0 and col in (0, 2, 3)) or (row == 1 and col == 4):
print('*', end=' ')
else:
print(' ', end=' ')
print()
def ... |
expected_output = {
'our_address': {
'10.229.1.2': {
'neighbor_address': {
'10.229.1.1': {
'demand_mode': 0,
'elapsed_time_watermarks': '0 0',
'elapsed_time_watermarks_last': 0,
'handle': 1,
... | expected_output = {'our_address': {'10.229.1.2': {'neighbor_address': {'10.229.1.1': {'demand_mode': 0, 'elapsed_time_watermarks': '0 0', 'elapsed_time_watermarks_last': 0, 'handle': 1, 'hello': 500, 'hello_hits': 544, 'holddown': 2561, 'holddown_hits': 0, 'interface': 'GigabitEthernet2', 'last_packet': {'c_bit': 1, 'd... |
# https://leetcode.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.ans = False
def backtrack(self, node, index):
if self.ans:
return
if index == len(self... |
SECRET_KEY = '00000000'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'news'
]
| secret_key = '00000000'
installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'news'] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = [1, 2, 3]
b = [*a, 4, 5, 6]
if __name__ == '__main__':
print(b)
| a = [1, 2, 3]
b = [*a, 4, 5, 6]
if __name__ == '__main__':
print(b) |
difference_list=[]
prime_num=open("/home/grey/Desktop/Primenum/prime.txt","r")
prime_list = prime_num.readlines()
length_of_primelist=len(prime_list)
def get_patterns(prime_list):
size_of_list=len(prime_list)
i=0
while(i<size_of_list-1):
d=int(prime_list[i+1])-int(prime_list[i])
difference_... | difference_list = []
prime_num = open('/home/grey/Desktop/Primenum/prime.txt', 'r')
prime_list = prime_num.readlines()
length_of_primelist = len(prime_list)
def get_patterns(prime_list):
size_of_list = len(prime_list)
i = 0
while i < size_of_list - 1:
d = int(prime_list[i + 1]) - int(prime_list[i])... |
DEPS = [
'depot_tools/depot_tools',
'depot_tools/gsutil',
'flutter/os_utils',
'flutter/zip',
'recipe_engine/buildbucket',
'recipe_engine/file',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/runtime',
'recipe_engine/step',
'recipe_engine/uuid',
]
| deps = ['depot_tools/depot_tools', 'depot_tools/gsutil', 'flutter/os_utils', 'flutter/zip', 'recipe_engine/buildbucket', 'recipe_engine/file', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/runtime', 'recipe_engine/step', 'recipe_engine/uuid'] |
class Solution:
def minTransfers(self, transactions: List[List[int]]) -> int:
balance = [0] * 21
for u, v, amount in transactions:
balance[u] -= amount
balance[v] += amount
debt = [b for b in balance if b]
def dfs(s: int) -> int:
while s < len(debt) and not debt[s]:
s += 1... | class Solution:
def min_transfers(self, transactions: List[List[int]]) -> int:
balance = [0] * 21
for (u, v, amount) in transactions:
balance[u] -= amount
balance[v] += amount
debt = [b for b in balance if b]
def dfs(s: int) -> int:
while s < len... |
_base_ = [
'../common/mstrain-poly_3x_coco_instance.py',
'../_base_/models/mask_rcnn_r50_fpn.py'
]
model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
| _base_ = ['../common/mstrain-poly_3x_coco_instance.py', '../_base_/models/mask_rcnn_r50_fpn.py']
model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101)) |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
if not head:
return head
prevNode, curr ... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_between(self, head: ListNode, m: int, n: int) -> ListNode:
if not head:
return head
(prev_node, curr) = (None, head)
while m > 1:
p... |
class FrontEnd:
def dropdown_from_dataframe(self, name, df, chosen_col):
"""
Create text to use for rendering an HTML dropdown from a DataFrame.
Render by using {{ df|safe }} in your HTML file.
Parameters
--------
name: str
Name you'd like for the dropdo... | class Frontend:
def dropdown_from_dataframe(self, name, df, chosen_col):
"""
Create text to use for rendering an HTML dropdown from a DataFrame.
Render by using {{ df|safe }} in your HTML file.
Parameters
--------
name: str
Name you'd like for the dropd... |
# 103. Binary Tree Zigzag Level Order Traversal
# Runtime: 28 ms, faster than 91.36% of Python3 online submissions for Binary Tree Zigzag Level Order Traversal.
# Memory Usage: 14.5 MB, less than 42.40% of Python3 online submissions for Binary Tree Zigzag Level Order Traversal.
# Definition for a binary tree node.
... | class Solution:
def zigzag_level_order(self, root: TreeNode) -> list[list[int]]:
if root is None:
return []
ans = []
def dfs(node: TreeNode, lvl: int) -> None:
if lvl >= len(ans):
ans.append([node.val])
elif lvl % 2 == 0:
... |
def extractEachKth(inputArray, k):
index = []
z = [x for x in range(0,len(inputArray)) if (x+1)%k!=0]
[index.append(inputArray[z[y]]) for y in range(len(z))]
return(index)
| def extract_each_kth(inputArray, k):
index = []
z = [x for x in range(0, len(inputArray)) if (x + 1) % k != 0]
[index.append(inputArray[z[y]]) for y in range(len(z))]
return index |
class intCodeVM():
def __init__(self, inp : str):
self.__input = inp
self.__instructionList = [int(i) for i in open(inp).read().split(",")]
self.__programCounter = 0
self.__correspondingInputs = {
1:3,
2:3,
3:1,
4:1,
5:2,
... | class Intcodevm:
def __init__(self, inp: str):
self.__input = inp
self.__instructionList = [int(i) for i in open(inp).read().split(',')]
self.__programCounter = 0
self.__correspondingInputs = {1: 3, 2: 3, 3: 1, 4: 1, 5: 2, 6: 2, 7: 3, 8: 3, 99: 0}
def add(inp):
... |
DATA_DIR = "C:/Users/udiyo/OneDrive - mail.tau.ac.il/Research/data"
EXTENSION = "csv.gz"
COMPRESSION = "infer"
COL_NAMES = {
0: "_id",
1: "raw_time",
2: "temperature",
3: "pressure",
4: "humidity",
5: "light",
6: "magnetic_tot",
7: "magnetic_x",
8: "magnetic_y",
9: "magnetic_z",
... | data_dir = 'C:/Users/udiyo/OneDrive - mail.tau.ac.il/Research/data'
extension = 'csv.gz'
compression = 'infer'
col_names = {0: '_id', 1: 'raw_time', 2: 'temperature', 3: 'pressure', 4: 'humidity', 5: 'light', 6: 'magnetic_tot', 7: 'magnetic_x', 8: 'magnetic_y', 9: 'magnetic_z', 10: 'acc_tot', 11: 'acc_x', 12: 'acc_y', ... |
class Settings():
class QQ():
position_a = (10,10)
position_c = (1500,10)
size = (300,400)
| class Settings:
class Qq:
position_a = (10, 10)
position_c = (1500, 10)
size = (300, 400) |
# CollatzSequence
# Objective: When entering in any number, the Collatz Sequence will evaluate down to 1.
def collatz():
try:
number = int(input("Enter number: "))
while True:
if number == 1 or number == 0:
break
elif number % 2 == 0:
numbe... | def collatz():
try:
number = int(input('Enter number: '))
while True:
if number == 1 or number == 0:
break
elif number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * n... |
"""
Entradas
Chelines--->float--->CHA
Dracmas--->float-DRG
Pesetas--->float--->PST
Salidas
Pesetas--->float---PST
Francos Franceses--->float--->FRA
dolares--->float--->USD
Liras--->float--->LIR
"""
print("Chelines a Pesetas: ")
CHA=float(input("Ingrese el valor en chelines: "))
PST=((CHA*956871)/100)
print("El valor en... | """
Entradas
Chelines--->float--->CHA
Dracmas--->float-DRG
Pesetas--->float--->PST
Salidas
Pesetas--->float---PST
Francos Franceses--->float--->FRA
dolares--->float--->USD
Liras--->float--->LIR
"""
print('Chelines a Pesetas: ')
cha = float(input('Ingrese el valor en chelines: '))
pst = CHA * 956871 / 100
print('El valo... |
class Solution:
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
ftimes = [0]*n
stack = []
pre_start_time = 0
for log in logs:
f_id, which, f_time = log.split(":")
f_id, f_time = int(f_id), int(f_time)
i... | class Solution:
def exclusive_time(self, n: int, logs: List[str]) -> List[int]:
ftimes = [0] * n
stack = []
pre_start_time = 0
for log in logs:
(f_id, which, f_time) = log.split(':')
(f_id, f_time) = (int(f_id), int(f_time))
if which == 'start':
... |
def count_chars(s: str) -> dict:
"""Checking the chars number in a str example
:param s: {str}
:return: {dict}
"""
count_dict = {}
for c in s:
if c in count_dict:
count_dict[c] += 1
else:
count_dict[c] = 1
return count_dict
| def count_chars(s: str) -> dict:
"""Checking the chars number in a str example
:param s: {str}
:return: {dict}
"""
count_dict = {}
for c in s:
if c in count_dict:
count_dict[c] += 1
else:
count_dict[c] = 1
return count_dict |
# Copyright 2013-2021 Aerospike, 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 required by applicable law or agreed to in writ... | queries = '\n/***************************************************\n* System Resource *\n****************************************************/\n// SET CONSTRAINT VERSION <= 3.8.4;\n// SET CONSTRAINT VERSION < 3.8.4;\n// SET CONSTRAINT VERSION >= 3.8.4;\n// SET CONSTRAINT VERSION > 3.8.4;... |
def part1(rows):
return go(rows, 1)
def part2(rows):
return go(rows, 2)
def go(rows, part):
position = 0
depth = 0
aim = 0
for row in rows:
command, arg = row.split()
match command, int(arg):
case "forward", value:
position += value
... | def part1(rows):
return go(rows, 1)
def part2(rows):
return go(rows, 2)
def go(rows, part):
position = 0
depth = 0
aim = 0
for row in rows:
(command, arg) = row.split()
match (command, int(arg)):
case ['forward', value]:
position += value
... |
class Solution:
# @param A : list of integers
# @return an integer
def merge(self,A, aux, low, mid, high):
k = i = low
j=mid+1
inversionCount = 0
while i <= mid and j <= high:
if A[i] <= A[j]:
aux[k] = A[i]
i = i + 1
els... | class Solution:
def merge(self, A, aux, low, mid, high):
k = i = low
j = mid + 1
inversion_count = 0
while i <= mid and j <= high:
if A[i] <= A[j]:
aux[k] = A[i]
i = i + 1
else:
aux[k] = A[j]
j =... |
lista_Itens = ['a', 'b', 'c'] #Lista Criada
for itens in lista_Itens: #for para imprimir itens da lista
print (itens)
lista_Itens.append('d')
lista_Itens.extend(['e', 'f', 'g'])
for itens in lista_Itens:
print (itens)
print ("Resultado final: {}, {}, {}, {}, {}, {}, {}.".format(lista_Itens[0], lista_Itens[1], l... | lista__itens = ['a', 'b', 'c']
for itens in lista_Itens:
print(itens)
lista_Itens.append('d')
lista_Itens.extend(['e', 'f', 'g'])
for itens in lista_Itens:
print(itens)
print('Resultado final: {}, {}, {}, {}, {}, {}, {}.'.format(lista_Itens[0], lista_Itens[1], lista_Itens[2], lista_Itens[3], lista_Itens[4], lis... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/abiantorres/Documentos/tfg/autonomous-vehicles-system-simulation/low_level_simulation/src/rosbridge_suite/rosapi/msg/TypeDef.msg"
services_str = "/home/abiantorres/Documentos/tfg/autonomous-vehicles-system-simulation/low_level_simulation/src/ros... | messages_str = '/home/abiantorres/Documentos/tfg/autonomous-vehicles-system-simulation/low_level_simulation/src/rosbridge_suite/rosapi/msg/TypeDef.msg'
services_str = '/home/abiantorres/Documentos/tfg/autonomous-vehicles-system-simulation/low_level_simulation/src/rosbridge_suite/rosapi/srv/DeleteParam.srv;/home/abianto... |
"""
The SSJ dataset has an unusual bug: all of the sentences end with SpaceAfter=no
This script fixes them and writes the fixed files to the given location.
"""
def process(input_txt, input_conllu, input_txt_copy, input_conllu_copy):
conllu_lines = open(input_conllu).readlines()
txt_lines = open(input_txt).r... | """
The SSJ dataset has an unusual bug: all of the sentences end with SpaceAfter=no
This script fixes them and writes the fixed files to the given location.
"""
def process(input_txt, input_conllu, input_txt_copy, input_conllu_copy):
conllu_lines = open(input_conllu).readlines()
txt_lines = open(input_txt).re... |
"""Ambra exceptions."""
class AmbraException(Exception):
"""Base ambra exception."""
class AmbraResponseException(AmbraException):
"""Ambra response exception."""
def __init__(self, code, description=None, response_text=None):
"""Init.
:param code: response code
:param descript... | """Ambra exceptions."""
class Ambraexception(Exception):
"""Base ambra exception."""
class Ambraresponseexception(AmbraException):
"""Ambra response exception."""
def __init__(self, code, description=None, response_text=None):
"""Init.
:param code: response code
:param descriptio... |
# https://leetcode.com/contest/weekly-contest-68/problems/reorganize-string/
class Solution:
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
# sort S by character occurrence, return value is a list
S = sorted(sorted(S), key=S.count, reverse=True)
... | class Solution:
def reorganize_string(self, S):
"""
:type S: str
:rtype: str
"""
s = sorted(sorted(S), key=S.count, reverse=True)
length = len(S)
middle = int((length - 1) / 2) + 1
res = []
(i, j) = (0, middle)
while i < middle and j <... |
# -*- coding: utf-8 -*-
def sample() -> str:
return "hoge"
def main() -> None:
print("Hello Python")
if __name__ == "__main__":
main()
| def sample() -> str:
return 'hoge'
def main() -> None:
print('Hello Python')
if __name__ == '__main__':
main() |
class Context(object):
@staticmethod
def click(x, y, new_context, ctrl):
ctrl.move(x=x, y=y)
ctrl.click()
return new_context
class MainMenu(Context):
@classmethod
def click_play(cls, ctrl):
return cls.click(x=270, y=210, new_context=LevelMenu, ctrl=ctrl)
class Lev... | class Context(object):
@staticmethod
def click(x, y, new_context, ctrl):
ctrl.move(x=x, y=y)
ctrl.click()
return new_context
class Mainmenu(Context):
@classmethod
def click_play(cls, ctrl):
return cls.click(x=270, y=210, new_context=LevelMenu, ctrl=ctrl)
class Levelme... |
class Atoi():
def myatoi(self, s: str) -> int:
start = True
ret = ""
for i in list(s):
if i == " ":
if not start:
break
elif i == "+" or i == "-":
if start:
start = False
ret =... | class Atoi:
def myatoi(self, s: str) -> int:
start = True
ret = ''
for i in list(s):
if i == ' ':
if not start:
break
elif i == '+' or i == '-':
if start:
start = False
ret = ... |
def get_patient_names(self):
"""
get the list of patient names, if self.data_names id not None, then load patient
names from that file, otherwise search all the names automatically in data_root
"""
# use pre-defined patient names
if (self.data_names is not None):
assert (os.path.isfile(self.data_names))
with ... | def get_patient_names(self):
"""
get the list of patient names, if self.data_names id not None, then load patient
names from that file, otherwise search all the names automatically in data_root
"""
if self.data_names is not None:
assert os.path.isfile(self.data_names)
with open(self.data_name... |
LIST_OF_STATES = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "S... | list_of_states = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'W... |
# Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
# def removeElements(head,val):
# while head and head.val == val:
# head = head.next
# q = head
# p = q.next
# while p:
# if p.val == val:
# ... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def remove_elements(head, val):
starter = list_node()
starter.next = head
prev = starter
curr = head
while curr:
if curr.val == val:
prev.next = curr.next
else:
... |
def main() -> None:
print("Yes" if sorted(input()) < sorted(input(), reverse=1) else "No")
if __name__ == "__main__":
main()
| def main() -> None:
print('Yes' if sorted(input()) < sorted(input(), reverse=1) else 'No')
if __name__ == '__main__':
main() |
# What are Functions?
#
# Functions are a convenient way to divide your code into useful blocks.
# That way we can reuse the code.
# Python uses indentation to define code blocks, instead of brackets
# def myFunction():
# print("Hello From My Function!")
# print("Hi")
#
# myFunction()
# def myFunctionWithArgs... | def sum_two_numbers(a, b):
return a + b
if __name__ == '__main__':
result = sum_two_numbers(5, 3)
print(result)
print(not False)
print((not False) == False) |
# A collection of functions to create displays of different ABI RGB
# products and band subtractions.
# abitrucol is derived from McIDAS-X's ABITRUCOL function
# which creates an ABI RGB by deriving a green band
# McIDAS-X's ABITRUCOL is based on the CIMSS Natural True Color method
# http://cimss.ssec.wisc.edu/goes/OC... | def abi_tru_col_rgb(red, grn, blu):
red_coef = red * 0.45
grn_coef = grn * 0.1
blu_coef = blu * 0.45
comb_grn = redCoef + grnCoef + bluCoef
red_masked = mask(red, '<', 33, 0) * red
comb_grn_masked = mask(combGrn, '<', 40, 0) * combGrn
blu_masked = mask(blu, '<', 50, 0) * blu
red_scaled1 ... |
class SolutionHashTableNaive:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
num_index1 = defaultdict(list)
for index1, num in enumerate(nums1):
num_index1[num].append(index1)
max_len = 0
for index2, num in enumerate(nums2):
for index1 in... | class Solutionhashtablenaive:
def find_length(self, nums1: List[int], nums2: List[int]) -> int:
num_index1 = defaultdict(list)
for (index1, num) in enumerate(nums1):
num_index1[num].append(index1)
max_len = 0
for (index2, num) in enumerate(nums2):
for index1 ... |
"""
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Update (2015-02-10):
The signature of the C++ function... | """
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Update (2015-02-10):
The signature of the C++ function... |
class Category:
def __init__(self, categoryId, name):
self.categoryId = categoryId
self.name = name
| class Category:
def __init__(self, categoryId, name):
self.categoryId = categoryId
self.name = name |
#########
# Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved
#
# 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... | def attr(*args, **kwargs):
"""Decorator that adds attributes to classes or functions
for use with unit tests runner.
"""
def wrapped(element):
for name in args:
setattr(element, name, True)
for (name, value) in kwargs.items():
setattr(element, name, value)
... |
# demonstrate function scope
spam = "global spam"
# local scope
def do_local():
spam = "local spam"
print(spam)
do_local()
print(spam) | spam = 'global spam'
def do_local():
spam = 'local spam'
print(spam)
do_local()
print(spam) |
class RecentCounter(object):
def __init__(self):
self.p = []
def ping(self, t):
"""
:type t: int
:rtype: int
"""
self.p.append(t)
res = 0
for s in self.p[::-1]:
if t - s > 3000:
break;
res += 1
retu... | class Recentcounter(object):
def __init__(self):
self.p = []
def ping(self, t):
"""
:type t: int
:rtype: int
"""
self.p.append(t)
res = 0
for s in self.p[::-1]:
if t - s > 3000:
break
res += 1
retur... |
class NCoverage(): # Model under test
def __init__(self, threshold = 0.2, exclude_layer=['pool', 'fc', 'flatten'], only_layer = ""):
self.cov_dict = {}
self.threshold = threshold
def scale(self, layer_outputs, rmax=1, rmin=0):
'''
scale the intermediate lay... | class Ncoverage:
def __init__(self, threshold=0.2, exclude_layer=['pool', 'fc', 'flatten'], only_layer=''):
self.cov_dict = {}
self.threshold = threshold
def scale(self, layer_outputs, rmax=1, rmin=0):
"""
scale the intermediate layer's output between 0 and 1
:param lay... |
"""
Dla pobranej liczby, sprawdz czy liczba jest ujemna, dodatnia, czy jest zerem.
"""
if __name__ == "__main__":
print("podaj liczbe")
a = int(input())
if a < 0:
print("libczba jest ujemna")
elif a > 0:
print("liczba jest dodatnia")
else:
print("liczba jest zerem")
| """
Dla pobranej liczby, sprawdz czy liczba jest ujemna, dodatnia, czy jest zerem.
"""
if __name__ == '__main__':
print('podaj liczbe')
a = int(input())
if a < 0:
print('libczba jest ujemna')
elif a > 0:
print('liczba jest dodatnia')
else:
print('liczba jest zerem') |
class Question:
# Defines the init function that is called each time a new object is created
def __init__(self, text, correct_answer):
# The attribute text is initialized with the value of the parameter text
self.text = text
# The attribute answer is initialized with the value of the p... | class Question:
def __init__(self, text, correct_answer):
self.text = text
self.answer = correct_answer |
'''
This is the __init__.py file for the PyCSW common scripts.
author :kballantyne
date :20190304
version :1.1
python_version :2.7.5
#================================================================================================================
'''
__all__ = ['pycsw_func'] | """
This is the __init__.py file for the PyCSW common scripts.
author :kballantyne
date :20190304
version :1.1
python_version :2.7.5
#================================================================================================================
"""
__all__ = ['pycsw_func'] |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
arr = []
... | class Solution:
def sort_list(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
arr = []
while head:
arr.append(head.val)
head = head.next
arr.sort()
new = cur = list_node()
for ele in... |
i = 10
while i >= 0:
print(i)
i = i - 1
| i = 10
while i >= 0:
print(i)
i = i - 1 |
"""
Contains the EnzymeLookup class.
"""
class EnzymeLookup():
"""
This is the enzyme lookup class. It is a reverse lookup table that loads
an enzyme data from the path given to its initialize operator. In turn a
find method is supplied that looks up any matching names.
"""
###########... | """
Contains the EnzymeLookup class.
"""
class Enzymelookup:
"""
This is the enzyme lookup class. It is a reverse lookup table that loads
an enzyme data from the path given to its initialize operator. In turn a
find method is supplied that looks up any matching names.
"""
def __init__(self, pa... |
""" Contains Event class """
class Event:
""" Represents a LoTLan Event instance """
def __init__(self, logical_name, physical_name, event_type, comparator=None, value=None):
self.logical_name = logical_name
self.physical_name = physical_name
self.event_type = event_type
self.c... | """ Contains Event class """
class Event:
""" Represents a LoTLan Event instance """
def __init__(self, logical_name, physical_name, event_type, comparator=None, value=None):
self.logical_name = logical_name
self.physical_name = physical_name
self.event_type = event_type
self.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.