content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Simple SQL Web Interface
"""
__version__ = "0.1.1"
| """
Simple SQL Web Interface
"""
__version__ = '0.1.1' |
input_number = input ("Give me number if even or odd")
converted_input = int (input_number)
print(converted_input)
if converted_input % 2 == 0:
print("even number")
else:
print ("odd number") | input_number = input('Give me number if even or odd')
converted_input = int(input_number)
print(converted_input)
if converted_input % 2 == 0:
print('even number')
else:
print('odd number') |
class NodeChilds(object):
def __init__(self, nodes):
self.nodes = nodes
self.isArray = type(nodes) == list
self.isObject = type(nodes) == dict
def add(self, child):
if self.isArray:
self.node.append(child)
elif self.isObject:
self.node[child.ke... | class Nodechilds(object):
def __init__(self, nodes):
self.nodes = nodes
self.isArray = type(nodes) == list
self.isObject = type(nodes) == dict
def add(self, child):
if self.isArray:
self.node.append(child)
elif self.isObject:
self.node[child.key]... |
# Circular primes
# https://projecteuler.net/problem=35
prime = [True for i in range(1000010)]
prime[0] = prime[1] = False
p = 2
while p <= 1000000:
if prime[p]:
for i in range(p * 2, 1000001, p):
prime[i] = False
p += 1
circ = []
for i in range(2, 1000000):
if prime[i]:
temp = ... | prime = [True for i in range(1000010)]
prime[0] = prime[1] = False
p = 2
while p <= 1000000:
if prime[p]:
for i in range(p * 2, 1000001, p):
prime[i] = False
p += 1
circ = []
for i in range(2, 1000000):
if prime[i]:
temp = i
digits = len(str(i))
for j in range(dig... |
# -*- coding: utf-8 -*-
# Quaternary ligand binding to aromatic residues in the active-site gorge of acetylcholinesterase.
# Harel, M., Schalk, I., Ehret-Sabatier, L., Bouet, F., Goeldner, M., Hirth, C., Axelsen,
# P.H., Silman, I., Sussman, J.L. (1993) Proc.Natl.Acad.Sci.USA 90: 9031-9035
reference_1acj = {
'pdb... | reference_1acj = {'pdb_id': '1acj', 'ligand': 999, 'rings': [(5195, 5196, 5198, 5201, 5200, 5199), (5195, 5196, 5194, 5197, 5190, 5191), (5190, 5191, 5192, 5193, 5188, 5189)], 'neighbours': [72, 80, 81, 84, 85, 117, 118, 119, 121, 122, 130, 199, 200, 201, 330, 334, 432, 436, 439, 440, 441, 442, 444], 'hydrophobic': [84... |
name='trie'
def get_line(in_f,num=1):
line = in_f.readline()
obj = line.split(' ')
if len(obj) != num and -1 != num:
print('ERROR')
for i in range(len(obj)):
obj[i] = int(obj[i])
return obj
def check_in_file(in_f):
T = int(in_f.readline())
maxn = 0
MaxQc = 0
Is = True
Maxdep = 0
for xx in range(T):
#p... | name = 'trie'
def get_line(in_f, num=1):
line = in_f.readline()
obj = line.split(' ')
if len(obj) != num and -1 != num:
print('ERROR')
for i in range(len(obj)):
obj[i] = int(obj[i])
return obj
def check_in_file(in_f):
t = int(in_f.readline())
maxn = 0
max_qc = 0
is ... |
class InputOutputLabel():
def __init__(self):
self.inputs = None
self.outputs = None
self.labels = None
def update(self, inputs, outputs, labels):
self.inputs = inputs
self.outputs = outputs
self.labels = labels | class Inputoutputlabel:
def __init__(self):
self.inputs = None
self.outputs = None
self.labels = None
def update(self, inputs, outputs, labels):
self.inputs = inputs
self.outputs = outputs
self.labels = labels |
# Runtime: 280 ms, faster than 70.79% of Python3 online submissions for Sort an Array.
# Memory Usage: 19.7 MB, less than 57.14% of Python3 online submissions for Sort an Array.
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
# merge sort: avg, worst, best time = O(nlogn), space = O(n)
... | class Solution:
def sort_array(self, nums: List[int]) -> List[int]:
def mergesort(left, right, nums):
if left < right:
mid = (left + right) // 2
mergesort(left, mid, nums)
mergesort(mid + 1, right, nums)
nums[left:right + 1] = mer... |
#// The format of this file is descriped in api_kernel32.idc
#///func=RtlGetLastWin32Error entry=bochsys._BxWin32GetLastError@0
#///func=RtlSetLastWin32Error entry=bochsys._BxWin32SetLastError@4
#///func=NtSetLdtEntries purge=24
#///func=RtlAllocateHeap entry=nt_HeapAlloc
def nt_HeapAlloc():
# Redirect HeapAlloc ->... | def nt__heap_alloc():
cpu.eax = bochs_virt_alloc(0, bochs_get_param(3), 1)
return 0
def nt__encode_pointer():
cpu.eax = bochs_get_param(1) ^ 287454020
return 0
def nt__decode_pointer():
cpu.eax = bochs_get_param(1) ^ 287454020
return 0 |
def get_keywords(tweets_features):
query = tweets_features['search_metadata']['query']
keywords = query.split(' -filter')[0].split(' OR ')
return keywords
| def get_keywords(tweets_features):
query = tweets_features['search_metadata']['query']
keywords = query.split(' -filter')[0].split(' OR ')
return keywords |
# if-else
if True:
print("True execute")
else:
print("False execute")
x = input("Please enter a number: ") # Get a number from user input
x = int(x) # convert the number to integer
if x > 200:
print("Greater than 200")
elif x > 100:
print("Greater than 100, Less than 100")
else:
print("Less than... | if True:
print('True execute')
else:
print('False execute')
x = input('Please enter a number: ')
x = int(x)
if x > 200:
print('Greater than 200')
elif x > 100:
print('Greater than 100, Less than 100')
else:
print('Less than 100')
number1 = int(input('Enter the first number: '))
number2 = int(input('... |
"""
Python mergesort algorithms
"""
def mergeSort(array):
if len(array) > 1:
# Finding the mid of the arrayay
mid = len(array) // 2
# Dividing the array elements into 2 halves
L = array[:mid]
R = array[mid:]
# Sorting the first half
mergeSort(L)
... | """
Python mergesort algorithms
"""
def merge_sort(array):
if len(array) > 1:
mid = len(array) // 2
l = array[:mid]
r = array[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
array[k]... |
# [EASY]232. Implement Queue using Stacks
# https://leetcode.com/problems/implement-queue-using-stacks/description/
# The idea is to simulate a queue using two stacks. I use python list as the underlying data structure for stack: it moves all elements of the "inStack" to the "outStack" when the "outStack" is empty. Her... | class Myqueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.StackIn = []
self.StackOut = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.StackIn.ap... |
#!/usr/bin/env python3
expsz = 4 # number of bits in the exponent
wordsz = 8 # number of bits in the word
# no config below
# how many bits in the mantissa
mansz = wordsz - 2 - expsz # please ensure mansz >= 1
# print bits allocation
print(f"{wordsz}b allocation: [1b sign] [{mansz}b mantissa] "\
f"[1b e... | expsz = 4
wordsz = 8
mansz = wordsz - 2 - expsz
print(f'{wordsz}b allocation: [1b sign] [{mansz}b mantissa] [1b exp sign] [{expsz}b exponent]\n')
maxman = (1 << mansz) - 1
manval = 1 + maxman / (1 << mansz)
print(f'max mantissa = 1.{maxman:b}b -> {manval:f}')
maxexp = (1 << expsz) - 1
expval = 2 ** maxexp
print(f'max e... |
# by Kami Bigdely
# Extract Class
class Food:
def __init__(self, name, prep_time, is_vegeterian, food_type,
cuisine_type, ingredients, recipe):
self.name = name
self.prep_time = prep_time
self.is_vegeterian = is_vegeterian
self.food_type = food_type
self.c... | class Food:
def __init__(self, name, prep_time, is_vegeterian, food_type, cuisine_type, ingredients, recipe):
self.name = name
self.prep_time = prep_time
self.is_vegeterian = is_vegeterian
self.food_type = food_type
self.cuisine_type = cuisine_type
self.ingredients =... |
def main():
message = input('Message: ')
alphabet = 'abcdefghijklkmnopqrstuvwxyz'
letters = alphabet.split(sep='')
| def main():
message = input('Message: ')
alphabet = 'abcdefghijklkmnopqrstuvwxyz'
letters = alphabet.split(sep='') |
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 2015-02-27 4174 nabowle Output full stacktrace.
# 2018-10-05 mjames@ucar Fix returned retVal encoding.
... | class Serializableexceptionwrapper(object):
def __init__(self):
self.stackTrace = None
self.message = None
self.exceptionClass = None
self.wrapper = None
def __str__(self):
return self.__repr__()
def __repr__(self):
if not self.message:
self.mes... |
#
# PySNMP MIB module VCP-PRIVATE-MIB-VER-2 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VCP-PRIVATE-MIB-VER-2
# Produced by pysmi-0.3.4 at Mon Apr 29 21:26:27 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')
(single_value_constraint, value_range_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
frase = ('O rato roeu a roupa do rei')
letra = ('r')
contador = 0
for valor in frase:
if valor == letra:
contador = contador + 1
print(f'A letra {letra} apareceu {contador} vezes na frase') | frase = 'O rato roeu a roupa do rei'
letra = 'r'
contador = 0
for valor in frase:
if valor == letra:
contador = contador + 1
print(f'A letra {letra} apareceu {contador} vezes na frase') |
#!/usr/bin/env python3
"""Frames per second.
Create a function that returns the number of frames shown in a
given number of minutes for a certain FPS.
Source:
https://edabit.com/challenge/Yj2Rew5XQYpu7Nosq
"""
def frames(minutes: int, fps: int) -> int:
"""Find the number of frames shown."""
seconds = minute... | """Frames per second.
Create a function that returns the number of frames shown in a
given number of minutes for a certain FPS.
Source:
https://edabit.com/challenge/Yj2Rew5XQYpu7Nosq
"""
def frames(minutes: int, fps: int) -> int:
"""Find the number of frames shown."""
seconds = minutes * 60
return second... |
# encoding: utf-8
__author__ = 'lianggao'
__date__ = '2019/5/29 10:44 AM'
def javpop_url(time):
yield 'http://javpop.com/' + time[:4] + '/' + time[4:6] + '/' + time[-2:] | __author__ = 'lianggao'
__date__ = '2019/5/29 10:44 AM'
def javpop_url(time):
yield ('http://javpop.com/' + time[:4] + '/' + time[4:6] + '/' + time[-2:]) |
def type_name(cls):
"""Get the name of a class."""
if not cls:
return '(none)'
return '{}.{}'.format(cls.__module__, cls.__name__)
def viewset_model(serializer):
"""Get the model of a serializer."""
if hasattr(serializer, 'serializer_class'):
return serializer.serializer_class.Meta... | def type_name(cls):
"""Get the name of a class."""
if not cls:
return '(none)'
return '{}.{}'.format(cls.__module__, cls.__name__)
def viewset_model(serializer):
"""Get the model of a serializer."""
if hasattr(serializer, 'serializer_class'):
return serializer.serializer_class.Meta.... |
async def send_to_client(packet_type, packet_data):
"""Implementation of this function not shown."""
raise RuntimeError('Nope')
async def trigger_event(event_name, event_data):
"""Implementation of this function not shown."""
raise RuntimeError('Nope')
async def receive(packet_type, packet_data):
... | async def send_to_client(packet_type, packet_data):
"""Implementation of this function not shown."""
raise runtime_error('Nope')
async def trigger_event(event_name, event_data):
"""Implementation of this function not shown."""
raise runtime_error('Nope')
async def receive(packet_type, packet_data):
... |
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... | print('Step 1')
print('Step 2')
print('Step 3')
True
37
3.14159265359
27 + 3
'Ice cream'
'More ice cream'
'A really long string\nwith multiple lines'
'I love' + 'to eat' + 'ice cream'
type(True)
type(False)
type(132)
type(34.62)
type('A single quote string')
type('A double quote string')
type('A tripple quote string')
... |
# this file was automatically generated
major = 1
minor = 4
release = '20130410193624'
version = '%d.%d-%s' % (major, minor, release)
| major = 1
minor = 4
release = '20130410193624'
version = '%d.%d-%s' % (major, minor, release) |
"""
entradas
valor-->int-->va
"""
cd = int(input("Ingrese cantidad de dinero $"))
bcien = (cd-cd % 100000)/100000
cd=cd % 100000
bcincuen = (cd-cd % 50000)/50000
cd=cd % 50000
bvein = (cd-cd % 20000)/20000
cd=cd % 20000
bdiez = (cd-cd % 10000)/10000
cd=cd % 10000
bcinco = (cd-cd % 5000)/5000
cd=cd % 5000
bd = (cd-cd % ... | """
entradas
valor-->int-->va
"""
cd = int(input('Ingrese cantidad de dinero $'))
bcien = (cd - cd % 100000) / 100000
cd = cd % 100000
bcincuen = (cd - cd % 50000) / 50000
cd = cd % 50000
bvein = (cd - cd % 20000) / 20000
cd = cd % 20000
bdiez = (cd - cd % 10000) / 10000
cd = cd % 10000
bcinco = (cd - cd % 5000) / 5000... |
a = input ('Put the number a: \n')
b= input ('Put the number b: \n')
a,b=b,a
print(f'Resalt a: {a}')
print(f'Resalt b: {b}')
| a = input('Put the number a: \n')
b = input('Put the number b: \n')
(a, b) = (b, a)
print(f'Resalt a: {a}')
print(f'Resalt b: {b}') |
class Player:
def __init__(self, id, x, y, z, health):
self.id = id
self.x = x
self.y = y
self.z = z
self.health = health
| class Player:
def __init__(self, id, x, y, z, health):
self.id = id
self.x = x
self.y = y
self.z = z
self.health = health |
"""
Given the array nums, for each nums[i] find out how many numbers in the
array are smaller than it. That is, for each nums[i] you have to count the
number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example:
Input: nums = [8,1,2,2,3]
Output: ... | """
Given the array nums, for each nums[i] find out how many numbers in the
array are smaller than it. That is, for each nums[i] you have to count the
number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example:
Input: nums = [8,1,2,2,3]
Output: ... |
"""
package used to easy creation of new device interfaces.
"""
| """
package used to easy creation of new device interfaces.
""" |
"""Build rules for utilizing glslang."""
def _glslang(name, mode = None, target = None, **kwargs):
MODES = {
"glsl": "",
"hlsl": "-D",
}
if mode not in MODES:
fail("Illegal mode {}".format(mode), "mode")
TARGETS = {
"opengl": "-G",
"vulkan": "-V",
}
if t... | """Build rules for utilizing glslang."""
def _glslang(name, mode=None, target=None, **kwargs):
modes = {'glsl': '', 'hlsl': '-D'}
if mode not in MODES:
fail('Illegal mode {}'.format(mode), 'mode')
targets = {'opengl': '-G', 'vulkan': '-V'}
if target not in TARGETS:
fail('Illegal target ... |
# General
DEBUG_MODE = True
# FolderWatcher
FOLDER_PATH = 'images/'
FRAMERATE = 1
SCALE_TO_SIZE = (640, 480)
# Server
ROUTE = '/folder_feed' | debug_mode = True
folder_path = 'images/'
framerate = 1
scale_to_size = (640, 480)
route = '/folder_feed' |
with open(r"C:\Users\joash\Desktop\CS\haskell\AOC19\aoc\day2.txt", "r") as f:
program = [ int(i) for i in f.read().split(",") ]
pos = 0
while program[pos] != 99:
print("currently on pos:", pos, "opcode is: ", program[pos])
if program[pos] == 1:
program[program[pos+3]] = program[program[pos+1]] + program[pr... | with open('C:\\Users\\joash\\Desktop\\CS\\haskell\\AOC19\\aoc\\day2.txt', 'r') as f:
program = [int(i) for i in f.read().split(',')]
pos = 0
while program[pos] != 99:
print('currently on pos:', pos, 'opcode is: ', program[pos])
if program[pos] == 1:
program[program[pos + 3]] = program[program[pos + ... |
class dotReferenceModel_t(object):
# no doc
aActiveFilePath = None
aBasePointGuid = None
aFilename = None
ModelObject = None
Position = None
Rotation = None
Scale = None
Visibility = None
| class Dotreferencemodel_T(object):
a_active_file_path = None
a_base_point_guid = None
a_filename = None
model_object = None
position = None
rotation = None
scale = None
visibility = None |
class FARule(object):
def __init__(self, state, char, next):
super(FARule, self).__init__()
self.state = state
self.char = char
self.next = next
def is_applied(self, state, char):
return self.state == state and self.char == char
def follow(self, config):
ret... | class Farule(object):
def __init__(self, state, char, next):
super(FARule, self).__init__()
self.state = state
self.char = char
self.next = next
def is_applied(self, state, char):
return self.state == state and self.char == char
def follow(self, config):
re... |
def purge(pTable):
"""
if a CEA candidate has been selected, purge all cell pairs that do not belong to this candiate
"""
# inventorize cells with selected candidates
selected = {}
for cell in pTable.getCells():
if ('sel_cand' in cell) and cell['sel_cand']:
key = (cell['row_... | def purge(pTable):
"""
if a CEA candidate has been selected, purge all cell pairs that do not belong to this candiate
"""
selected = {}
for cell in pTable.getCells():
if 'sel_cand' in cell and cell['sel_cand']:
key = (cell['row_id'], cell['col_id'])
selected[key] = ce... |
"""
A sequential search is O(n) for ordered and unordered lists.
A binary search of an ordered list is O(logn) in the worst case.
Hash tables can provide constant time searching.
A bubble sort, a selection sort, and an insertion sort are O(n^2) algorithms.
A shell sort improves on the insertion sort by sorting increme... | """
A sequential search is O(n) for ordered and unordered lists.
A binary search of an ordered list is O(logn) in the worst case.
Hash tables can provide constant time searching.
A bubble sort, a selection sort, and an insertion sort are O(n^2) algorithms.
A shell sort improves on the insertion sort by sorting increme... |
#_ -*- coding: utf-8 -*-
# Copyright (c) 2021 OceanBase
# OceanBase CE is licensed under Mulan PubL v2.
# You can use this software according to the terms and conditions of the Mulan PubL v2.
# You may obtain a copy of Mulan PubL v2 at:
# http://license.coscl.org.cn/MulanPubL-2.0
# THIS SOFTWARE IS PROVIDED O... | global fields
fields = ['tenant_id', 'tablegroup_id', 'database_id', 'table_id', 'rowkey_split_pos', 'is_use_bloomfilter', 'progressive_merge_num', 'rowkey_column_num', 'load_type', 'table_type', 'index_type', 'def_type', 'table_name', 'compress_func_name', 'part_level', 'charset_type', 'collation_type', 'create_mem_ve... |
class Hoge:
def hoge(self) -> None:
pass
@classmethod
def fuga(cls) -> None:
pass
| class Hoge:
def hoge(self) -> None:
pass
@classmethod
def fuga(cls) -> None:
pass |
adict = {
"BLACKBOARD_LEARN_INSTANCE" : "",
"APPLICATION_KEY" : "",
"APPLICATION_SECRET" : "",
"django_secret_key" : '',
"disable_collectstatic" : "1",
"django_allowed_hosts" : "127.0.0.1 localhost .ngrok.io .herokuapp.com [::1]",
"django_debug" : "False",
} | adict = {'BLACKBOARD_LEARN_INSTANCE': '', 'APPLICATION_KEY': '', 'APPLICATION_SECRET': '', 'django_secret_key': '', 'disable_collectstatic': '1', 'django_allowed_hosts': '127.0.0.1 localhost .ngrok.io .herokuapp.com [::1]', 'django_debug': 'False'} |
# Find the Duplicate Number
# Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
# find the duplicate one.
# There is only one duplicate number, but it can be repeated multiple times.
# Note: You cannot modify the array, no extra space is allowed.
class SolutionV1(object):
... | class Solutionv1(object):
def find_duplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
(lo, hi) = (1, len(nums) - 1)
while lo < hi:
mid = lo + (hi - lo) / 2
count = 0
for num in nums:
if num <= mid:
... |
class MessageStorage:
messageList = []
@staticmethod
def addMessage(m):
MessageStorage.messageList.append(m)
@staticmethod
def countMessages():
return len(MessageStorage.messageList)
@staticmethod
def getMessageList():
return MessageStorage.messageList
@stati... | class Messagestorage:
message_list = []
@staticmethod
def add_message(m):
MessageStorage.messageList.append(m)
@staticmethod
def count_messages():
return len(MessageStorage.messageList)
@staticmethod
def get_message_list():
return MessageStorage.messageList
@s... |
class SingleServerConfig():
def __init__(self):
self.redis_config = None
def set_config(self, **kwargs):
"""
kwargs:
:host:
Can be used to point to a startup node
:port:
Can be used to point to a startup node
... | class Singleserverconfig:
def __init__(self):
self.redis_config = None
def set_config(self, **kwargs):
"""
kwargs:
:host:
Can be used to point to a startup node
:port:
Can be used to point to a startup node
... |
class Solution:
def removeDuplicateLetters(self, s):
for c in sorted(set(s)):
chop = s[s.index(c):]
# print(c, set(chop), set(s), chop, c, s)
if set(chop) == set(s):
return c + self.removeDuplicateLetters(chop.replace(c, ""))
return ""
a = Solution... | class Solution:
def remove_duplicate_letters(self, s):
for c in sorted(set(s)):
chop = s[s.index(c):]
if set(chop) == set(s):
return c + self.removeDuplicateLetters(chop.replace(c, ''))
return ''
a = solution()
b = 'cbabc'
print(a.removeDuplicateLetters(b)) |
print("Look at the assinment statements")
#1. Set a variable called playerlives equal to 3
playerlives = 3
#Write assignment statements for 2 to 6 below
#2. set a variable called chocolate equal to 2
#3. set a variable called scorevalue equal to 4
#4. set a variable called totalscore equal to scorevalue * 3
#5. set... | print('Look at the assinment statements')
playerlives = 3 |
palavra = input('Informe uma palavra: ')
print('palavra invertida: ', palavra[::-1])
for letra in palavra:
print(letra) | palavra = input('Informe uma palavra: ')
print('palavra invertida: ', palavra[::-1])
for letra in palavra:
print(letra) |
"""Non-public internal utilities used across the library.
The classes and functions under this module are not meant to be touched by users.
"""
__all__ = ()
| """Non-public internal utilities used across the library.
The classes and functions under this module are not meant to be touched by users.
"""
__all__ = () |
dy_import_module_symbols("testchunk_helper")
SERVER_IP = getmyip()
SERVER_PORT = 60606
DATA_RECV = 1024
CHUNK_SIZE_SEND = 2**9 # 512KB chunk size
CHUNK_SIZE_RECV = 2**9
DATA_TO_SEND = "Hello" # 5Bytes of data
launch_test()
| dy_import_module_symbols('testchunk_helper')
server_ip = getmyip()
server_port = 60606
data_recv = 1024
chunk_size_send = 2 ** 9
chunk_size_recv = 2 ** 9
data_to_send = 'Hello'
launch_test() |
'''
pretrained model for StarGAN
details adding soon !
'''
| """
pretrained model for StarGAN
details adding soon !
""" |
#
# Copyright 2021 Abir Haque
# Subject to MIT License in LICENSE file
#
#
#
# Perfect Square Roots:
#
# Find the square root of any given perfect square without multiplication or division.
#
# This is possible as all perfect squares are the sum of odd integers [1].
# This arithmetic sequence can be seen below:
#
# ... | def sqrt(n):
(i, j, k) = (0, -1, 0)
while k < n:
j += 2
k += j
i += 1
if k == n:
return i
return 'not possible'
n = int(input('Please enter a number: '))
print('Square root of ' + str(n) + ' is ' + str(sqrt(n)) + '.') |
"""
A module that displays a poor-man's bar chart.
"""
def render_chart(word_list):
"""
Renders a bar chart to the console. Each row of the chart contains the frequency
of each letter in the word list.
Returns:
A dictionary whose keys are the letters and values are the fre... | """
A module that displays a poor-man's bar chart.
"""
def render_chart(word_list):
"""
Renders a bar chart to the console. Each row of the chart contains the frequency
of each letter in the word list.
Returns:
A dictionary whose keys are the letters and values are the freq... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""unshurl
- Author: Daniel J. Umpierrez
- Created: 26-05-2019
- License: UNLICENSE
- Github: https://github.com/havocesp/unshurl
"""
__version__ = '0.1.0'
__site__ = 'https://github.com/havocesp/unshurl'
__license__ = 'UNLICENSE'
__author__ = 'Daniel... | """unshurl
- Author: Daniel J. Umpierrez
- Created: 26-05-2019
- License: UNLICENSE
- Github: https://github.com/havocesp/unshurl
"""
__version__ = '0.1.0'
__site__ = 'https://github.com/havocesp/unshurl'
__license__ = 'UNLICENSE'
__author__ = 'Daniel J. Umpierrez'
__email__ = 'umpierrez@pm.me'
_... |
# For Keystone Engine. AUTO-GENERATED FILE, DO NOT EDIT [keystone_const.py]
KS_API_MAJOR = 0
KS_API_MINOR = 9
KS_VERSION_MAJOR = 0
KS_VERSION_MINOR = 9
KS_VERSION_EXTRA = 1
KS_ARCH_ARM = 1
KS_ARCH_ARM64 = 2
KS_ARCH_MIPS = 3
KS_ARCH_X86 = 4
KS_ARCH_PPC = 5
KS_ARCH_SPARC = 6
KS_ARCH_SYSTEMZ = 7
KS_ARCH_HEXAGON = 8
KS_ARC... | ks_api_major = 0
ks_api_minor = 9
ks_version_major = 0
ks_version_minor = 9
ks_version_extra = 1
ks_arch_arm = 1
ks_arch_arm64 = 2
ks_arch_mips = 3
ks_arch_x86 = 4
ks_arch_ppc = 5
ks_arch_sparc = 6
ks_arch_systemz = 7
ks_arch_hexagon = 8
ks_arch_evm = 9
ks_arch_max = 10
ks_mode_little_endian = 0
ks_mode_big_endian = 10... |
class TestDataError(Exception):
pass
class MissingElementAmountValue(TestDataError):
pass
class FactoryStartedAlready(TestDataError):
pass
class NoSuchDatatype(TestDataError):
pass
class InvalidFieldType(TestDataError):
pass
class MissingRequiredFields(TestDataError):
pass
class UnmetDependentFi... | class Testdataerror(Exception):
pass
class Missingelementamountvalue(TestDataError):
pass
class Factorystartedalready(TestDataError):
pass
class Nosuchdatatype(TestDataError):
pass
class Invalidfieldtype(TestDataError):
pass
class Missingrequiredfields(TestDataError):
pass
class Unmetdepen... |
# -*- coding: utf-8 -*-
def test_help_message(testdir):
result = testdir.runpytest(
'--help',
)
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'helm:',
'*--helm-path=HELM_PATH*',
])
def test_helm_path_ini_setting(testdir):
testdir.makeini("... | def test_help_message(testdir):
result = testdir.runpytest('--help')
result.stdout.fnmatch_lines(['helm:', '*--helm-path=HELM_PATH*'])
def test_helm_path_ini_setting(testdir):
testdir.makeini('\n [pytest]\n HELM_PATH=/path/to/helm\n ')
testdir.makepyfile("\n import pytest\n\n ... |
# ******Numbers with The Highest Amount of Divisors******
# codewars
# An array of different positive integers is given. We should create a code that gives us the number (or the numbers) that has (or have) the highest number of divisors among other data.
# The function proc_arrInt(), (Javascript: procArrInt()) will ... | def proc_arr_int(listNum):
primes = []
output = [0, [0]]
maxi = 0
for i in listNum:
count = 1
for j in range(1, i // 2 + 1):
if i % j == 0:
count += 1
if count == 2:
primes.append(i)
if count > maxi:
output[0] = count
... |
#
# PySNMP MIB module EDB-snmp (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EDB-snmp
# Produced by pysmi-0.3.4 at Wed May 1 12:59:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) ... |
n1 = float(input())
n2 = float(input())
meida = ((n1*3.5)+(n2*7.5))/(3.5+7.5)
print(f"MEDIA = {meida:.5f}") | n1 = float(input())
n2 = float(input())
meida = (n1 * 3.5 + n2 * 7.5) / (3.5 + 7.5)
print(f'MEDIA = {meida:.5f}') |
# Rotate Image
'''
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[... | """
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0:
return 0
current_length = 0
max_length = 0
idx = 0
last_dup_index = -1
count = {}
while idx < len(s):
if s[idx] not in count or count[s[idx]] < last_dup... | class Solution:
def length_of_longest_substring(self, s: str) -> int:
if len(s) == 0:
return 0
current_length = 0
max_length = 0
idx = 0
last_dup_index = -1
count = {}
while idx < len(s):
if s[idx] not in count or count[s[idx]] < last_... |
class move_avg:
def __init__(self, bufmax):
self.buf = []
self.bufmax = bufmax
def add(self, val):
self.buf.append(val)
if len(self.buf) > self.bufmax:
del self.buf[0]
def get(self):
if len(self.buf) > 0:
avg = sum(self.buf)/len(self.buf)
else:
avg = 0
return avg
| class Move_Avg:
def __init__(self, bufmax):
self.buf = []
self.bufmax = bufmax
def add(self, val):
self.buf.append(val)
if len(self.buf) > self.bufmax:
del self.buf[0]
def get(self):
if len(self.buf) > 0:
avg = sum(self.buf) / len(self.buf)
... |
# -*- coding: utf-8 -*-
"""
Standard values for CoastalVarExtractor.
They should not need to be changed except to include more site value mappings.
They do not require any input values.
"""
sitemap = {
'Assawoman':{'region': 'Delmarva', 'site': 'Assawoman',
'code': 'assa',
'M... | """
Standard values for CoastalVarExtractor.
They should not need to be changed except to include more site value mappings.
They do not require any input values.
"""
sitemap = {'Assawoman': {'region': 'Delmarva', 'site': 'Assawoman', 'code': 'assa', 'MHW': 0.34, 'MLW': -0.55, 'id_init_val': 200000, 'morph_state': 12}, ... |
# -*- coding: utf-8; -*-
class ConsulSSLError(Exception):
"""
Error raised when https is defined in --host argument or
environmental variable and ssl certificates are not configured
or defined
"""
def __init__(self, msg):
self.msg = "https scheme defined without any ssl certificates pr... | class Consulsslerror(Exception):
"""
Error raised when https is defined in --host argument or
environmental variable and ssl certificates are not configured
or defined
"""
def __init__(self, msg):
self.msg = 'https scheme defined without any ssl certificates provided'
def __str__(s... |
TEMPLATES = {
"multilingual-record-dumper": "templates/invenio_record_dumper_multilingual.py.jinja2",
"record-multilingual": "templates/invenio_record_multilingual.py.jinja2",
"subschema-multilingual": "templates/invenio_schema_multilingual.py.jinja2",
"multi-search": "templates/invenio_record_search_mu... | templates = {'multilingual-record-dumper': 'templates/invenio_record_dumper_multilingual.py.jinja2', 'record-multilingual': 'templates/invenio_record_multilingual.py.jinja2', 'subschema-multilingual': 'templates/invenio_schema_multilingual.py.jinja2', 'multi-search': 'templates/invenio_record_search_multilingual.py.jin... |
# Getting input and converting to int
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# Varibales to store sum and total and count
sum_of_heights = 0
total_height = 0
count_of_students = 0 # This is to f... | student_heights = input('Input a list of student heights ').split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
sum_of_heights = 0
total_height = 0
count_of_students = 0
for student in student_heights:
sum_of_heights += student
count_of_students += 1
total_heigh... |
N, X = input().split()
A = list(map(int, input().split()))
B = []
for i in range(0, int(N)) :
if(A[i] < int(X)) :
print(A[i], end=" ") | (n, x) = input().split()
a = list(map(int, input().split()))
b = []
for i in range(0, int(N)):
if A[i] < int(X):
print(A[i], end=' ') |
'''
A string S of lowercase letters is given. We want to partition this string into as many parts as possible
so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
'''
class Solution:
def partitionLabels(self, S):
"""
:type S: str
... | """
A string S of lowercase letters is given. We want to partition this string into as many parts as possible
so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
"""
class Solution:
def partition_labels(self, S):
"""
:type S: str... |
def main():
print("Welcome to the casino!")
print("Rules are simple, guess a number, if you get it right you win 100000 dollars~")
print("Else you loose 5 dollars")
while True:
try:
number = int(input("Choose a number: "))
except ValueError:
print("INVALID NU... | def main():
print('Welcome to the casino!')
print('Rules are simple, guess a number, if you get it right you win 100000 dollars~')
print('Else you loose 5 dollars')
while True:
try:
number = int(input('Choose a number: '))
except ValueError:
print('INVALID NUMBER!... |
# -*- coding: utf-8 -*-
class Config(object):
"""Configure me so examples work
Use me like this:
mysql.connector.Connect(**Config.dbinfo())
"""
HOST = 'localhost'
DATABASE = 'test'
USER = ''
PASSWORD = ''
PORT = 3306
CHARSET = 'utf8'
UNICODE = True
... | class Config(object):
"""Configure me so examples work
Use me like this:
mysql.connector.Connect(**Config.dbinfo())
"""
host = 'localhost'
database = 'test'
user = ''
password = ''
port = 3306
charset = 'utf8'
unicode = True
warnings = True
@classmethod... |
class VectorIndex:
@property
def files(self):
return []
def save(self):
pass
def load(self):
pass
def build(self):
pass
def search(self):
pass
def search_index(self):
pass
def add(self, vector):
pass
def add_bulk(self, vectors):
pass
def set_bulk(self, indices... | class Vectorindex:
@property
def files(self):
return []
def save(self):
pass
def load(self):
pass
def build(self):
pass
def search(self):
pass
def search_index(self):
pass
def add(self, vector):
pass
def add_bulk(self, v... |
class CallbackSettings(object):
@property
def JAVASCRIPT(self):
return super().JAVASCRIPT + (
'callback/modal.js',
)
@property
def INSTALLED_APPS(self):
apps = super().INSTALLED_APPS + [
'callback'
]
if not 'captcha' in apps:
... | class Callbacksettings(object):
@property
def javascript(self):
return super().JAVASCRIPT + ('callback/modal.js',)
@property
def installed_apps(self):
apps = super().INSTALLED_APPS + ['callback']
if not 'captcha' in apps:
apps += ['captcha']
return apps
defa... |
#Duplicates of ReadyResult constants - keeps this class clean of imported modules leaking into the sandbox
NOT_READY = 'NotReady'
READY = 'Ready'
FAILED = 'Failed'
class ReadyResultHolder:
def __init__(self):
self.__readiness = READY
self.__reason = None
def ready(self):
self.__readi... | not_ready = 'NotReady'
ready = 'Ready'
failed = 'Failed'
class Readyresultholder:
def __init__(self):
self.__readiness = READY
self.__reason = None
def ready(self):
self.__readiness = READY
return self
def not_ready(self):
self.__readiness = NOT_READY
retu... |
##############################################################################
# Copyright (c) 2017 ZTE Corp
# feng.xiaowei@zte.com.cn
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is ... | not_found_base = 'Could Not Found'
exist_base = 'Already Exists'
def key_error(key):
return "KeyError: '{}'".format(key)
def no_file_uploaded():
return 'Please upload a file.'
def no_body():
return 'No Body'
def not_found(key, value):
return '{} {} [{}]'.format(not_found_base, key, value)
def missi... |
n = int(input())
pieces = {}
for _ in range(n):
piece, composer, key = input().split('|')
pieces[piece] = [composer, key]
while True:
line = input()
if line == 'Stop':
break
args = line.split('|')
command = args[0]
piece = args[1]
if command == 'Add':
... | n = int(input())
pieces = {}
for _ in range(n):
(piece, composer, key) = input().split('|')
pieces[piece] = [composer, key]
while True:
line = input()
if line == 'Stop':
break
args = line.split('|')
command = args[0]
piece = args[1]
if command == 'Add':
composer = args[2]... |
def map_llc_result_to_dictionary_list(land_charge_result):
"""Produce a list of jsonable dictionaries of an alchemy result set
"""
if not isinstance(land_charge_result, list):
return list(map(lambda land_charge: land_charge.to_dict(),
[land_charge_result]))
else:
... | def map_llc_result_to_dictionary_list(land_charge_result):
"""Produce a list of jsonable dictionaries of an alchemy result set
"""
if not isinstance(land_charge_result, list):
return list(map(lambda land_charge: land_charge.to_dict(), [land_charge_result]))
else:
return list(map(lambda ... |
DEBUG = True
PLUGINS = ["fastack_sqlmodel", "fastack_migrate"]
COMMANDS = []
DB_USER = "fastack_user"
DB_PASSWORD = "fastack_pass"
DB_HOST = "db"
DB_PORT = 5432
DB_NAME = "fastack_db"
SQLALCHEMY_DATABASE_URI = (
f"postgresql+psycopg2://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
)
SQLALCHEMY_OPTIONS = {}... | debug = True
plugins = ['fastack_sqlmodel', 'fastack_migrate']
commands = []
db_user = 'fastack_user'
db_password = 'fastack_pass'
db_host = 'db'
db_port = 5432
db_name = 'fastack_db'
sqlalchemy_database_uri = f'postgresql+psycopg2://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}'
sqlalchemy_options = {} |
"""
1. Clarification
2. Possible solutions
- Binary search I
- Binary search II
- Binary search III
3. Coding
4. Tests
"""
# T=O(lgn), S=O(1)
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: return -1
left, right = 0, len(nums) - 1
while left ... | """
1. Clarification
2. Possible solutions
- Binary search I
- Binary search II
- Binary search III
3. Coding
4. Tests
"""
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums:
return -1
(left, right) = (0, len(nums) - 1)
while left <= ... |
a = input()
p = input()
if p in a + '*':
print("S")
else:
print("N")
| a = input()
p = input()
if p in a + '*':
print('S')
else:
print('N') |
'''
All python scripts are modules and collection modules are package
pip is used to install packages
'''
def Demo():
a = int(input('Enter a 1st number'))
b = int(input('Enter 2nd number'))
s = 0
s = a + b
return s
print(Demo())
print("I will run")
print(f'{__name__}')
def Solve... | """
All python scripts are modules and collection modules are package
pip is used to install packages
"""
def demo():
a = int(input('Enter a 1st number'))
b = int(input('Enter 2nd number'))
s = 0
s = a + b
return s
print(demo())
print('I will run')
print(f'{__name__}')
def solve():
print('Pyth... |
# https://www.python-course.eu/graphs_python.php
class Graph(object):
def __init__(self, vertices):
""" initializes a complete graph object """
graph_dict = {}
for node in vertices:
graph_dict[node] = []
for vertex in vertices:
if node != vertex:
... | class Graph(object):
def __init__(self, vertices):
""" initializes a complete graph object """
graph_dict = {}
for node in vertices:
graph_dict[node] = []
for vertex in vertices:
if node != vertex:
graph_dict[node].append(vertex)
... |
WALL = '#'
PASSABLE = '.'
class SquareGrid:
def __init__(self, width, height):
self.width = width
self.height = height
self.walls = set()
def in_bounds(self, id):
(x, y) = id
return 0 <= x < self.width and 0 <= y < self.height
def cost(self, from_node, to_node):
... | wall = '#'
passable = '.'
class Squaregrid:
def __init__(self, width, height):
self.width = width
self.height = height
self.walls = set()
def in_bounds(self, id):
(x, y) = id
return 0 <= x < self.width and 0 <= y < self.height
def cost(self, from_node, to_node):
... |
s = ""
for x in range(33,127): # <33; 126>
s += chr(x)
print(s)
| s = ''
for x in range(33, 127):
s += chr(x)
print(s) |
class RadioButtonFsm:
def __init__(self, title, position, command=None):
self.title = title
self.command = command
self.position = position
| class Radiobuttonfsm:
def __init__(self, title, position, command=None):
self.title = title
self.command = command
self.position = position |
# Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
#
# An input string is valid if:
#
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
# Note that an empty string is also considered val... | def is_valid(s):
stack = []
for c in s:
if c == '(':
stack.append('(')
if c == ')':
if len(stack) == 0:
return False
if stack[-1] != '(':
return False
else:
stack.pop()
if c == '[':
... |
price = 24
item = 'banana'
print('The %s costs %d cents.' % (item, price))
print('The %+10s costs %5.2f cents.' % (item, price))
print('The %+10s costs %10.2f cents.' % (item, price))
itemdict = {'item': 'banana', 'cost': 24}
print('The %(item)s costs %(cost)7.1f cents.' % itemdict)
"""
The banana costs 24 cents.
Th... | price = 24
item = 'banana'
print('The %s costs %d cents.' % (item, price))
print('The %+10s costs %5.2f cents.' % (item, price))
print('The %+10s costs %10.2f cents.' % (item, price))
itemdict = {'item': 'banana', 'cost': 24}
print('The %(item)s costs %(cost)7.1f cents.' % itemdict)
'\nThe banana costs 24 cents.\nThe ... |
# Scrapy settings for tutorial project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'tutorial'
SPIDER_MODULES = ['tutorial.spiders']
NEWSPIDER_MODULE = 'tutorial.spiders... | bot_name = 'tutorial'
spider_modules = ['tutorial.spiders']
newspider_module = 'tutorial.spiders'
download_delay = 2
cookies_enabled = False
retry_enabled = False
download_timeout = 10
item_pipelines = ['tutorial.pipelines.SqlitePipeline']
dupefilter_class = 'tutorial.dupefilter.SqliteDupeFilter' |
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if (root is None):
return 0
if (root.left is None and root.right is None):
return 1
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right) + 1 | class Solution:
def max_depth(self, root: TreeNode) -> int:
if root is None:
return 0
if root.left is None and root.right is None:
return 1
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right) + 1 |
red_flags = []
class RedFlagsModel():
def __init__(self):
self.db = red_flags
def save(self, data):
id = len(red_flags) + 1
payload = {
"id": id,
"title": data['title'],
"description": data['description'],
"location": data['location'],... | red_flags = []
class Redflagsmodel:
def __init__(self):
self.db = red_flags
def save(self, data):
id = len(red_flags) + 1
payload = {'id': id, 'title': data['title'], 'description': data['description'], 'location': data['location'], 'type': data['type']}
self.db.append(payload... |
#------------------------------------------------------------------------------#
# Copyright 2018 Gabriele Valentini. All rights reserved. Use of this source #
# code is governed by a MIT license that can be found in the LICENSE file. #
#----------------------------------------------------------------------------... | __cli__ = 'betrack'
__version__ = '0.1.1' |
r"""
Git errors
This module provides subclasses of ``RuntimeError`` to indicate error
conditions when calling git.
AUTHORS:
- Julian Rueth: initial version
"""
#*****************************************************************************
# Copyright (C) 2013 Julian Rueth <julian.rueth@fsfe.org>
#
# Distribu... | """
Git errors
This module provides subclasses of ``RuntimeError`` to indicate error
conditions when calling git.
AUTHORS:
- Julian Rueth: initial version
"""
class Giterror(RuntimeError):
"""
Error raised when git exits with a non-zero exit code.
EXAMPLES::
sage: from sage.dev.git_error impo... |
class Solution(object):
memo = {0: [], 1: [TreeNode(0)]}
def allPossibleFBT(self, N):
if N not in Solution.memo:
ans = []
for x in xrange(N):
y = N - 1 - x
for left in self.allPossibleFBT(x):
for right in self.allPossibleFBT(y)... | class Solution(object):
memo = {0: [], 1: [tree_node(0)]}
def all_possible_fbt(self, N):
if N not in Solution.memo:
ans = []
for x in xrange(N):
y = N - 1 - x
for left in self.allPossibleFBT(x):
for right in self.allPossibleFBT... |
__all__ = ['cohort',
'daterange',
'dimension',
'metric',
'order',
'pivot',
'report_request',
'segment']
| __all__ = ['cohort', 'daterange', 'dimension', 'metric', 'order', 'pivot', 'report_request', 'segment'] |
""" elstruct.writer._qchem5 parameters
"""
OPTION_EVAL_DCT = {
}
| """ elstruct.writer._qchem5 parameters
"""
option_eval_dct = {} |
word = input("Give me a word: ")
wrong = True
while wrong:
if word == "banana":
wrong = False
print("END GAME")
else:
print("WRONG")
word = input("Give me a word: ") | word = input('Give me a word: ')
wrong = True
while wrong:
if word == 'banana':
wrong = False
print('END GAME')
else:
print('WRONG')
word = input('Give me a word: ') |
while True:
try:
line = input().strip().split(' ')
except EOFError:
break
winner = 3
for i in range(3):
if line[i] == 'pedra' and line[(i +1) % 3] == 'tesoura' and line[(i +1) % 3] == line[(i + 2) % 3]:
winner = i
break
elif line[i] == 'papel' an... | while True:
try:
line = input().strip().split(' ')
except EOFError:
break
winner = 3
for i in range(3):
if line[i] == 'pedra' and line[(i + 1) % 3] == 'tesoura' and (line[(i + 1) % 3] == line[(i + 2) % 3]):
winner = i
break
elif line[i] == 'papel' ... |
# Solution A:
class Solution:
def reverse(self, x):
if -10 < x < 10:
return x
str_ = str(x)
if str_[0] != '-':
str_ = str_[::-1]
res = int(str_)
else:
str_ = str_[:0:-1]
res = int(str_)
res = -res
return ... | class Solution:
def reverse(self, x):
if -10 < x < 10:
return x
str_ = str(x)
if str_[0] != '-':
str_ = str_[::-1]
res = int(str_)
else:
str_ = str_[:0:-1]
res = int(str_)
res = -res
return res if -2 ** ... |
nodes = {}
node_stats = {}
buckets_summary = {}
stats_summary = {}
bucket_info = {}
buckets = {}
stats = {
"minute" : {
'disk_write_queue' : {},
'cmd_get' : {},
'cmd_set' : {},
'delete_hits' : {},
'curr_items' : {},
'vb_replica_curr_items' : {},
'curr_connec... | nodes = {}
node_stats = {}
buckets_summary = {}
stats_summary = {}
bucket_info = {}
buckets = {}
stats = {'minute': {'disk_write_queue': {}, 'cmd_get': {}, 'cmd_set': {}, 'delete_hits': {}, 'curr_items': {}, 'vb_replica_curr_items': {}, 'curr_connections': {}, 'vb_active_queue_drain': {}, 'vb_replica_queue_drain': {}, ... |
n = int(input())
a = list(map(int,input().split()))
i = 0
money=0
while i<n-1:
while i<n-1 and a[i]>=a[i+1]:
i+=1
if i==n-1:
break
buy_at=i
i+=1
while i<n and a[i]>=a[i-1]:
i+=1
sell_at=i-1
money+=a[sell_at]-a[buy_at]
print(money) | n = int(input())
a = list(map(int, input().split()))
i = 0
money = 0
while i < n - 1:
while i < n - 1 and a[i] >= a[i + 1]:
i += 1
if i == n - 1:
break
buy_at = i
i += 1
while i < n and a[i] >= a[i - 1]:
i += 1
sell_at = i - 1
money += a[sell_at] - a[buy_at]
print(mon... |
#
# PySNMP MIB module HUAWEI-NAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-NAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:47:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
class Color():
def __init__(self, red=0, green=0, blue=0, type=False):
self.red = red
self.green = green
self.blue = blue
# False = 15bit, True = 24bit
self.__type = type
if self.__type:
self.assert24Bit()
else:
self.assert15Bit()
... | class Color:
def __init__(self, red=0, green=0, blue=0, type=False):
self.red = red
self.green = green
self.blue = blue
self.__type = type
if self.__type:
self.assert24Bit()
else:
self.assert15Bit()
def get_red(self):
return self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.