content stringlengths 7 1.05M |
|---|
# Python program to learn about control flow
number = 23
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# New block ends here
elif guess < number:
# Another block
print('N... |
#takes data from the Game() class and...
#1. populates the score board with the runs scored and balls used by batsman
#2. changes the player position if the run hit is 1,3 or 5
#3. removes the player from the activePlayers list and the playing list if he gets out
class Runs():
def __init__(self,run,playing,remain... |
class Arrayerrortype(basestring):
"""
ARRAY_INCONSISTENT_ADDRESSING_METHOD|ARRAY_DEVTYPE_ERROR
Possible values:
<ul>
<li> "array_inconsistent_addressing_method" - Array is using
inconsistent LUN addressing schemes.,
<li> "array_devtype_error" - Array has
encountered ... |
#!/usr/bin/env python3
# Author:: Justin Flannery (mailto:juftin@juftin.com)
"""
Project Configuration for Yellowstone Variables
"""
class SearchConfig:
"""
File Path Storage Class
"""
POLLING_INTERVAL_MINIMUM: int = 5 # 5 MINUTES
RECOMMENDED_POLLING_INTERVAL: int = 10 # 10 MINUTES
ER... |
__author__ = 'cosmin'
class CommandError(Exception):
def __init__(self, arg):
self.msg = arg
class InvalidParameters(Exception):
def __init__(self, arg):
self.msg = arg |
if __name__ == '__main__':
N = int(input())
nested_list = []
for _ in range(N):
name = input()
score = float(input())
nested_list.append([name,score])
score_list = []
for i in nested_list:
score_list.append(i[1])
mini = min(score_list)
score_list = sorted(scor... |
colors = {"Red", "Green", "Blue"}
# add(): adds item to the set.
colors.add("Magenta")
print(colors)
# discard(): removes item from set without error if not present.
colors.discard("Blue")
colors.discard("Blue")
print(colors)
# remove(): removes item from set with KeyError if not present.
colors.remove("Red")
# colo... |
"""Presets for end-to-end model training for special tasks."""
__all__ = [
'tabular_gpu_presets'
]
|
class ProcessoSimulado:
idProcesso = 0
contadorPrograma = 0
tempoInicio = 0
idProcessoPai = 0
estado = 0 # Bloqueado:0, Pronto:1, Em execução:2
prioridade = 0 # 0,1,2,3 sendo que 3 é a mais baixa e 0 a mais alta
tempoCPU = 0
instrucoes = []
def __init__(self, idProcesso, contadorPr... |
# -*- coding: utf-8 -*-
def main():
n, m, x, y = map(int, input().split())
xs = list(map(int, input().split())) + [x]
ys = list(map(int, input().split())) + [y]
x_max = max(xs)
y_min = min(ys)
if x_max < y_min:
print('No War')
else:
print('War')
if __na... |
description_short = "linux signal file descriptor for python"
keywords = [
"signalfd",
"python3",
"linux",
]
|
a, n = map(int, input().split())
ans = 0
for i in range(n):
ans = ans + (n - i) * a * (10 ** i)
print(ans)
|
def parse_comment(comment, data):
comment.etag = data["etag"]
comment.id = data["string"]
# snippet
snippet_data = data.get("snippet", False)
if snippet_data:
comment.author_display_name = author_display_name_data["snippet"][
"authorDisplayName"
]
comment.author_... |
def isPalindrome(strn):
for i in range(0, len(strn)//2):
if strn[i] != strn[len(strn)-i-1]:
return False
return True
x=input()
if isPalindrome(x)==1:
print("Yes, '{}' is a palindrome".format(x))
else:
print("No, '{}' is NOT a palindrome".format(x))
|
# Faça um programa que tenha uma função chamada escreva(), que receba um texto
# qualquer como parâmetro e mostre uma mensagem com tamanho adaptável.
def escreva(msg):
a = len(msg) + 4
print('~' * a)
print(f'{msg.center(a)}') # Centralizando a formatação de uma string
print('~' * a)
escrev... |
"""
You can't call grok.context multiple times on module level:
>>> import grokcore.component.tests.adapter.modulecontextmultiple_fixture
Traceback (most recent call last):
...
GrokImportError: The 'context' directive can only be called once per
class or module.
"""
|
# @Title: 提莫攻击 (Teemo Attacking)
# @Author: KivenC
# @Date: 2018-07-24 13:50:50
# @Runtime: 116 ms
# @Memory: N/A
class Solution(object):
def findPoisonedDuration(self, timeSeries, duration):
"""
:type timeSeries: List[int]
:type duration: int
:rtype: int
"""
if tim... |
if __name__ == "__main__":
# Read integer input from stdin
t = int(input())
for t_itr in range(t):
# Read string input from stdin
n, k = list(map(int, input().split()))
# Compute bitwise and max value
print(k-1 if ((k-1) | k) <= n else k-2)
|
# -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
__author__ = 'ZGQ'
|
# https://app.terra.bio/#workspaces/broad-dsp-hca-processing-prod4/Bone-Marrow-Myeloma-copy/workflows/broad-dsp-hca-processing-prod4/CreateSS2AdapterMetadata
BAM_INPUT = {
"file_path": "/cromwell_root/localized-path/call-HISAT2PairedEnd/cacheCopy/0244354d-cf37-4483-8db3-425b7e504ca6_qc.bam",
"sha256": "1d7038c... |
#! /usr/bin/env python3
a = 1
b = 0
x = 1
limit = 1000
while len("%d"%a) < limit:
print("F(%d) %d: %d " % (x,len("%d"%a),a))
c = a
a = a+b
b = c
x+=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 FindElements:
def __init__(self, root: TreeNode):
self.root = root
self.recover(self.root, 0)
de... |
# Given two strings str1 and str2 and below operations that can performed on str1.
# Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.
# Insert
# Remove
# Replace
# All of the above operations are of equal cost.
def editDistance(s,t):
m = len(s)
n = len(t)
dp = [[0 for j in ra... |
a = 10
if 0 <= a < 5:
print('[0, 5)')
elif 5 <= a < 8:
print('[5, 8)')
else:
print('[8, +Infinity)')
|
for T in range(1,int(input())+1):
t,c=input().split()
t=list(t)
c=int(c)
ans=0
for i in range(len(t)-c+1):
if t[i]=='-':
ans+=1
for j in range(i,i+c): t[j]='+' if t[j]=='-' else '-'
if not '-' in t: print('Case #%d:'%T,ans)
else: print('Case #%d: IMPOSSIBLE'%T) |
# Time: O(n)
# Space: O(1)
class Solution:
def missingNumber(self, nums):
n = len(nums)
sum = n * (n + 1) / 2
sum2 = 0
for i in nums:
sum2 += i
return int(sum - sum2)
if __name__ == "__main__":
nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
s = Solution()
... |
# Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite.
vel = float(input('Digite a velocidade do carro: '))
if vel > 80.0:
multa = (vel - 80.0) * 7
print('Voce foi multado em R$ ... |
class Solution:
def uniquePaths(self, m, n):
dp = [[0] * n for i in xrange(m)]
dp[m - 1][n - 1] = 1
process = collections.deque([(m - 1, n - 1)])
while process:
i, j = process.popleft()
if j < n - 1:
a = dp[i][j + 1]
el... |
# Adapted from a Java code in the "Refactoring" book by Martin Fowler.
# Replace temp with query
# Code snippet. Not runnable.
def get_price():
base_price = quantity * item_price
discount_factor = 0
if base_price > 1000:
discount_factor = 0.95
else:
discount_factor = 0.98
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/30 10:38
# @Author : Leishichi
# @File : 12.py
# @Software: PyCharm
# @Tag:
class Solution:
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
symbols = {1: "I", 5: "V", 10: "X", 50: "L", 100: "... |
# Esto es un comentario
# Input siempre regresa una string(palabra)
# Nombre
nombre = "Cristian"
print("Mi nombre es " + nombre)
# Apellidos
apellidoPaterno = "Flores"
apellidoMaterno = "Bernal"
apellidos = apellidoPaterno + ' ' + apellidoMaterno
print("Mis Apellidos son: " + apellidos)
# Edad
edad =... |
"""
encoders.py
-----------
Convert GraphData to texts.
"""
def encode_edgelist(graph, delimiter=' ', attr=False, header=False):
text = ''
if header:
text += delimiter.join([str(a) for a in graph.edge_attr[:2]])
if attr:
text += delimiter
text += delimiter.join([str(... |
# Largest palindrome product
def checkPalindrome(x):
if str(x) == str(x)[::-1]:
return True
return False
maxPalindrome = 0
for x in range(999,99,-1):
for y in range(999,99,-1):
if checkPalindrome(x*y):
print(x,y)
print(x*y)
if x*y > maxPalindrome:
... |
class Animal:
name = "Lion"
noise = "Rrrrr"
color = "Gray"
def make_noise(self):
print(f"{self.noise}")
def get_noise(self):
return self.noise
def set_noise(self, new_noise):
self.noise = new_noise
def show_name(self):
print(f"{self.name}")
def get_name(se... |
# Time complexity: O(n*2^n)
# Approach: For each subset, iterate from 0 to n-1 and for each number in binary, take elements corresponding to 1s.
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
n = len(nums)
ans = []
for i in range(2*... |
class rawDataError(Exception):
def __init__(self):
self.message = 'Please choose a valid raw data file!'
super().__init__(self.message)
class ratioError(Exception):
def __init__(self):
self.message = 'Could not read Active:Carbon:Binder ratio input.'
super().__init__(self.messag... |
class Reservations:
def __init__(self, client):
self.client = client
def list(self, params={}):
return self.client.request('GET', self._url(params), params)
def create(self, params={}):
return self.client.request('POST', self._url(params), params)
def show(self, id):
u... |
"""
time complexity = O(n) space complexity = O(1)
set MAX and MIN value to be 32 bits maximun and minimun integar
strip to delete whitespace
remain sign as 1 or -1
check each char should be in '0'~ '9'
plus the ret as each bit check MAX//10 and ret to make sure result will not out of range
return ret*sign
"""
clas... |
def english_full_name(first=None, last=None, middle=None,
prefix=None, suffix=None):
fullname = None
if first is None or last is None:
raise ValueError("first and last must be specified")
if middle:
fullname = first + " " + middle + " " + last
else:
fullna... |
del_items(0x80122C20)
SetType(0x80122C20, "struct THEME_LOC themeLoc[50]")
del_items(0x80123368)
SetType(0x80123368, "int OldBlock[4]")
del_items(0x80123378)
SetType(0x80123378, "unsigned char L5dungeon[80][80]")
del_items(0x80123008)
SetType(0x80123008, "struct ShadowStruct SPATS[37]")
del_items(0x8012310C)
SetType(0x... |
# -*- coding: utf-8 -*-
def pytest_addoption(parser):
group = parser.getgroup("portion")
group.addoption(
"--portion", action="store", help='Select a part of all the collected tests in the form "i/n" or "start:end"'
)
def slice_fraction(sequence, i, n):
"""
Split a sequence in `n` slices... |
def normalize_bbox(bbox, size):
return [
int(1000 * bbox[0] / size[0]),
int(1000 * bbox[1] / size[1]),
int(1000 * bbox[2] / size[0]),
int(1000 * bbox[3] / size[1]),
]
|
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
result = set()
l = len(nums)
for a in range(l - 3):
if a > 0 and nums[a] == nums[a - 1]: continue
if nums[a] + nums[a + 1] + nums[a + 2] + nums[a + 3] > target: ... |
a = int(input())
b = int(input())
for i in range(a,b+1):
if i%2==0:
print(i) |
'''
BFS is a tree traversal method. We search the graph level by level.
- The concept is a layered traversal.
- This means we start at the root of the node and we begin a "levelled" traversal.
Let's define the **level or depth of a given node the amount of edges between that node and the root**.
Let's look at the fo... |
defs = {
'season': {
'type': 'numeric',
'options': {
'min_length': 1,
'max_length': 2
}
},
'episode': {
'type': 'numeric',
'options': {
'min_length': 1,
'max_length': 2
}
},
'shot': {
'type': 'nume... |
def main():
h,w = map(int,input().split())
maze = []
for _ in range(h):
maze.append(list(input()))
dx = [1,0,-1,0]
dy = [0,1,0,-1]
que = []
que.append([0,0])
d = [[-1 for _ in range(w)] for _ in range(h)]
d[0][0] = 0
while len(que)!=0:
qx,qy = que.pop()
f... |
class RuleCollection(object):
def __init__(self, name, ruleset_list, result_on_match):
self.name = name
self.ruleset_list = ruleset_list
self.result_on_match = result_on_match
def check(self, data):
results = []
for ruleset in self.ruleset_list:
results.append(ruleset.check(data))
... |
class A:
def __init__(self):
self.nr=int(input())
self.nc=int(input())
self.matrix=[]
for i in range(self.nr):
self.col=[]
for j in range(self.nc):
self.element=int(input())
self.col.append(self.element)
... |
poesia = list()
poesia = input().split(" ")
while "*" not in poesia[0]:
aux = poesia[0]
aux = aux[0].lower()
tam = 0
for i in poesia:
if i[0].lower() == aux:
tam+=1
if tam == len(poesia):
print("Y")
else:
print("N")
poesia.clear()
poesia = input().split(" ")
|
# Time: O(n^2)
# Space: O(n^2)
# On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j).
#
# Now rain starts to fall. At time t, the depth of the water everywhere is t.
# You can swim from a square to another 4-directionally adjacent square
# if and only if the elevation of both squares... |
class CommonWriter:
"""
Writer interface
"""
def write(self, dictionary):
raise Exception("unimplemented") |
#
# PySNMP MIB module ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH
# Produced by pysmi-0.3.4 at Wed May 1 13:06:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
#... |
def ordenada(lista):
ordem = True
for index in range(len(lista)-1):
if lista[index] > lista[index + 1]:
ordem = False
return ordem
|
def credits():
print('\nObrigado por jogar !\n')
print('-' * 20)
print('CRÉDITOS FINAIS \nDiretor Geral - Álef Ádonis\nProgramador - Álef Ádonis\nRoteirista - Álef Ádonis\nEditor Chefe - Álef Ádonis\n\nUM PEQUENO GESTO PARA DEMOSTRAR MEU AMOR')
print('-' *20)
|
DATA = '../data/articles/'
BUILDINGS = "../data/buildings/"
OUTPUT = '../output/'
PHOTO_LOC = '/Users/elisabethsilver/Box/SIB/photos/'
DATA_FNAME = f"{DATA}uni_data.xlsx"
FMTD_DATA_FNAME = f"{DATA}uni_data_year_formatted.xlsx"
LINK_FNAME = f"{DATA}uni_links.csv"
YEAR_LINK_FNAME = f"{DATA}uni_links_year.csv"
GDRIVE = "... |
def generate(env):
env.Replace(
MODE='Release'
)
env.Append(
CPPDEFINES={'RELEASE': None},
CCFLAGS=[
'-O3',
],
)
def exists(env):
return 1
|
def binomial( k, n ):
if n < k or n < 0 or k < 0:
raise ValueError("n > k > 0")
if k == 1 or k == (n-1):
return n
elif k == 0 or k == n:
return 1
return binomial( k, n - 1 ) + binomial( k-1, n-1)
print("( a nad b )")
a = int(input("A = "))
b = int(input("B = "))
print( binom... |
__all__ = ['merge_lists']
# HELPER FUNCTION FOR MERGING LISTS
def merge_lists(*args, **kwargs):
merged = []
for seq in args:
for element in seq:
merged.append(element)
return merged |
def tablefy(data, column=None, gutter=1, width=79):
"""
Convert a list of strings into being a table, displaying in a left-to-right
and top-to-bottom pattern. This does not sort the values.
:param data: list of strings
:param column: width of column, if None, detected
:param gutter: width of g... |
def sockMerchant(n, ar):
ar_no_duplicates = dict.fromkeys(ar)
pairs = 0
for sock in ar_no_duplicates:
ocurrences = ar.count(sock)
print("ocurrences of {} in {} -> {}".format(sock, ar, ocurrences))
if ocurrences % 2 == 0:
pairs += ocurrences / 2
elif ocurrences % ... |
nome = input()
salfixo = float(input())
qtdvendas = float(input())
bonus = float(qtdvendas * (15/100))
total = salfixo + bonus
print ('TOTAL = R$ %0.2f' %total)
|
"""
The ``density`` module contains functions to calculate the density and
temperature at hub height of a wind turbine.
SPDX-FileCopyrightText: 2019 oemof developer group <contact@oemof.org>
SPDX-License-Identifier: MIT
"""
def barometric(pressure, pressure_height, hub_height, temperature_hub_height):
r"""
C... |
def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
print(gcd(5,20))
|
#!/usr/bin/env python
if __name__== '__main__':
#set help message
help = """
Usage: help
TOOLS:
=== Help ===
./help.py [[this file]]
=== Generate results and plot ===
./run_1.py [[Do 1 run. Input conf file. Output rundir w/ csv and dbs.]]
./plot_1.py [[Plot results from 1 run. Inp... |
class Lift:
def __init__(self, name, lift_type, status, sector):
self.name = name
self.lift_type = lift_type
self.status = status
self.sector = sector
def __str__(self):
return self.name + " " + self.lift_type + " " + self.status + " " + self.sector
|
class Constants:
j_title_list = [
'Journal of Academy of Marketing Science',
'Journal of Marketing',
'Journal of Marketing Research',
'Marketing Science',
'Management Science',
'Administrative Science Quarterly',
'Academy of Management Journal',
'Academy of Management Review']
... |
def factorial(n):
if n==1 or n==0:
return 1
return n*factorial(n-1)
|
# Code listing #10
""" Module A (a.py) - Implement functions that operate on series of numbers """
# Note this is version 1 of a.py so called a1.py
def squares(narray):
""" Return array of squares of numbers """
return pow_n(narray, 2)
def cubes(narray):
""" Return array of cubes of numbers """
retu... |
app = Flask(__name__)
api = Api(app)
index = RetrievalIndex()
class BuildIndex(Resource):
def post(self):
request_body = json.loads(request.data)
user_id = request_body["user_id"]
image_hashes = request_body["image_hashes"]
image_embeddings = request_body["image_embeddings"]
index.build_index_for_user(user_i... |
# ###########################################################
# ## generate menu
# ###########################################################
_a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(T('... |
BASE = r"""Export of Github issues for [{repo_name}]({repo_url}).{datestring}
{issues}
"""
ISSUE = r"""# [\#{number}]({url}) `{state}`: {title}
{labels}
#### [{author}]({author_url}) opened issue at [{date}]({url}):
{body}
{comments}
<div style="page-break-after: always;"></div>
"""
COMMENT = r"""#### [{author}]({... |
"""Base
Base Package
more description
"""
|
class ReverseProxied(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
print(environ)
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH... |
"""
Package for the application.
"""
#from .graficoLinhaTempo import PlotGraphTimeLineBar
#from .DataFrameUtil import SumRows
#from .DataFrameUtil import RenameCols |
print("first string" + ", " + "second string")
print(str(1) + "2" + "3" + "4")
print("spam" * 3)
print(4 * "2")
print("Love" * 0)
print("7" * 3)
# 1 + "2" + 3 -- TypeError
# "4" * "2" -- TypeError
# "Python is fun" * 7.0 -- TypeError
|
f = open("all.txt")
s = f.readlines();
f.close()
fout = open("allout1.txt", 'w')
o = []
outPath = 'S:\\BACKUP!!!\\WD\\L\\Canon\\All\\'
quote = "\""
for x in s:
#x.replace('\\', '\\\\')
#print(x)
#if x.rfind('MVI') > -1: ix = x.rindex('MVI');
x = x.strip();
if x.rfind('MVI') > -1: ix ... |
class Solution:
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
count = 0
n = len(nums)
d = {}
for i in range(n):
d[nums[i]] = i
for i in range(n):... |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
class _FieldInfo:
""" Exposes the public members of the System.Reflection.FieldInfo class to unmanaged code. """
def Equals(self,other):
"""
Equals(self: _FieldInfo,other: object) -> bool
Provides COM objects with version-independent access to the System.Object.Equals(System.Object)
method... |
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""
Simple calculator that determines the
price of a meal after tax and tip
Author: Alexander A. Laurence
Last modified: January 2019
Website: www.celestial.tokyo
"""
# pricing
meal = 44.5
tax = 6.75/100
tip = 15.0/100
# logic
meal = meal + (meal*tax)
total = meal+(meal*... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"ROOT_DIR": "00_core.ipynb",
"DOWNLOAD_DIR_BASE": "00_core.ipynb",
"PROCESSED_DIR_BASE": "00_core.ipynb",
"DATASET_DIR": "00_core.ipynb",
"create_country_dirs": "00_core.ip... |
class Quark:
""" An :class:`src.ops.ElementalOperator` is a product of quark fields and
other commuting objects.
:param barred: Specifies if quark or anti-quark
:type barred: bool
:param flavor: Quark flavor
:type flavor: char
:param spin: Quark spin
:type s... |
server='tcp:mkgsupport.database.windows.net'
database='mkgsupport'
username='mkguser'
password='Usersqlmkg123!'
driver='/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.6.so.1.1'
|
# _create_empty_dict.py
__module_name__ = "_create_empty_dict.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["vinyard@g.harvard.edu",])
def _create_empty_dict(keys):
"""
Create an empty python Dictionary given a set of keys.
Parameters:
-----------
keys
... |
""" faça um programa que leia um numeo de 0 a 9999 e mostre na tela cada um dos seus digitos separados"""
numero = int(input('Digite um numero entre 0 e 9999 para exibir seus valores: '))
u = numero // 1 % 10 # nesse caso eu estou dividino inteiro e pego o resto da divisão
d = numero // 10 % 10
c = numero // 100 % 1... |
seq_emoji_map = {
'A': ':apple:', # avocado? differnet colours?
'C': ':corn:',
'T': ':tomato:',
'G': ':grapes:',
'N': ':question:'
}
all_qualities = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
#From https://en.wikipedia.org/wiki/FASTQ_format
... |
"""
========================================================================
Bits.py
========================================================================
Pure-Python implementation of fixed-bitwidth data type.
Author : Shunning Jiang
Date : Oct 31, 2017
"""
class Bits:
__slots__ = ( "nbits", "value" )
def... |
# -*- coding: utf-8 -*-
'''
File name: code\combined_volume_of_cuboids\sol_212.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #212 :: Combined Volume of Cuboids
#
# For more information see:
# https://projecteuler.net/problem=212
# Prob... |
"""This module contains exceptions that power Injectify."""
class ClassFoundException(Exception):
pass
|
a = 1
b = 0
c = 128
d = 0
f = 836 + c #964
if a == 1:
c = 10550400
f = f + c #10551364
a = 0
for b in range(1, f+1):
if (f % b) == 0:
a += b
print(a) |
class GoodreadsClientException(Exception):
pass
class NetworkError(GoodreadsClientException):
pass
|
def show_words(**kwargs):
print(kwargs['pies'], kwargs['kot'])
for key, value in kwargs.items():
print(key + "->" + value)
show_words(pies="Dog", kot="Cat", sowa="Owl", mysz="Mouse")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Shashi Bhushan (sbhushan1 @ outlook dot com)'
class GameObject(object):
pass
|
n1 = int(input('Digite um número para ver sua tabuada: '))
print('-'*12)
print(f'{n1} X 1 = {n1 * 1} \n{n1} X 2 = {n1 * 2} \n{n1} X 3 = {n1 * 3} \n{n1} x 4 = {n1 * 4} ')
print(f'{n1} X 5 = {n1 * 5} \n{n1} X 6 = {n1 * 6} \n{n1} X 7 = {n1 * 7} \n{n1} X 8 = {n1 * 8}')
print(f'{n1} X 9 = {n1 * 9} \n{n1} X 10 =... |
debian_os = ['debian', 'ubuntu']
rhel_os = ['redhat', 'centos']
def test_distribution(host):
assert host.system_info.distribution.lower() in debian_os + rhel_os
def test_conf_dir(host):
f = host.file('/etc/pgbouncer_exporter')
assert f.exists
assert f.is_directory
def test_log_dir(host):
f = ... |
#!/usr/bin/env python3
"""
linear_search.py - Linear Search Implementation
Author: Hoanh An (hoanhan@bennington.edu)
Date: 10/18/2017
"""
def linear_search(arr, x):
for i in arr:
if i == x:
return True
return False
if __name__ == '__main__':
test_array = [1, 2, 3]
if linear_se... |
a = 1
b = 2
c = 3
d = 4
e = 5
f = 6 |
# --- Day 15: Rambunctious Recitation ---
# You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm, all direct flights have been cancelled, but a route is available to get around the storm. You take it.
# While you wait for your flight, you decide to check in with the Elve... |
# -*- coding: utf-8 -*-
# in VTK, the header file is the same as the classname
def get_include_file(classname,filename):
incfile = '#include "{0}"'.format(filename)
#print "including class {0} from file {1}".format(classname,incfile)
if classname.startswith("itk::DefaultConvertPixelTraits"):
incfile... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.