content stringlengths 7 1.05M |
|---|
"""Helper functions that assist with testing, but are themselves not fixtures."""
def clear_data(db):
"""Clear all data in the database so the test suite has a clean slate to work with."""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
db.session.commit()
def... |
_marker = []
def merge(base, overlay):
"""Recursively merge two dictionaries.
This function merges two dictionaries. It is intended to be used to
(re)create the full new state of a resource based on its current
state and any changes passed in via a PATCH request. The merge rules
are:
* if a ... |
def remdup(l):
dupr=[]
for i in l:
if i not in dupr:
dupr.append(i)
l=dupr
print(l)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 29 09:25:41 2021
@author: Easin
"""
n,k = input().split()
k = int(k)
count = 0
a = input().split()
for elm in range(len(a)):
a[elm] = int(a[elm])
if int(a[k-1]) <= a[elm] and a[elm]:
count += 1
print(count)
|
description = 'STRESS-SPEC setup with Eulerian cradle'
group = 'basic'
includes = [
'system', 'monochromator', 'detector', 'sampletable', 'primaryslit',
'slits', 'reactor'
]
excludes = ['stressi', 'robot']
sysconfig = dict(
datasinks = ['caresssink'],
)
devices = dict(
chis = device('nicos.devi... |
# Complete the function below.
def findSum(a, b):
return(c)
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# %% hello cell for 8
hello="Welcome 8!!!"
print(hello)
# %% new cell to do sth
n1 = 8
n2 = 6
print("Product of ",n1," and ",n2, "is", n1*n2)
# %% new cell--trouble maker
print(hello,n1*dfasljn2)
# %% one more cell
print("Checked!")
... |
# -*- coding: utf-8 -*-
if not session.cart:
# instantiate new cart
session.cart, session.balance = [], 0
def index():
now = datetime.datetime.now()
span = datetime.timedelta(days=10)
product_list = db(db.product.created_on >= (now-span)).select(limitby=(0,3), orderby=~db.product.created_on)
r... |
"""Desenvolva um programa que leia o comprimento de três retas
e diga ao usuário se elas podem ou não formar um triângulo. """
""" formula
| b - c | < a < b + c
| a - c | < b < a + c
| a - b | < c < a + b
"""
# Jeito que o guanabara fez
print('=-'*30)
print('Analisando triangulos')
print('=-'*30)
a = float(input('Dig... |
#
# Copyright (C) 2018 Red Hat, Inc.
#
# 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, Versi... |
class ErrorBlinkStyle(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies constants indicating when the error icon,supplied by an System.Windows.Forms.ErrorProvider,should blink to alert the user that an error has occurred.
enum ErrorBlinkStyle,values: AlwaysBlink (1),BlinkIfDifferentError (0),NeverBl... |
class A:
X = 0
def __init__(self,v = 0):
self.Y = v
A.X += v
a = A()
b = A(1)
c = A(2)
print(c.X)
# Prints 3 |
URL = 'https://raw.githubusercontent.com/sarumont/py-trello/master/CHANGELOG'
def get_head(line, releases, **kwargs):
for release in releases:
print("checking", release, "vs", line)
if "v{}".format(release) == line:
return release
return False
def get_urls(releases, **kwargs):
... |
'''Leia dois valores inteiros, no caso para variáveis A e B. A seguir, calcule a soma entre elas e atribua à variável SOMA. A seguir escrever o valor desta variável.'''
A = int(input())
B = int(input())
SOMA = A + B
print('SOMA =', SOMA)
|
'''
Crie um programa que leia dois valores e mostre um menu na tela:
[ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.
'''
n1 = float(input('Digite o Primeiro Numero: '))
n2 = float(input('Digite o Segundo Numero: '))
me... |
# Copyright (c) 2010 Doug Hellmann. All rights reserved.
#
"""Simple example using doctest
"""
# end_pymotw_header
def my_function(a, b):
"""
>>> my_function(2, 3)
6
>>> my_function('a', 3)
'aaa'
"""
return a * b
|
class Memento:
def __init__(self, balance):
self.balance = balance
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
## SAVE all states
self.changes = [Memento(self.balance)]
## NEED to know index of current state for undo/redo
self.current... |
#!/bin/python
# Solution for https://www.hackerrank.com/challenges/game-of-thrones
string = raw_input().strip()
def can_be_palindrome(data):
odd_requencies = 0
for l in set(data):
current_frequency = data.count(l)
if current_frequency % 2:
odd_requencies += 1
if... |
#https://leetcode.com/problems/combination-sum-ii/description/
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.candidates = candidates
self.size = len(... |
#!/usr/bin/python3
with open('01_in.txt') as f:
lines = f.read()
data = [ float(x) for x in lines.split('\n') if x]
increases = 0
for i in range(1, len(data)):
increases += data[i] > data[i-1]
print(increases)
increases = 0
for i in range(3, len(data)):
old = sum( data[i-3:i] )
new = sum( data[i-2:i+1] )
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 14:20:52 2021
@author: caear
"""
def get_ratios(L1, L2):
"""
Parameters
----------
L1 and L2 are lists of equal length of numbers
Returns a list containing L1[i/L2[i]
-------
"""
ratios = []
for index in range(len(L1)):
try... |
'''
Created on 14.04.2016
@author: Tobias
'''
|
class Function:
def __init__(self, model_name, complexity_level, equation_string, output, mse):
self.model_name = model_name
self.complexity_level = complexity_level
self.equation_string = equation_string
self.output = output
self.mse = mse
def __str__(self):
'''... |
#-----------------------------------------------------------------------------
# Name: File Reading (fileReading - one line at a time.py)
# Purpose: To provide examples of how to read from files.
# Example from http://openbookproject.net/thinkcs/python/english3e/files.html
#
# Author: Mr. B... |
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0:
return 0
if x == 1:
return 1
pivot = x // 2
left, right = 0, pivot
while left <= right:
mid = (left + right) // 2
nxt = (mid + 1) * (mid + 1)
prev = (mid - ... |
PENN_TREEBANK_SRC = "https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/treebank.zip"
LOCAL_CORPORA_DIR_UNIX = "/usr/share/nl_data"
LOCAL_CORPORA_DIR_WINDOWS = "C:\\nl_data"
LOCAL_CORPORA_DIR_MAC = "/usr/local/share/nl_data" |
class ValidationError(ValueError):
"""
:param errors: a list of errors
"""
def __init__(self, errors):
self.errors = errors
class InconsistentOrderError(TypeError):
pass
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n, k = map(int, input().strip().split())
a ... |
"""
Módulo que gestiona todas las funcionalidades de introducción de datos
"""
'''from introducir.numero import (
solicitar_introducir_numero,
solicitar_introducir_numero_extremo,
)
from introducir.buleano import (
solicitar_introducir_si_o_no,
solicitar_introducir_verdadero_o_falso,
)
from introduci... |
# Atharv Kolhar
"""
Strings
"""
var_string = "The quick brown fox jumps over the lazy dog"
# Length of the string
print(len(var_string))
# Slicing the string
print(var_string[0:3])
# This will print characters at index 0,1,2
# Question
# #lazy dog
# Last Character Printing
print(var_string[-3:])
# Replace Char... |
class OpbTestMockable():
def __init__(self, case, filename):
self.case = case
self.filename = filename
self.prepender = []
self.replacers = {}
self.inputs = {}
self.proctotest = ""
self.appender = ["\nopbtestquitfn: output sD, FF\n"]
def testproc(self, pr... |
known_plugins = {
"BMP-FI": "imageio.plugins.freeimage",
"BMP-PIL": "imageio.plugins.pillow_legacy",
"BSDF": "imageio.plugins.bsdf",
"BUFR-PIL": "imageio.plugins.pillow_legacy",
"CUR-PIL": "imageio.plugins.pillow_legacy",
"CUT-FI": "imageio.plugins.freeimage",
"DCX-PIL": "imageio.plugins.pil... |
'''Property Definitions (bpy.props)
This module defines properties to extend blenders internal data, the result of these functions is used to assign properties to classes registered with blender and can't be used directly.
'''
def BoolProperty(name="", description="", default=False, options={'ANIMATABLE'... |
def calc(n):
if n == 0:
raise ZeroDivisionError
if n < 0:
raise ValueError
result = 100/n
return result
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 17 13:50:58 2017
@author: Anshu.Wang
"""
othe = othello()
othe.display()
othe.move(3,2,BLACK)
othe.move(2,2,WHITE)
othe.move(5,4,BLACK)
othe.move(5,3,WHITE)
othe.move(5,2,BLACK)
othe.move(4,2,WHITE) |
# Write a program to check the given person is eligible to vote or not
a = int(input("Age of a persion: "))
if(a>=18):
print("Yes,The persion is eligible to vote")
else:
print("No,The persion is not eligible to vote")
|
SkillSanta_Dict={
"name":"Pooja",
"age":22,
"salary":60000,
"city":"new delhi"
}
print("previous dictionary is:",SkillSanta_Dict)
SkillSanta_Dict["location"]=SkillSanta_Dict["city"]
del SkillSanta_Dict["city"]
print("change dictionary is:",SkillSanta_Dict)
|
def nba_extrap(ppg, mpg):
if mpg == 0:
return 0
else:
return round(ppg*48.0/mpg, 1) |
"""
The `app_metadata` module stores data for formatting metadata in the main.py application file.
"""
tags_metadata = [
{
"name": "default",
"description": "Application area-wide settings",
},
{
"name": "tasks",
"description": "Task management with description, solution code... |
#!/usr/bin/env python3
END_MARK = None
for _ in range(int(input())):
input() # don't need n
# build the trie
trie = {}
for word in input().split():
cur = trie
for ch in word:
try:
cur = cur[ch]
except KeyError:
nxt = {}
... |
# -*- coding: utf-8 -*-
class ComponentBaseException(Exception):
pass
class ComponentAPIException(ComponentBaseException):
"""Exception for Component API"""
def __init__(self, api_obj, error_message, resp=None):
self.api_obj = api_obj
self.error_message = error_message
self.resp... |
"""
Faça uma função não-recursiva que receba um número inteiro positivo n e retorne o hiperfatorial desse número.
Doctests:
>>> hiperfatorial(4)
27648
>>> hiperfatorial(2)
4
>>> hiperfatorial(1)
1
>>> hiperfatorial(3)
108
"""
def hiperfatorial(num: int):
hiper = 1
for c in range(1, num+1):
hiper *= ... |
load("//node:node_grpc_compile.bzl", "node_grpc_compile")
load("//node:node_module_index.bzl", "node_module_index")
load("@org_pubref_rules_node//node:rules.bzl", "node_module")
def node_grpc_library(**kwargs):
name = kwargs.get("name")
deps = kwargs.get("deps")
visibility = kwargs.get("visibility")
n... |
def genera_span(lista):
diccionario_es = {
"normal": "Normal", "fire": "Fuego", "flying": "Volador",
"steel": "Acero", "water": "Agua", "electric": "Eléctrico",
"grass": "Planta", "ice": "Hielo", "fighting": "Lucha",
"poison": "Veneno", "ground": "Tierra", "psychic": "Psíquico",
... |
"""
DSN means: "domain specific nerf" (the name is obviously tentative)
The idea is: in many subparts of the application, we apply the same pattern:
* a structure
* a Clef (set of notes that operate on that structure)
* play_... & construct_... can be used to combine the 2.
In principle, a single structure can have ... |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.return_urls
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class ReturnUrls(object):
"""Implementation of the 'ReturnUrls' model.
Return urls for the identity request
Attributes:
... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2018, Anaconda, Inc. and Intake contributors
# All rights reserved.
#
# The full license is in the LICENSE file, distributed with this software.
#------------------------------------------------------------------------... |
resource_type = [
('v1', 'Pod', 'pod'),
('batch/v1', 'Job', 'job.v1.batch')
]
|
"""58. Length of Last Word
https://leetcode.com/problems/length-of-last-word/
Given a string s consists of upper/lower-case alphabets and empty space
characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of
no... |
n = s = 0
while True:
n = int(input("Type a number » "))
if n == 999:
break
s += n
print(f"Sum of value {s}") |
numeros = []
pares = []
impares = []
perg = ''
'''while True:
valor = int(input('Digite um número: '))
numeros.append(valor)
if valor % 2 == 0:
pares.append(valor)
else:
impares.append(valor)
perg = str(input('Quer continuar? [S / N] '))[0].strip().upper()
if perg in 'Nn':
... |
class Weight():
def __init__(self, value=0.0, previous_delta=0.0):
self.value = value
self.previous_val = value
self.previous_delta = previous_delta
def add_delta(self, delta_w):
self.previous_val = self.value
self.value -= delta_w
self.previous_delta = delta_w... |
class CanExecuteChangedEventManager(WeakEventManager):
# no doc
@staticmethod
def AddHandler(source,handler):
""" AddHandler(source: ICommand,handler: EventHandler[EventArgs]) """
pass
@staticmethod
def RemoveHandler(source,handler):
""" RemoveHandler(source: ICommand,handler: EventHandler[EventArgs]... |
#
# PySNMP MIB module Wellfleet-ATM-LE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-ATM-LE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:39:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
#Tienen DNI, nombre, correo electrónico, teléfono, domicilio, lista de libros en prestamo
#import Book as book
class User:
def __init__(self, dni="", name="", email="", phone=0, address=""):
self.__dni = dni
self.__name = name
self.__email = email
self.__phone = phone
self._... |
"""
PASSENGERS
"""
numPassengers = 1311
passenger_arriving = (
(2, 6, 2, 2, 1, 0, 0, 6, 1, 3, 1, 0), # 0
(0, 3, 0, 0, 2, 0, 2, 3, 1, 2, 1, 0), # 1
(2, 1, 3, 1, 1, 0, 2, 6, 1, 3, 0, 0), # 2
(2, 1, 1, 0, 2, 0, 3, 5, 1, 0, 0, 0), # 3
(1, 3, 2, 0, 2, 0, 3, 3, 3, 5, 1, 0), # 4
(5, 5, 3, 2, 0, 0, 2, 3, 1, 2, 1,... |
class IExtension:
""" An interface that supports the additional operation for Extension Status """
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
|
"""
Assessment Module
Written by Ed Oughton.
Winter 2020
"""
def assess(country, regions, option, global_parameters, country_parameters, timesteps):
"""
For each region, assess the viability level.
Parameters
----------
country : dict
Country information.
regions : dataframe
... |
n1 = float(input('Digite um distancia em metros: '))
print('Coversão para Quilometros: {}'.format(n1/1000))
print('Conversão para Equitometro: {}'.format(n1/100))
print('Conversão para Decametro: {}'.format(n1/10))
print('Conversão para Decimetro: {}'.format(n1*10))
print('Convesão para Centimetro: {}'.format(n1*100))
... |
def countDigits(n):
c = 0
while n:
c +=1
n //=10
return c
def match(val,x):
ans = {
1: lambda x: x,
2: lambda x: f'{x//10} * 10 + {x%10}',
3: lambda x: f'{x//100} * 100 + {x//10%10} * 10 + {x%10}',
4: lambda x: f'{x//1000} * 1000 + {x//100%10} * 100 + {x//10%10} * 10 + {x%10}'
}[val](x)
return ans
de... |
class DocumentPreviewSettings(object,IDisposable):
""" Contains the settings related to the saving of preview images for a given document. """
def Dispose(self):
""" Dispose(self: DocumentPreviewSettings) """
pass
def ForceViewUpdate(self,forceViewUpdate):
"""
ForceViewUpdate(self: DocumentPreviewSett... |
class Constants:
# DR_Net
DRNET_EPOCHS = 100
DRNET_SS_EPOCHS = 1
DRNET_LR = 1e-4
DRNET_LAMBDA = 0.0001
DRNET_BATCH_SIZE = 256
DRNET_INPUT_NODES = 30
DRNET_SHARED_NODES = 200
DRNET_OUTPUT_NODES = 100
ALPHA = 1
BETA = 1
# Adversarial VAE Info GAN
Adversarial_epochs = 1... |
#
# PySNMP MIB module Wellfleet-MPLS-LDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-MPLS-LDP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:40:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
"""
BSTree implementation
"""
__all__ = [
'is_node',
'new_bstree'
]
class Node:
__slots__ = (
'_key',
'_value',
'_left_child',
'_right_child'
)
def __init__(self, key, value, left_child=None, right_child=None):
self._key = key
self._value = value
... |
#
# PySNMP MIB module CPQIDE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQIDE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:11:50 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:... |
def foo(x):
for i in range(x):
try:
pass
finally:
try:
try:
print(x, i)
finally:
try:
1 / 0
finally:
return 42
finally:
... |
class Token:
def __init__(self, content):
try:
self.content = int(content)
except ValueError:
raise ValueError("Token content must be a number composed only of digits.")
def __repr__(self):
"""Representation of the Token object as a string mimicking the cont... |
class MissingRemote(Exception):
"""
Raise when a remote by name is not found.
"""
pass
class MissingMasterBranch(Exception):
"""
Raise when the "master" branch cannot be located.
"""
pass
class BaseOperation(object):
"""
Base class for all Git-related operations.
""... |
def funcao(x,y):
return 3*x+4*y
def foldt(function,lista):
x=0
for i in range(0,len(lista)):
x+=function(x,lista[i])
return x
lista=[1,2,3,4]
print(foldt(funcao,lista))
|
class Player(object):
"""docstring for Player"""
def __init__(self, name, money):
self.name = name
self.money = money
def __init__(self, name):
self.name = name
# Default is $500
self.money = 500
def lose_money(self, amt):
self.money -= amt
def gain_money(self, amt):
self.money ... |
p=int(input("Digite o primeiro termo da P.A: "))
r=int(input("Digite a razão da P.A: "))
d= p+(10-1)*r
for c in range(p,d,r):
print('{}'.format(c), end=' -> ')
|
"""
1 - Traversal
When designing iterative functions, take the tree below as an example.
A
B C
Iterative Traversal Model:
# init
res = []
stack = []
node = root
# loop
while node is not None or stack:
- Pre (M -> L -> R)
while node is not None:
... |
def main():
problem()
#PROBLEM
#Create a task list. A user is presented with the text below. Let them select an option to list all of their tasks, add a task to their list, delete a task, or quit the program.
#Make each option a different function in your program.
# Do NOT use Google. Do NOT use other students. T... |
#Traduza os comandos a seguir para expressões Booleanas em Python e avalie-as:
print('=' * 50)
print('(a) A soma de 2 e 2 é menor que 4.')
resposta = 2 + 2 < 4
print(resposta)
print('=' * 50)
print('(b) O valor de 7 // 3 é igual a 1 + 1.')
resposta = 7 // 3 == 1 + 1
print(resposta)
print('=' * 50)
print('(c) A soma d... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 29 14:24:51 2021
@author: Hari Kishan Perugu
"""
|
def Kth_max_min(l, n, k):
l.sort()
return (l[k-1], l[-k])
if __name__ == "__main__":
t = int(input())
while t > 0:
n = int(input())
arr = list(map(int, input().split(' ')))
k = int(input())
print(Kth_max_min(arr, n, k))
t -= 1
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
ret... |
# Server IP
XXIP = '127.0.0.1'
# Client ports
XXPORT = 5000
XXVIDEOPORT = 5001
XXAUDIOPORT = 5002
XXSCREEENPORT = 5003
BECTRLPORT = 5004 |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2017 Vic Chan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
count = 0
for i in range(len(nums)-2):
if nums[i] * 3 >= tar... |
#
# @lc app=leetcode id=35 lang=python3
#
# [35] Search Insert Position
#
# @lc code=start
class Solution:
def searchInsert(self, nums: List[int], target: int):
if not nums:
return 0
if target <= nums[0]:
return 0
if target > nums[-1]:
return len(nums)
... |
"""Private config items for mqtt-audio-alert."""
sounds = {
# 'NAMEOFSOUND1': '/PATH/TO/AUDIOFILE.mp3',
# 'NAMEOFSOUND2': '/PATH/TO/AUDIOFILE.mp3'
}
# Time ranged where sounds are permitted to play.
# Multiple time ranges are allowed.
active_times = [
#['07:00', '12:00'],
#['13:15', '14:15'],
['0... |
# -*- coding: utf-8 -*-
class TweetBuilder(object):
"""Constructs tweets to specific users"""
def __init__(self, mention_users):
"""Create a new tweet builder which will mention the given users"""
super(TweetBuilder, self).__init__()
# Convert lists to a space separated string
... |
# Copypastas by BACVelocifaptor#6969, he#9999 and u/GerardDG on Reddit. Script written by BACVelocifaptor#6969. If you kang, you big gei.
opt = {
"v":"""
I always knew humanity cannot be the only cognizant species in the galaxy. The fact that we are less than type 1 on the Kardashev scale always bothered... |
class Vec2:
x: float
y: float
def __init__(self, x:float, y:float) -> None:
self.x = x
self.y = y
|
while(True):
try:
a = int(input())
if(a==2002):
print("Acesso Permitido")
break
else:
print("Senha Invalida")
except EOFError:
break |
BYTES_PREFIXES = ("", "K", "M", "G", "T")
PREFIX_FACTOR_BYTES = 1024.0
def bytes_for_humans(size, suffix="B"):
"""
Function to get bytes in more human readable format, untranslated, for logging purposes only.
:type size: int
:type suffix: str
:rtype: str
"""
for prefix in BYTES_PREFIXES:
... |
#!/usr/bin/env python3
def gregorian_to_ifc(day, month, leap=False):
month = month - 1
day = day - 1
days_per_month = [31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31]
if leap: days_per_month[1] = 29
day_number = 0
for m in range(month):
day_number += days_per_month[... |
# Finding the second largest number in a list.
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split())) # Converting input string into list by map and list()
new = [x for x in arr if x != max(arr)] # Using list compressions building new list removing the highest number
print(max... |
brasileirao2018 = 'Palmeiras', 'Flamengo', 'Internacional', 'Grêmio', 'São Paulo', \
'Atlético MG', 'Athletico PR', 'Cruzeiro', 'Botafogo', 'Santos', \
'Bahia', 'Fluminense', 'Corinthians', 'Chapecoense', 'Ceará', \
'Vasco', 'Sport', 'América-MG', 'Vitória', 'Paraná... |
# someone in the internet do that
i = 1
for k in (range(1, 21)):
if i % k > 0:
for j in range(1, 21):
if (i * j) % k == 0:
i *= j
break
print(i)
|
class Unit:
def __init__(self, name, hp, damage):
self.name=name
self.damage=damage
self.hp=hp
print("{0} 유닛이 생성되었습니다." .format(self.name))
print("체력 : {0}, 공격력 : {1}" .format(hp,damage))
wraith1 = Unit("레이스", 80, 5)
print("유닛 이름 : {0}, 공격력 {1}" .format(wraith1.name, wraith1... |
async def commands_help(ctx, help_ins):
message = help_ins.get_help()
if message is None:
message = 'No such command available!'
await ctx.send(message) |
n = int(input())
while n > 0:
c = input()
print('gzuz')
n -= 1 |
# This file is part of VoltDB.
# Copyright (C) 2008-2020 VoltDB Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ver... |
p,q = [int(i) for i in input().split()]
if (p % 2 == 1 and q % 2 == 1):
print(1)
elif (p % 2 == 0):
print(0)
elif (q > p):
print(2)
else:
print(0)
|
# Snippets from Actual Settings.py
TEMPLATES = [
{
'BACKEND': 'django_jinja.backend.Jinja2',
"DIRS": ["PROJECT_ROOT_DIRECTORY", "..."],
'APP_DIRS': True,
'OPTIONS': {
'match_extension': '.html',
'context_processors': [
'django.template.context... |
class Solution:
def solve(self, nums):
rights = []
left_ans = []
for num in nums:
if num < 0:
while rights and rights[-1] < abs(num):
rights.pop()
if not rights:
left_ans.append(num)
if rig... |
#
# This file contains the Python code from Program 2.7 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm02_07.txt
#
def geometricSeries... |
# Author: BHARATHI KANNAN N - Github: https://github.com/bharathikannann, linkedin: https://linkedin.com/in/bharathikannann
# ## Linked List
#
# - Linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next.
# - In its mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.