content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/3/9 2:37 PM
# @Author : xiaoliji
# @Email : yutian9527@gmail.com
class ListNode:
def __init__(self, x: int):
self.val = x
self.next = None
def construct_linklist(nodes: 'iterable')-> 'LinkedList':
vals = list(nodes)
head... | class Listnode:
def __init__(self, x: int):
self.val = x
self.next = None
def construct_linklist(nodes: 'iterable') -> 'LinkedList':
vals = list(nodes)
head = list_node(0)
h = head
for val in vals:
h.next = list_node(val)
h = h.next
return head.next
def pretty_... |
class Shape:
@staticmethod #define a static method before initiating an instance
def add_ally(x,y):
x.append(y)
return x
def __init__(self, shape_type):
self.shape_type=shape_type
self.__allies=[] #initiate a private empty list in an instance
@property
def allies_public(self): #make it accessibl... | class Shape:
@staticmethod
def add_ally(x, y):
x.append(y)
return x
def __init__(self, shape_type):
self.shape_type = shape_type
self.__allies = []
@property
def allies_public(self):
return self.__allies
def __create_allies(self):
return self.a... |
def vogal(letra):
if(letra=='a') or (letra=='A'):
return True
if (letra=='e') or (letra=='E'):
return True
if (letra=='i') or (letra=='I'):
return True
if (letra=='o') or (letra=='O'):
return True
if (letra=='u') or (letra=='U'):
return True
else:
... | def vogal(letra):
if letra == 'a' or letra == 'A':
return True
if letra == 'e' or letra == 'E':
return True
if letra == 'i' or letra == 'I':
return True
if letra == 'o' or letra == 'O':
return True
if letra == 'u' or letra == 'U':
return True
else:
... |
# 24. Swap Nodes in Pairs
'''
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Input: 1->2->3->4,
Output: 2->1->4->3.
'''
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
current = h... | """
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Input: 1->2->3->4,
Output: 2->1->4->3.
"""
class Solution:
def swap_pairs(self, head: ListNode) -> ListNode:
current = head
while curren... |
def encrypt_letter(msg, key):
enc_id = (ord(msg) + ord(key)) % 1114112
return chr(enc_id)
def decrypt_letter(msg, key):
dec_id = (1114112 + ord(msg) - ord(key)) % 1114112
return chr(dec_id)
def process_message(message, key, encrypt):
returned_message = ""
for i, letter in enumerate(message)... | def encrypt_letter(msg, key):
enc_id = (ord(msg) + ord(key)) % 1114112
return chr(enc_id)
def decrypt_letter(msg, key):
dec_id = (1114112 + ord(msg) - ord(key)) % 1114112
return chr(dec_id)
def process_message(message, key, encrypt):
returned_message = ''
for (i, letter) in enumerate(message):... |
def pre_save_operation(instance):
# If this is a new record, then someone has started it in the Admin using EITHER a legacy COVE ID
# OR a PBSMM UUID. Depending on which, the retrieval endpoint is slightly different, so this sets
# the appropriate URL to access.
if instance.pk is None:
if in... | def pre_save_operation(instance):
if instance.pk is None:
if instance.object_id and instance.object_id.strip():
url = __get_api_url('pbsmm', instance.object_id)
elif instance.legacy_tp_media_id:
url = __get_api_url('cove', str(instance.legacy_tp_media_id))
else:
... |
t = int(input().strip())
result = 0
current_time, current_value = 1, 3
def get_next_interval_cycle(time, value):
next_time = time + value
next_value = value * 2
return next_time, next_value
while True:
new_time, new_value = get_next_interval_cycle(
current_time,
current_value
... | t = int(input().strip())
result = 0
(current_time, current_value) = (1, 3)
def get_next_interval_cycle(time, value):
next_time = time + value
next_value = value * 2
return (next_time, next_value)
while True:
(new_time, new_value) = get_next_interval_cycle(current_time, current_value)
if new_time > ... |
def acmTeam(topic):
maxtopic, maxteam = 0, 1
for i in range(n):
for j in range(i+1, n):
know = 0
for x in range(m):
if topic[i][x] == '1' or topic[j][x] == '1':
know += 1
if know > maxtopic:
maxtopic = know
... | def acm_team(topic):
(maxtopic, maxteam) = (0, 1)
for i in range(n):
for j in range(i + 1, n):
know = 0
for x in range(m):
if topic[i][x] == '1' or topic[j][x] == '1':
know += 1
if know > maxtopic:
maxtopic = know
... |
# flake8: noqa
# tor ref src\app\config\auth_dirs.inc
AUTHORITY_DIRS = """
"moria1 orport=9101 "
"v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
"128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
"tor26 orport=443 "
"v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
"ipv6=[2001:858:2:2:... | authority_dirs = '\n"moria1 orport=9101 "\n "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "\n "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",\n"tor26 orport=443 "\n "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "\n "ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "\n "86.59.21.38:80 847B 1F8... |
def make_readable(seconds):
if seconds >= 0 and seconds <= 359999:
hrs = seconds // 3600
seconds %= 3600
mins = seconds // 60
seconds %= 60
secs = seconds
hour = str('{:02d}'.format(hrs))
minute = str('{:02d}'.format(mins))
second = str('{:02d}'.format... | def make_readable(seconds):
if seconds >= 0 and seconds <= 359999:
hrs = seconds // 3600
seconds %= 3600
mins = seconds // 60
seconds %= 60
secs = seconds
hour = str('{:02d}'.format(hrs))
minute = str('{:02d}'.format(mins))
second = str('{:02d}'.format... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Giraph(MavenPackage):
"""Apache Giraph is an iterative graph processing system built
for high scalability."... | class Giraph(MavenPackage):
"""Apache Giraph is an iterative graph processing system built
for high scalability."""
homepage = 'https://giraph.apache.org/'
url = 'https://downloads.apache.org/giraph/giraph-1.0.0/giraph-dist-1.0.0-src.tar.gz'
list_url = 'https://downloads.apache.org/giraph/'
list... |
"""
Contains config variables unique to the user.
Copy this file to config.py and make any necessary changes.
"""
PYTHON_COMMAND = "python"
| """
Contains config variables unique to the user.
Copy this file to config.py and make any necessary changes.
"""
python_command = 'python' |
"""# `//ll:ll.bzl`
Rules for building C/C++ with an upstream LLVM/Clang toolchain.
Build files should import these rules via `@rules_ll//ll:defs.bzl`.
"""
load("//ll:providers.bzl", "LlCompilationDatabaseFragmentsInfo", "LlInfo")
load(
"//ll:internal_functions.bzl",
"resolve_binary_deps",
"resolve_librar... | """# `//ll:ll.bzl`
Rules for building C/C++ with an upstream LLVM/Clang toolchain.
Build files should import these rules via `@rules_ll//ll:defs.bzl`.
"""
load('//ll:providers.bzl', 'LlCompilationDatabaseFragmentsInfo', 'LlInfo')
load('//ll:internal_functions.bzl', 'resolve_binary_deps', 'resolve_library_deps')
load(... |
epsilon_d_ = {
"epsilon": ["float", "0.03", "0.01 ... 0.3"],
}
distribution_d_ = {
"distribution": ["string", "normal", "normal, laplace, logistic, gumbel"],
}
n_neighbours_d_ = {
"n_neighbours": ["int", "3", "1 ... 10"],
}
p_accept_d_ = {
"p_accept": ["float", "0.1", "0.01 ... 0.3"],
}
repulsion_factor... | epsilon_d_ = {'epsilon': ['float', '0.03', '0.01 ... 0.3']}
distribution_d_ = {'distribution': ['string', 'normal', 'normal, laplace, logistic, gumbel']}
n_neighbours_d_ = {'n_neighbours': ['int', '3', '1 ... 10']}
p_accept_d_ = {'p_accept': ['float', '0.1', '0.01 ... 0.3']}
repulsion_factor_d = {'repulsion_factor': ['... |
def fatorial(n):
if n == 0:
return 1
else:
return n * fatorial(n - 1)
while True:
try:
entrada = input()
entrada = entrada.split()
fat1 = fatorial(int(entrada[0]))
fat2 = fatorial(int(entrada[1]))
print(fat1 + fat2)
except EOFErro... | def fatorial(n):
if n == 0:
return 1
else:
return n * fatorial(n - 1)
while True:
try:
entrada = input()
entrada = entrada.split()
fat1 = fatorial(int(entrada[0]))
fat2 = fatorial(int(entrada[1]))
print(fat1 + fat2)
except EOFError:
break |
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.end = False
self.size = 0
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
retu... | class Trienode:
def __init__(self):
self.children = [None] * 26
self.end = False
self.size = 0
class Trie:
def __init__(self):
self.root = self.getNode()
def get_node(self):
return trie_node()
def _char_to_index(self, ch):
return ord(ch) - ord('a')
... |
# coding=utf-8
"""
This is exceptions used in graph package
"""
class GraphError(Exception):
"""
This is base graph error
"""
pass
class GraphTypeError(GraphError, TypeError):
"""
This error occurs when there is a type mismatch in this package
"""
pass
class GraphExistenceError(G... | """
This is exceptions used in graph package
"""
class Grapherror(Exception):
"""
This is base graph error
"""
pass
class Graphtypeerror(GraphError, TypeError):
"""
This error occurs when there is a type mismatch in this package
"""
pass
class Graphexistenceerror(GraphError):
"""
... |
class Database:
def __init__(self, row_counts):
self.row_counts = row_counts
self.max_row_count = max(row_counts)
n_tables = len(row_counts)
self.parents = list(range(n_tables))
def merge(self, src, dst):
src_parent = self.get_parent(src)
dst_parent = self.get_pa... | class Database:
def __init__(self, row_counts):
self.row_counts = row_counts
self.max_row_count = max(row_counts)
n_tables = len(row_counts)
self.parents = list(range(n_tables))
def merge(self, src, dst):
src_parent = self.get_parent(src)
dst_parent = self.get_p... |
# index_power
# Created by JKChang
# 16/04/2018, 14:49
# Tag:
# Description: You are given an array with positive numbers and a number N. You should find the N-th power of the
# element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first
# element has the index 0.
#
... | def index_power(array, n):
"""
Find Nth power of the element with index N.
"""
if n > len(array) - 1:
return -1
return array[n] ** n
if __name__ == '__main__':
assert index_power([1, 2, 3, 4], 2) == 9, 'Square'
assert index_power([1, 3, 10, 100], 3) == 1000000, 'Cube'
assert ... |
# Find the Most Competitive Subsequence: https://leetcode.com/problems/find-the-most-competitive-subsequence/
# Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.
# An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elem... | class Solution:
def most_competitive(self, nums, k: int):
stack = []
addition = len(nums) - k
for num in nums:
while addition > 0 and len(stack) > 0 and (stack[-1] > num):
stack.pop()
addition -= 1
stack.append(num)
while len(s... |
# Copyright (c) 2018 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
"""
================================================================================
============================================================================... | """
================================================================================
================================================================================
================================================================================
"""
def grid_configure(frame, rows={}, columns={}):
"""
Put weig... |
# Template 1. preorder DFS
# O(N) / O(H)
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
arr = []
def preorder(node):
if not node:
return
arr.append(node.val)
preorder(node.left)
preorder(node.right)
pr... | class Solution:
def preorder_traversal(self, root: TreeNode) -> List[int]:
arr = []
def preorder(node):
if not node:
return
arr.append(node.val)
preorder(node.left)
preorder(node.right)
preorder(root)
return arr
class... |
"""
Macro for supporting custom resource set typically defined in Gradle via source sets.
Bazel expects all resources to be in same root `res` directory but Gradle does not have this
limitation. This macro receives directory on file system and copies the required resources to
Bazel compatible `res` folder during build... | """
Macro for supporting custom resource set typically defined in Gradle via source sets.
Bazel expects all resources to be in same root `res` directory but Gradle does not have this
limitation. This macro receives directory on file system and copies the required resources to
Bazel compatible `res` folder during build... |
"""Test Forex API"""
def test_forex_api_doc(client):
response = client.get("/api/forex/doc")
assert response.status_code == 200
def test_get_usd_rates(client):
response = client.get("/api/forex/rates/usd", follow_redirects=True)
assert response.status_code == 200
| """Test Forex API"""
def test_forex_api_doc(client):
response = client.get('/api/forex/doc')
assert response.status_code == 200
def test_get_usd_rates(client):
response = client.get('/api/forex/rates/usd', follow_redirects=True)
assert response.status_code == 200 |
with open('artistsfollowed.txt') as af:
with open('/app/tosearch.txt', 'w') as ts:
for line in af:
if 'name' in line:
line = line.strip()
line = line.replace('name: ', '')
line = line.replace('\'', '')
line = line.replace(',', '')
... | with open('artistsfollowed.txt') as af:
with open('/app/tosearch.txt', 'w') as ts:
for line in af:
if 'name' in line:
line = line.strip()
line = line.replace('name: ', '')
line = line.replace("'", '')
line = line.replace(',', '')
... |
class Evaluator:
""" A superclass for metrics evaluations"""
def __init__(self, qp_ens):
"""Class constructor.
Parameters
----------
qp_ens: qp.Ensemble object
PDFs as qp.Ensemble
"""
self._qp_ens = qp_ens
def evaluate(self): #pragma: no cover
... | class Evaluator:
""" A superclass for metrics evaluations"""
def __init__(self, qp_ens):
"""Class constructor.
Parameters
----------
qp_ens: qp.Ensemble object
PDFs as qp.Ensemble
"""
self._qp_ens = qp_ens
def evaluate(self):
"""
... |
'''a Python program to print out a set containing all the colors from color_list_1
which are not present in color_list_2'''
def main():
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print("Original set elements:")
print(color_list_1)
print(color_list_2)
pr... | """a Python program to print out a set containing all the colors from color_list_1
which are not present in color_list_2"""
def main():
color_list_1 = set(['White', 'Black', 'Red'])
color_list_2 = set(['Red', 'Green'])
print('Original set elements:')
print(color_list_1)
print(color_list_2)
pri... |
input = [
('Mamma Mia', ['ABBA']),
('Ghost Rule', ['DECO*27', 'Hatsune Miku']),
('Animals', ['Martin Garrix']),
('Remember The Name', ['Ed Sheeran', 'Eminem', '50 Cent']),
('404 Not Found', [])
]
def songTitle(song):
artists = ''
if len(song[1]) > 1:
for artist in range(len(song[1]... | input = [('Mamma Mia', ['ABBA']), ('Ghost Rule', ['DECO*27', 'Hatsune Miku']), ('Animals', ['Martin Garrix']), ('Remember The Name', ['Ed Sheeran', 'Eminem', '50 Cent']), ('404 Not Found', [])]
def song_title(song):
artists = ''
if len(song[1]) > 1:
for artist in range(len(song[1])):
artist... |
class FluidAudioDriver():
''' Represents the FluidSynth audio driver object as defined in audio.h.
This class is inspired by the FluidAudioDriver object from pyfluidsynth by MostAwesomeDude.
Member:
audio_driver -- The FluidSynth audio driver object (fluid_audio_driver_t).
handle -- The handle... | class Fluidaudiodriver:
""" Represents the FluidSynth audio driver object as defined in audio.h.
This class is inspired by the FluidAudioDriver object from pyfluidsynth by MostAwesomeDude.
Member:
audio_driver -- The FluidSynth audio driver object (fluid_audio_driver_t).
handle -- The handle t... |
class Writer:
def __init__(self, outfile):
self.outfile = outfile
def writeHeader(self):
pass
def write(self, record):
pass
def writeFooter(self):
pass
| class Writer:
def __init__(self, outfile):
self.outfile = outfile
def write_header(self):
pass
def write(self, record):
pass
def write_footer(self):
pass |
"""
Pyformlang
==========
Pyformlang is a python module to perform operation on formal languages.
How to use the documentation
----------------------------
Documentation is available in two formats: docstrings directly
in the code and a readthedocs website: https://pyformlang.readthedocs.io.
Available subpackages
-----... | """
Pyformlang
==========
Pyformlang is a python module to perform operation on formal languages.
How to use the documentation
----------------------------
Documentation is available in two formats: docstrings directly
in the code and a readthedocs website: https://pyformlang.readthedocs.io.
Available subpackages
-----... |
def b2tc(number: int):
"""
Funcion devuelve el complemento de un numero entero el cual se define como "inversion de todos los bits".
:param number: numero entero
:type number: int
:return: cadena conforme a resultado inverso de bit (XOR)
:rtype: str
"""
b2int = int(bin(number)[2:]) # [2... | def b2tc(number: int):
"""
Funcion devuelve el complemento de un numero entero el cual se define como "inversion de todos los bits".
:param number: numero entero
:type number: int
:return: cadena conforme a resultado inverso de bit (XOR)
:rtype: str
"""
b2int = int(bin(number)[2:])
x... |
a='cdef'
b='ab'
print('a'/'b')
a=8
b='ab'
print('a'/'b')
| a = 'cdef'
b = 'ab'
print('a' / 'b')
a = 8
b = 'ab'
print('a' / 'b') |
## GroupID-8 (14114002_14114068) - Abhishek Jaisingh & Tarun Kumar
## Date: April 15, 2016
## bitwise_manipulations.py - Bitwise Manipulation Functions for Travelling Salesman Problem
def size(int_type):
length = 0
count = 0
while (int_type):
count += (int_type & 1)
length += 1
int_type >... | def size(int_type):
length = 0
count = 0
while int_type:
count += int_type & 1
length += 1
int_type >>= 1
return count
def length(int_type):
length = 0
count = 0
while int_type:
count += int_type & 1
length += 1
int_type >>= 1
return lengt... |
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
result = []
for v in ops:
length = len(result)
if v == '+':
if length >= 2:
result.append(result[length-1] + result[length-2]... | class Solution:
def cal_points(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
result = []
for v in ops:
length = len(result)
if v == '+':
if length >= 2:
result.append(result[length - 1] + result[lengt... |
print("To change the data type of data")
int_data=int(input("Enter the integer data:"))
dec_data=float(input("Enter the decimal data:"))
int_str=str(int_data)
print(int_str)
dec_int=int(dec_data)
print(dec_int)
dec_str=str(dec_data) | print('To change the data type of data')
int_data = int(input('Enter the integer data:'))
dec_data = float(input('Enter the decimal data:'))
int_str = str(int_data)
print(int_str)
dec_int = int(dec_data)
print(dec_int)
dec_str = str(dec_data) |
# Time: O(l)
# Space: O(l)
# Given an integer n, find the closest integer (not including itself), which is a palindrome.
#
# The 'closest' is defined as absolute difference minimized between two integers.
#
# Example 1:
# Input: "123"
# Output: "121"
# Note:
# The input n is a positive integer represented by string, ... | class Solution(object):
def nearest_palindromic(self, n):
"""
:type n: str
:rtype: str
"""
l = len(n)
candidates = set((str(10 ** l + 1), str(10 ** (l - 1) - 1)))
prefix = int(n[:(l + 1) / 2])
for i in map(str, (prefix - 1, prefix, prefix + 1)):
... |
@dataclass
class Point:
x: int
y: int
z: int
position = property()
@position.setter
def position(self, new_value):
if type(new_value) not in (list, tuple, set):
raise TypeError
elif len(new_value) != 3:
raise ValueError
else:
self.x, ... | @dataclass
class Point:
x: int
y: int
z: int
position = property()
@position.setter
def position(self, new_value):
if type(new_value) not in (list, tuple, set):
raise TypeError
elif len(new_value) != 3:
raise ValueError
else:
(self.x, ... |
def get_sql_lite_conn_str(db_file: str):
db_file_stripped = db_file.strip()
if not db_file or not db_file_stripped:
# db_file = '../db/meet_app.db'
raise Exception("SQL lite DB file is not specified.")
return 'sqlite:///' + db_file_stripped | def get_sql_lite_conn_str(db_file: str):
db_file_stripped = db_file.strip()
if not db_file or not db_file_stripped:
raise exception('SQL lite DB file is not specified.')
return 'sqlite:///' + db_file_stripped |
# -*- coding: utf-8 -*-
__author__ = """Juan Eiros"""
__email__ = 'jeirosz@gmail.com'
| __author__ = 'Juan Eiros'
__email__ = 'jeirosz@gmail.com' |
# definitions used
# constants
DE = 'DE'
# variables
qhLen = None # number of rows of the quarter of an hour output vector (4 each hour)
header = None
zones = None
dataImport = None
dataExport = None
sumImport = None
sumExport = None
data = None
# output file names
output_file_name = 'GenerationAndLoad.csv'
# c... | de = 'DE'
qh_len = None
header = None
zones = None
data_import = None
data_export = None
sum_import = None
sum_export = None
data = None
output_file_name = 'GenerationAndLoad.csv'
countries_dict = {'AT': ['DE'], 'BE': ['FR', 'NL'], 'FR': ['BE', 'DE'], 'DE': ['AT', 'FR', 'NL'], 'NL': ['BE', 'DE']}
psrtype_mappings = {'A... |
class StructureObject:
def __init__(self, name="", dir=""):
self.name = name
self.dir = dir
def getName(self): return self.name
def getDir(self): return self.dir
def getType(self): return type(self) | class Structureobject:
def __init__(self, name='', dir=''):
self.name = name
self.dir = dir
def get_name(self):
return self.name
def get_dir(self):
return self.dir
def get_type(self):
return type(self) |
def dbl_linear(n):
u = [1]
def func(nums):
global fin
new_nums = []
for i in nums:
new_nums.append(2 * i + 1)
new_nums.append(3 * i + 1)
u.extend(new_nums)
if len(u) > n*12:
fin = list(sorted(set(u)))
else:
... | def dbl_linear(n):
u = [1]
def func(nums):
global fin
new_nums = []
for i in nums:
new_nums.append(2 * i + 1)
new_nums.append(3 * i + 1)
u.extend(new_nums)
if len(u) > n * 12:
fin = list(sorted(set(u)))
else:
func(n... |
def write(filename, content):
with open(filename, 'w') as file_object:
file_object.write(content)
def appendWrite(filename, content):
with open(filename, 'a') as file_object:
file_object.write(content)
| def write(filename, content):
with open(filename, 'w') as file_object:
file_object.write(content)
def append_write(filename, content):
with open(filename, 'a') as file_object:
file_object.write(content) |
# Copyright (c) 2021 Qianyun, Inc. All rights reserved.
# smartx
SMARTX_INSTANCE_STATE_STOPPED = 'stopped'
| smartx_instance_state_stopped = 'stopped' |
for i in range (6):
for j in range (7):
if (i==0 and j %3!=0) or (i==1 and j % 3==0) or (i-j==2) or (i+j==8):
print("*",end=" ")
else:
print(end=" ")
print()
| for i in range(6):
for j in range(7):
if i == 0 and j % 3 != 0 or (i == 1 and j % 3 == 0) or i - j == 2 or (i + j == 8):
print('*', end=' ')
else:
print(end=' ')
print() |
A, B, K = map(int, input().split())
if A >= K:
A -= K
print(A, B)
else:
A, B = 0, max(0, B - (K - A))
print(A, B)
| (a, b, k) = map(int, input().split())
if A >= K:
a -= K
print(A, B)
else:
(a, b) = (0, max(0, B - (K - A)))
print(A, B) |
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
carry = 0
for i in range(len(digits) - 1, -1, -1):
if i == len(digits) - 1:
digits[i] += 1
else:
digits[i] = digits[i] + carry
if digits[i] == 10:
di... | class Solution:
def plus_one(self, digits: List[int]) -> List[int]:
carry = 0
for i in range(len(digits) - 1, -1, -1):
if i == len(digits) - 1:
digits[i] += 1
else:
digits[i] = digits[i] + carry
if digits[i] == 10:
... |
def close(n, smallest=10, d=10):
""" A sequence is near increasing if each element but the last two is smaller than all elements
following its subsequent element. That is, element i must be smaller than elements i + 2, i + 3, i + 4, etc.
Implement close, which takes a non-negative integer n and returns the... | def close(n, smallest=10, d=10):
""" A sequence is near increasing if each element but the last two is smaller than all elements
following its subsequent element. That is, element i must be smaller than elements i + 2, i + 3, i + 4, etc.
Implement close, which takes a non-negative integer n and returns the ... |
#!/usr/bin/env python3
charlimit = 450
def isChan(chan, checkprefix):
if not chan:
return False
elif chan.startswith("#"):
return True
elif checkprefix and len(chan) >= 2 and not chan[0].isalnum() and chan[1] == "#":
return True
else:
return False
| charlimit = 450
def is_chan(chan, checkprefix):
if not chan:
return False
elif chan.startswith('#'):
return True
elif checkprefix and len(chan) >= 2 and (not chan[0].isalnum()) and (chan[1] == '#'):
return True
else:
return False |
__title__ = 'MongoFlask'
__description__ = 'A Python Flask library for connecting a MongoDB instance to a Flask application'
__url__ = 'https://github.com/juanmanuel96/mongo-flask'
__version_info__ = ('0', '1', '3')
__version__ = '.'.join(__version_info__)
__author__ = 'Juan Vazquez'
__py_version__ = 3
| __title__ = 'MongoFlask'
__description__ = 'A Python Flask library for connecting a MongoDB instance to a Flask application'
__url__ = 'https://github.com/juanmanuel96/mongo-flask'
__version_info__ = ('0', '1', '3')
__version__ = '.'.join(__version_info__)
__author__ = 'Juan Vazquez'
__py_version__ = 3 |
JournalFame = {"4" : 1200,
"5" : 2400,
"6" : 4800,
"7" : 9600,
"8" : 19200}
FameGenerated = {"4": {"2Hweapon":720, "1Hweapon":540, "BigArmor":360, "SmallArmor":180},
"5": {"2Hweapon":2880, "1Hweapon":2160, "BigArmor":1440, "SmallArmor"... | journal_fame = {'4': 1200, '5': 2400, '6': 4800, '7': 9600, '8': 19200}
fame_generated = {'4': {'2Hweapon': 720, '1Hweapon': 540, 'BigArmor': 360, 'SmallArmor': 180}, '5': {'2Hweapon': 2880, '1Hweapon': 2160, 'BigArmor': 1440, 'SmallArmor': 720}, '6': {'2Hweapon': 8640, '1Hweapon': 6480, 'BigArmor': 4320, 'SmallArmor':... |
# -*- coding: utf-8 -*-
# Copyright 2017 Vector Creations Ltd
#
# 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 applica... | """This module implements the TCP replication protocol used by synapse to
communicate between the master process and its workers (when they're enabled).
Further details can be found in docs/tcp_replication.rst
Structure of the module:
* handler.py - the classes used to handle sending/receiving commands to
... |
class ExtraException(Exception):
def __init__(self, message: str = None, **kwargs):
if message:
self.message = message
self.extra = kwargs
super().__init__(message, kwargs)
def __str__(self) -> str:
return self.message
class PackageNotFoundError(ExtraException, L... | class Extraexception(Exception):
def __init__(self, message: str=None, **kwargs):
if message:
self.message = message
self.extra = kwargs
super().__init__(message, kwargs)
def __str__(self) -> str:
return self.message
class Packagenotfounderror(ExtraException, Looku... |
class Solution:
# @param A : list of integers
# @return an integer
'''
Facebook Codelab
No hints or solutions needed
N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of ... | class Solution:
"""
Facebook Codelab
No hints or solutions needed
N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of current bulb. Given an initial state of all bulbs, find the ... |
def main():
recursion()
def recursion():
count = [0]
num = b(5, 2, count)
print(num)
# print(sum(count))
print(count[0])
def b(n, k, count):
# count.append(1) ## count the number of stack frame
count[0] += 1
if k == 0 or k == n:
print('Base Case!')
return 2
else:
return b(n-1... | def main():
recursion()
def recursion():
count = [0]
num = b(5, 2, count)
print(num)
print(count[0])
def b(n, k, count):
count[0] += 1
if k == 0 or k == n:
print('Base Case!')
return 2
else:
return b(n - 1, k - 1, count) + b(n - 1, k, count)
if __name__ == '__ma... |
#
# @lc app=leetcode.cn id=547 lang=python3
#
# [547] friend-circles
#
None
# @lc code=end | None |
"""
Memoization decorator.
"""
def memoize(f):
memos = {}
def memoized(*args):
if args not in memos: memos[args] = f(*args)
return memos[args]
return memoized
| """
Memoization decorator.
"""
def memoize(f):
memos = {}
def memoized(*args):
if args not in memos:
memos[args] = f(*args)
return memos[args]
return memoized |
class CaseInsensitiveKey( object ):
def __init__( self, key ):
self.key = key
def __hash__( self ):
return hash( self.key.lower() )
def __eq__( self, other ):
return self.key.lower() == other.key.lower()
def __str__( self ):
return self.key
GROK_PATTERN_CONF = dict()
# B... | class Caseinsensitivekey(object):
def __init__(self, key):
self.key = key
def __hash__(self):
return hash(self.key.lower())
def __eq__(self, other):
return self.key.lower() == other.key.lower()
def __str__(self):
return self.key
grok_pattern_conf = dict()
GROK_PATTERN... |
class ValueResolver:
def resolve(self, value):
if value.kind() == "id":
string = self._resolve_id_value(value)
elif value.kind() == "node":
string = f"Node({self.resolve(value.value)}.value)"
elif value.kind() == "arc":
string = f"Arc({self.resolve(value.s... | class Valueresolver:
def resolve(self, value):
if value.kind() == 'id':
string = self._resolve_id_value(value)
elif value.kind() == 'node':
string = f'Node({self.resolve(value.value)}.value)'
elif value.kind() == 'arc':
string = f'Arc({self.resolve(value.... |
""" Module docstring """
def _write_file_impl(ctx):
f = ctx.actions.declare_file("out.txt")
ctx.actions.write(f, "contents")
write_file = rule(
attrs = {},
implementation = _write_file_impl,
)
| """ Module docstring """
def _write_file_impl(ctx):
f = ctx.actions.declare_file('out.txt')
ctx.actions.write(f, 'contents')
write_file = rule(attrs={}, implementation=_write_file_impl) |
########################
### Feature combine ###
########################
#Combine Units:
df_tcad = merge_extraction(dfs=[df_tcad,df_units,gdf_16],val=['dba','type1','units','low','high','units_from_type','est_from_type','shape_area'])
replace_nan(df_tcad,['units_x','units_y','low','high'],val=0,reverse=True)
#Don't f... | df_tcad = merge_extraction(dfs=[df_tcad, df_units, gdf_16], val=['dba', 'type1', 'units', 'low', 'high', 'units_from_type', 'est_from_type', 'shape_area'])
replace_nan(df_tcad, ['units_x', 'units_y', 'low', 'high'], val=0, reverse=True)
df_tcad.units_y = np.where(df_tcad.est_from_type, np.nan, df_tcad.units_y)
df_tcad.... |
exports = {
"name": "Earth",
"aspects": {
"amulets": [
{
"item": "scholar",
"effect": "health",
"description": "Into the earth is the answer. "
"Into the earth lies existance. "
"In... | exports = {'name': 'Earth', 'aspects': {'amulets': [{'item': 'scholar', 'effect': 'health', 'description': 'Into the earth is the answer. Into the earth lies existance. Into the earth lies death and memory. Less health for opponents'}, {'item': 'stargazer', 'effect': 'hit', 'description': 'The stars blesses our earth.... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyCarputils(PythonPackage):
"""The carputils framework for running simulations with the openCARP software."""
... | class Pycarputils(PythonPackage):
"""The carputils framework for running simulations with the openCARP software."""
homepage = 'https://www.opencarp.org'
git = 'https://git.opencarp.org/openCARP/carputils.git'
maintainers = ['MarieHouillon']
version('master', branch='master')
version('oc7.0', co... |
def perfect_number(number):
printing = "It's not so perfect."
checker = number
nums = 0
proper_devisors_sum = 0
for num in range(1, int(checker)):
if int(checker) % num == 0:
nums += int(num)
if nums == int(checker):
printing = "We have a perfect number!"
return p... | def perfect_number(number):
printing = "It's not so perfect."
checker = number
nums = 0
proper_devisors_sum = 0
for num in range(1, int(checker)):
if int(checker) % num == 0:
nums += int(num)
if nums == int(checker):
printing = 'We have a perfect number!'
return p... |
# Get all available modules
# help("modules")
module_names = [ "micropython", "uhashlib", "uselect", "_onewire", "sys", "uheapq", "ustruct", "builtins", "uarray", "uio", "utime", "cmath", "ubinascii", "ujson", "utimeq", "firmware", "ubluetooth", "umachine", "uzlib", "gc", "ucollections", "uos", "hub", "uctypes", "urand... | module_names = ['micropython', 'uhashlib', 'uselect', '_onewire', 'sys', 'uheapq', 'ustruct', 'builtins', 'uarray', 'uio', 'utime', 'cmath', 'ubinascii', 'ujson', 'utimeq', 'firmware', 'ubluetooth', 'umachine', 'uzlib', 'gc', 'ucollections', 'uos', 'hub', 'uctypes', 'urandom', 'math', 'uerrno', 'ure']
object_list_todo ... |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Summary Functions\n",
"\n",
"def get_summ_combined_county_annual(state, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) ... | {'cells': [{'cell_type': 'code', 'execution_count': null, 'metadata': {}, 'outputs': [], 'source': ['# Summary Functions\n', '\n', "def get_summ_combined_county_annual(state, county = '',verification = True, key = 'WaPo'):\n", " '''(str(two letter abbreviation), str, bool, str) -> pd.df\n", ' Returns seller d... |
# -*- coding: utf-8 -*-
def ventilation_rates(
number_of_chimneys_main_heating,
number_of_chimneys_secondary_heating,
number_of_chimneys_other,
number_of_open_flues_main_heating,
number_of_open_flues_secondary_heating,
number_of_open_flues_other,
number_of_interm... | def ventilation_rates(number_of_chimneys_main_heating, number_of_chimneys_secondary_heating, number_of_chimneys_other, number_of_open_flues_main_heating, number_of_open_flues_secondary_heating, number_of_open_flues_other, number_of_intermittant_fans_total, number_of_passive_vents_total, number_of_flueless_gas_fires_tot... |
# -*- coding: utf-8 -*-
class ProxyMiddleware(object):
def __init__(self, proxy_url):
self.proxy_url = proxy_url
def process_request(self, request, spider):
request.meta['proxy'] = self.proxy_url
@classmethod
def from_crawler(cls, crawler):
return cls(
proxy_url=c... | class Proxymiddleware(object):
def __init__(self, proxy_url):
self.proxy_url = proxy_url
def process_request(self, request, spider):
request.meta['proxy'] = self.proxy_url
@classmethod
def from_crawler(cls, crawler):
return cls(proxy_url=crawler.settings.get('PROXY_URL')) |
if 5 == 2:
print("aaaa")
print("sjjdjdd")
else :
print("else")
| if 5 == 2:
print('aaaa')
print('sjjdjdd')
else:
print('else') |
n = int(input())
print('*' * (2*n+1))
print('.' + '*' + ' ' * (2*n - 3) + '*' + '.')
for i in range(1, n-1):
print('.' + '.' * i + '*' + '@' * ((2*n-3) -2*i) + '*' + '.' * i + '.')
print('.' * n +'*' + '.' * n)
for i in range(1, n-1):
print('.' * ((n)-i) + '*' + ' ' * (i-1) + '@' + ' ' * (i-1) + '*' + '.' * ... | n = int(input())
print('*' * (2 * n + 1))
print('.' + '*' + ' ' * (2 * n - 3) + '*' + '.')
for i in range(1, n - 1):
print('.' + '.' * i + '*' + '@' * (2 * n - 3 - 2 * i) + '*' + '.' * i + '.')
print('.' * n + '*' + '.' * n)
for i in range(1, n - 1):
print('.' * (n - i) + '*' + ' ' * (i - 1) + '@' + ' ' * (i - ... |
class Enum:
def __init__(self,list):
self.list = list
def enume(self):
for index, val in enumerate(self.list,start=1):
print(index,val)
e1 = Enum([5,15,45,4,53])
e1.enume() | class Enum:
def __init__(self, list):
self.list = list
def enume(self):
for (index, val) in enumerate(self.list, start=1):
print(index, val)
e1 = enum([5, 15, 45, 4, 53])
e1.enume() |
# -*- coding: utf-8 -*-
# Copyright 2016 CloudFlare, Inc. All rights reserved.
#
# The contents of this file are 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... | """
Defines pyPluribus specific exceptions.
"""
class Timeouterror(Exception):
"""Raised in case of exceeded runtime for a command."""
pass
class Commandexecutionerror(Exception):
"""Raised in case the output cannot be retrieved."""
pass
class Connectionerror(Exception):
"""Raised when the connec... |
"""Module defining linked list."""
class LinkedList(object):
"""Classic linked list data structure."""
def __init__(self, iterable=None):
"""Initialize LinkedList instance."""
self.head = None
self._length = 0
try:
for el in iterable:
self.push(el)
... | """Module defining linked list."""
class Linkedlist(object):
"""Classic linked list data structure."""
def __init__(self, iterable=None):
"""Initialize LinkedList instance."""
self.head = None
self._length = 0
try:
for el in iterable:
self.push(el)
... |
class UserState(object):
def __init__(self, user_id):
self.user_id = user_id
self.conversation_context = {}
self.conversation_started = False
self.user = None
self.ingredient_cuisine = None
self.recipe = None
| class Userstate(object):
def __init__(self, user_id):
self.user_id = user_id
self.conversation_context = {}
self.conversation_started = False
self.user = None
self.ingredient_cuisine = None
self.recipe = None |
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
cur = 1
k -= 1
while k > 0:
step, first, last = 0, cur, cur + 1
while first <= n:
step += min(last, n + 1) - first
first *= 10
last *= 10
if ... | class Solution:
def find_kth_number(self, n: int, k: int) -> int:
cur = 1
k -= 1
while k > 0:
(step, first, last) = (0, cur, cur + 1)
while first <= n:
step += min(last, n + 1) - first
first *= 10
last *= 10
... |
mylines = []
with open('resume.txt', 'rt') as myfile:
for myline in myfile:
mylines.append(myline)
print("Name: ", end="")
for c in mylines[0]:
if c == "|":
break;
else:
print(c, end="")
| mylines = []
with open('resume.txt', 'rt') as myfile:
for myline in myfile:
mylines.append(myline)
print('Name: ', end='')
for c in mylines[0]:
if c == '|':
break
else:
print(c, end='') |
""" examples package.
Author:
- 2020-2021 Nicola Creati
- 2020-2021 Roberto Vidmar
Copyright:
2020-2021 Nicola Creati <ncreati@inogs.it>
2020-2021 Roberto Vidmar <rvidmar@inogs.it>
License:
MIT/X11 License (see
:download:`l... | """ examples package.
Author:
- 2020-2021 Nicola Creati
- 2020-2021 Roberto Vidmar
Copyright:
2020-2021 Nicola Creati <ncreati@inogs.it>
2020-2021 Roberto Vidmar <rvidmar@inogs.it>
License:
MIT/X11 License (see
:download:`l... |
class Interaction:
current_os = -1
logger = None
def __init__(self, current_os, logger):
self.current_os = current_os
self.logger = logger
def print_info(self):
self.logger.raw("This is interaction with Maya")
# framework interactions
def schema_item_double_click(self,... | class Interaction:
current_os = -1
logger = None
def __init__(self, current_os, logger):
self.current_os = current_os
self.logger = logger
def print_info(self):
self.logger.raw('This is interaction with Maya')
def schema_item_double_click(self, param):
self.logger.... |
class GameObject:
# this is a generic object: the player, a monster, an item, the stairs...
# it's always represented by a character on screen.
def __init__(self, x, y, char, color):
self.x = x
self.y = y
self.char = char
self.color = color
def move(self, dx, dy, tile_m... | class Gameobject:
def __init__(self, x, y, char, color):
self.x = x
self.y = y
self.char = char
self.color = color
def move(self, dx, dy, tile_map):
tile = tile_map[self.x + dx][self.y + dy]
if not tile.blocked:
self.x += dx
self.y += dy
... |
class Institution(object):
institution_name = None
website = None
industry = None
type = None
headquarters = None
company_size = None
founded = None
def __init__(self, name=None, website=None, industry=None, type=None, headquarters=None, company_size=None, founded=None):
self.n... | class Institution(object):
institution_name = None
website = None
industry = None
type = None
headquarters = None
company_size = None
founded = None
def __init__(self, name=None, website=None, industry=None, type=None, headquarters=None, company_size=None, founded=None):
self.na... |
class NoSuchPointError(ValueError):
pass
class Point(tuple):
"""
A point on an elliptic curve. This is a subclass of tuple (forced to a 2-tuple),
and also includes a reference to the underlying Curve.
"""
def __new__(self, x, y, curve):
return tuple.__new__(self, (x, y))
def __in... | class Nosuchpointerror(ValueError):
pass
class Point(tuple):
"""
A point on an elliptic curve. This is a subclass of tuple (forced to a 2-tuple),
and also includes a reference to the underlying Curve.
"""
def __new__(self, x, y, curve):
return tuple.__new__(self, (x, y))
def __ini... |
#!/usr/bin/env python3
def insertion_sort(lst): #times
for i in range(1,len(lst)): #n - 1
while i > 0 and lst[i-1] > lst[i]: #(n - 1)n
lst[i], lst[i-1] = lst[i-1], lst[i] #(n - 1)n/2
... | def insertion_sort(lst):
for i in range(1, len(lst)):
while i > 0 and lst[i - 1] > lst[i]:
(lst[i], lst[i - 1]) = (lst[i - 1], lst[i])
i -= 1
return lst
print(insertion_sort([6, 4, 3, 8, 5])) |
"""
sp_tool package
Sub-Packages are
* sharepoint - the core library
* tool - the frontend tool
"""
| """
sp_tool package
Sub-Packages are
* sharepoint - the core library
* tool - the frontend tool
""" |
def access_required():
pass
| def access_required():
pass |
class cacheFilesManagerInterface:
def __init__(self, cacheRootPath, resourcesRootPath):
super().__init__()
def createCacheFiles (self, fileInfo):
raise NotImplementedError()
def deleteCacheFiles (self, fileInfo):
raise NotImplementedError()
def getCacheFile (self, fileU... | class Cachefilesmanagerinterface:
def __init__(self, cacheRootPath, resourcesRootPath):
super().__init__()
def create_cache_files(self, fileInfo):
raise not_implemented_error()
def delete_cache_files(self, fileInfo):
raise not_implemented_error()
def get_cache_file(self, file... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | class Systemmanagementinterface(object):
""" Interface description for hardware management controllers
- IPMI
- IOL
"""
def __init__(self, config):
self.config = config
def get_power_status(self):
raise NotImplementedError
def is_powered(self):
""" R... |
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | monitoring_core = 'nagios'
agent_port = 6556
agent_ports = []
snmp_ports = []
tcp_connect_timeout = 5.0
use_dns_cache = True
delay_precompile = False
restart_locking = 'abort'
check_submission = 'file'
aggr_summary_hostname = '%s-s'
agent_min_version = 0
check_max_cachefile_age = 0
cluster_max_cachefile_age = 90
piggyb... |
#Command line program that performs various conversions
def errorMsg(ErrorCode):
#Assigning menu methods as values to dictionary keys
codes = {
1: MainMenu,
2: CurrencyConverter,
3: TemperatureConverter,
4: MassConverter,
5: LengthConverter
}
#Extracti... | def error_msg(ErrorCode):
codes = {1: MainMenu, 2: CurrencyConverter, 3: TemperatureConverter, 4: MassConverter, 5: LengthConverter}
func = codes.get(ErrorCode)
print('\nUnrecognized action! Try again.\n')
return func()
def exit_program():
print('\nExiting Program.')
def convert_euro_din(euros):
... |
if __name__ == "__main__":
Motifs = [
"TCGGGGGTTTTT",
"CCGGTGACTTAC",
"ACGGGGATTTTC",
"TTGGGGACTTTT",
"AAGGGGACTTCC",
"TTGGGGACTTCC",
"TCGGGGATTCAT",
"TCGGGGATTCCT",
"TAGGGGAACTAC",
"TCGGGTATAACC",
]
| if __name__ == '__main__':
motifs = ['TCGGGGGTTTTT', 'CCGGTGACTTAC', 'ACGGGGATTTTC', 'TTGGGGACTTTT', 'AAGGGGACTTCC', 'TTGGGGACTTCC', 'TCGGGGATTCAT', 'TCGGGGATTCCT', 'TAGGGGAACTAC', 'TCGGGTATAACC'] |
fibs = {0: 0, 1: 1}
def fib(n):
if n in fibs: return fibs[n]
if n % 2 == 0:
fibs[n] = ((2 * fib((n / 2) - 1)) + fib(n / 2)) * fib(n / 2)
return fibs[n]
fibs[n] = (fib((n - 1) / 2) ** 2) + (fib((n+1) / 2) ** 2)
return fibs[n]
# limit 100000
| fibs = {0: 0, 1: 1}
def fib(n):
if n in fibs:
return fibs[n]
if n % 2 == 0:
fibs[n] = (2 * fib(n / 2 - 1) + fib(n / 2)) * fib(n / 2)
return fibs[n]
fibs[n] = fib((n - 1) / 2) ** 2 + fib((n + 1) / 2) ** 2
return fibs[n] |
t = int(input())
while t:
X, Y = map(int, input().split())
while X>0 and Y>0 :
if X>Y:
if X%Y==0:
X=Y
break
X = X%Y
else:
if Y%X==0:
Y=X
break
Y = Y%X
print(X+Y)
t =... | t = int(input())
while t:
(x, y) = map(int, input().split())
while X > 0 and Y > 0:
if X > Y:
if X % Y == 0:
x = Y
break
x = X % Y
else:
if Y % X == 0:
y = X
break
y = Y % X
print(... |
a = int(input())
b = int(input())
r = 0
if a < b:
for x in range(a + 1, b):
if x % 2 != 0:
r += x
elif a >= b:
for x in range(a - 1, b, -1):
if x % 2 != 0:
r += x
print(r) | a = int(input())
b = int(input())
r = 0
if a < b:
for x in range(a + 1, b):
if x % 2 != 0:
r += x
elif a >= b:
for x in range(a - 1, b, -1):
if x % 2 != 0:
r += x
print(r) |
def regionQuery(self,P,eps):
result = []
for d in self.dataSet:
if (((d[0]-P[0])**2 + (d[1] - P[1])**2)**0.5)<=eps:
result.append(d)
return result
def expandCluster(self,point,NeighbourPoints,C,eps,MinPts):
C.addPoint(point)
for p in NeighbourPoints:
if ... | def region_query(self, P, eps):
result = []
for d in self.dataSet:
if ((d[0] - P[0]) ** 2 + (d[1] - P[1]) ** 2) ** 0.5 <= eps:
result.append(d)
return result
def expand_cluster(self, point, NeighbourPoints, C, eps, MinPts):
C.addPoint(point)
for p in NeighbourPoints:
if ... |
def main():
n = int(input())
x = sorted(map(int, input().split()))
q = int(input())
m = [int(input()) for _ in range(q)]
for coin in m:
l, r = -1, n
while l + 1 < r:
mid = (l + r) // 2
if x[mid] <= coin:
l = mid
else:
... | def main():
n = int(input())
x = sorted(map(int, input().split()))
q = int(input())
m = [int(input()) for _ in range(q)]
for coin in m:
(l, r) = (-1, n)
while l + 1 < r:
mid = (l + r) // 2
if x[mid] <= coin:
l = mid
else:
... |
"""A library for installing Python wheels.
"""
__version__ = "0.2.0.dev0"
| """A library for installing Python wheels.
"""
__version__ = '0.2.0.dev0' |
with open("opcodes.txt") as f:
code = tuple([int(x) for x in f.read().strip().split(',')])
def op1(code, a, b, c, pos):
code[c] = a + b
return pos+4
def op2(code, a, b, c, pos):
code[c] = a * b
return pos+4
def op3(code, a, pos):
global sysID
code[a] = sysID
return pos+2
def op4(code, a, pos):
glo... | with open('opcodes.txt') as f:
code = tuple([int(x) for x in f.read().strip().split(',')])
def op1(code, a, b, c, pos):
code[c] = a + b
return pos + 4
def op2(code, a, b, c, pos):
code[c] = a * b
return pos + 4
def op3(code, a, pos):
global sysID
code[a] = sysID
return pos + 2
def op... |
#
# PySNMP MIB module MSERIES-PORT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MSERIES-PORT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:15:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, constraints_union, value_size_constraint) ... |
#
# Pelican_manager
#
__title__ = 'pelican_manager'
__description__ = 'easy way to management pelican blog.'
__url__ = 'https://github.com/xiaojieluo/pelican-manager'
__version__ = '0.2.1'
__build__ = 0x021801
__author__ = 'Xiaojie Luo'
__author_email__ = 'xiaojieluoff@gmail.com'
__license__ = 'Apache 2.0'
__copyright_... | __title__ = 'pelican_manager'
__description__ = 'easy way to management pelican blog.'
__url__ = 'https://github.com/xiaojieluo/pelican-manager'
__version__ = '0.2.1'
__build__ = 137217
__author__ = 'Xiaojie Luo'
__author_email__ = 'xiaojieluoff@gmail.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2017 Xiao... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class ScheduleInfoOutput(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and t... | class Scheduleinfooutput(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.