content
stringlengths 7
1.05M
|
---|
# A simple color module I wrote for my projects
# Feel free to copy this script and use it for your own projects!
class Color:
purple = '\033[95m'
blue = '\033[94m'
green = '\033[92m'
yellow = '\033[93m'
red = '\033[91m'
white = '\033[0m'
class textType:
bold = '\033[1m'
underline = '\033[4m'
|
# LC 1268
class TrieNode:
def __init__(self):
self.next = dict()
self.words = list()
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
# node = node.next.setdefault(char, TrieNode())
if char not in node.next:
node.next[char] = TrieNode()
node = node.next[char]
if len(node.words) < 3:
node.words.append(word)
def getSuggestionsFor(self, word):
ans = []
node = self.root
for char in word:
if node:
node = node.next.get(char, None)
if node:
ans.append(node.words)
else:
ans.append([])
return ans
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
trie = Trie()
for word in products:
trie.insert(word)
return trie.getSuggestionsFor(searchWord)
|
x = int(input())
y = int(input())
print(y % x)
|
# number_list = [str(x) for x in range(1000 +1)]
# number_list_str = ''.join(number_list)
# print(number_list_str.count('1'))
# print(''.join([str(x) for x in range(1000 +1)]).count('1'))
# format(n, '+')
# format(n, '-')
# format(n, ',') 천단위마다 콤마
# format(n, '_') 천단위마다 언더바
# format(n, 'b') 바이너리로
# format(n, '%') 퍼센트 붙여줌
num1 = 5
print(format(num1, 'b'))
|
mediaidade = 0
maioridade = 0
nomevelho = ''
totmulher = 0
for p in range(1, 5):
print('----{}ª pessoa----'.format(p))
nome = str(input('Digite seu nome: ')) .strip()
idade = int(input('Digite sua idade: '))
sexo = str(input('Sexo[M/F]: ')) .strip()
mediaidade += idade
if p == 1 and sexo in 'Mn':
maioridade = idade
nomevelho = nome
if idade > maioridade and sexo in 'Mm':
maioridade = idade
nomevelho = nome
if idade < 20 and sexo in 'fF':
totmulher += 1
mediaidade = mediaidade / 4
print('A média de idade do grupo é de {} anos.'.format(mediaidade))
print('O homen mais velho tem {} e se chama {}.'.format(maioridade, nomevelho))
print('O total de mulheres com menos de 20 anos são {}.'.format(totmulher))
|
class OutputBase:
def __init__(self):
self.output_buffer = []
def __call__(self, obj):
self.write(obj)
def write(self, obj):
pass
def clear(self):
self.output_buffer = []
|
#!/usr/bin/python
# https://po.kattis.com/problems/vandrarhem
class Bed(object):
def __init__(self, price, available_beds):
""" Constructor for Bed """
self.price = int(price)
self.available_beds = int(available_beds)
def is_full(self):
""" Checks if there is a bed of this type available """
return self.available_beds == 0
def book(self):
""" Books a bed of this type """
if not self.is_full():
self.available_beds -= 1
def main():
with open("infile.txt") as f:
infile = f.read().splitlines()
firstline = infile.pop(0)
attendees = int(firstline.split(" ")[0])
bedtype_count = int(firstline.split(" ")[1])
# The total cost for booking a bed for every attendee
total_cost = 0
bedtypes = []
for i in range(bedtype_count):
line = infile[i]
tokens = line.split(" ")
price = tokens[0]
available = tokens[1]
bedtypes.append(Bed(price, available))
# Sort the bedtypes by their price
bedtypes.sort(key=lambda bed: bed.price)
bed_type_counter = 0
# Book a bed for every attendee
while attendees > 0:
current_bed_type = bedtypes[bed_type_counter]
current_bed_price = current_bed_type.price
if current_bed_type.available_beds == 0:
bed_type_counter += 1
continue
else:
current_bed_type.book()
total_cost += current_bed_price
attendees -= 1
print(total_cost)
if __name__ == '__main__':
main()
|
DEBUG = False
# if False, "0" will be used
ENABLE_STRING_SEEDING = True
# use headless evaluator
HEADLESS = False
# === Emulator ===
DEVICE_NUM = 1
AVD_BOOT_DELAY = 30
AVD_SERIES = "api19_"
EVAL_TIMEOUT = 120
# if run on Mac OS, use "gtimeout"
TIMEOUT_CMD = "timeout"
# === Env. Paths ===
# path should end with a '/'
ANDROID_HOME = '/home/shadeimi/Software/android-sdk-linux/'
# the path of sapienz folder
WORKING_DIR = '/home/shadeimi/Software/eclipseWorkspace/sapienz/'
# === GA parameters ===
SEQUENCE_LENGTH_MIN = 20
SEQUENCE_LENGTH_MAX = 500
SUITE_SIZE = 5
POPULATION_SIZE = 50
OFFSPRING_SIZE = 50
GENERATION = 100
# Crossover probability
CXPB = 0.7
# Mutation probability
MUTPB = 0.3
# === Only for main_multi ===
# start from the ith apk
APK_OFFSET = 0
APK_DIR = ""
REPEATED_RESULTS_DIR = ""
REPEATED_RUNS = 20
# === MOTIFCORE script ===
# for initial population
MOTIFCORE_SCRIPT_PATH = '/mnt/sdcard/motifcore.script'
# header for evolved scripts
MOTIFCORE_SCRIPT_HEADER = 'type= raw events\ncount= -1\nspeed= 1.0\nstart data >>\n'
|
""" Remove metainfo files in folders, only if they're associated with torrents registered in Transmission.
Usage:
clutchless prune folder [--dry-run] <metainfo> ...
Arguments:
<metainfo> ... Folders to search for metainfo files to remove.
Options:
--dry-run Doesn't delete any files, only outputs what would be done.
"""
|
class InvalidDataFrameException(Exception):
pass
class InvalidCheckTypeException(Exception):
pass
|
#!/usr/bin/python
# vim: set ts=4:
# vim: set shiftwidth=4:
# vim: set expandtab:
#-------------------------------------------------------------------------------
#---> Elections supported
#-------------------------------------------------------------------------------
# election id - base_url - election type - year - has special polling stations tuples for each election
elections = [
('20150920', 'http://ekloges.ypes.gr/current', 'v', 2015, True),
('20150125', 'http://ekloges-prev.singularlogic.eu/v2015a', 'v', 2015, True),
('20150705', 'http://ekloges-prev.singularlogic.eu/r2015', 'e', 2015, True),
('20140525', 'http://ekloges-prev.singularlogic.eu/may2014', 'e', 2014, False),
('20120617', 'http://ekloges-prev.singularlogic.eu/v2012b', 'v', 2012, True),
('20120506', 'http://ekloges-prev.singularlogic.eu/v2012a', 'v', 2012, True)]
# chosen election
_ELECTION = 5
election_str = elections[_ELECTION][0]
base_url = elections[_ELECTION][1]
election_type = elections[_ELECTION][2]
year = elections[_ELECTION][3]
has_special = elections[_ELECTION][4]
#-------------------------------------------------------------------------------
#---> Json files urls
#-------------------------------------------------------------------------------
def get_url(lvl, idx, dynamic):
content_type = 'dyn' if dynamic else 'stat'
if year > 2012:
first_part = '{0}/{1}/{2}'.format(base_url, content_type, election_type)
else:
first_part = '{0}/{1}'.format(base_url, content_type)
if lvl == 'epik' or lvl == 'top':
return '{0}/{1}'.format(first_part, 'statics.js')
elif lvl == 'ep' or lvl == 'district':
return '{0}/ep_{1}.js'.format(first_part, idx)
elif lvl == 'den' or lvl == 'munical_unit':
return '{0}/den_{1}.js'.format(first_part, idx)
elif lvl == 'special':
return '{0}/special_{1}.js'.format(first_part, idx)
elif lvl == 'tm' or lvl == 'pstation':
if year > 2012:
return '{0}/{1}/tm_{2}.js'.format(first_part, int(idx / 10000), idx)
else:
return '{0}/tm_{1}.js'.format(first_part, idx)
else:
raise Exception
#-------------------------------------------------------------------------------
#---> Top level file structure
#-------------------------------------------------------------------------------
if election_type == 'v' and year >= 2015:
lvl_labels = ['epik', 'snom', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population'],
['id', 'name', 'pstation_cnt'],
['id', 'name', 'pstation_cnt', 'alt_id', 'mps', 'unknown'],
['id', 'name', 'pstation_cnt', 'upper_id'],
['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour', 'in_parliament']
elif election_type == 'v' and year >= 2012:
lvl_labels = ['epik', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population'],
['id', 'name', 'pstation_cnt', 'alt_id', 'mps'],
['id', 'name', 'pstation_cnt', 'upper_id'],
['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour']
elif election_type == 'e':
lvl_labels = ['epik', 'snom', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population', 'mps', 'unknown'],
['id', 'upper_id', 'name', 'pstation_cnt'],
['id', 'name', 'pstation_cnt', 'alt_id', 'upper_id'],
['id', 'name', 'pstation_cnt', 'upper_id'],
['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour', 'in_parliament']
#-------------------------------------------------------------------------------
#---> Translations
#-------------------------------------------------------------------------------
translations = dict([
('NumTm', 'pstation_cnt'),
('Gramenoi', 'registered'),
('Egkyra', 'valid'),
('Akyra', 'invalid'),
('Leyka', 'blank')])
#-------------------------------------------------------------------------------
#---> Top level access helpers
#-------------------------------------------------------------------------------
def get(data_lst, lvl, field):
structure = lvl_structs[lvl_labels.index(lvl)]
try:
idx = structure.index(field)
except:
if field == 'upper_id':
return -1
else:
raise ValueError
return data_lst[idx]
def get_parties_list(data):
return data[parties_label]
def get_party_field(data_lst, field):
idx = parties_struct.index(field)
return data_lst[idx]
def has_special_list():
if election_str == '20120506':
return False
return True
|
def ortho_locs(row, col):
offsets = [(-1,0), (0,-1), (0,1), (1,0)]
for row_offset, col_offset in offsets:
yield row + row_offset, col + col_offset
def adj_locs(row, col):
offsets = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]
for row_offset, col_offset in offsets:
yield row + row_offset, col + col_offset
class Grid:
def __init__(self, grid):
self.grid = grid
self.rows = len(grid)
self.cols = len(grid[0])
def __getitem__(self, row):
return self.grid[row]
def __iter__(self):
return self.grid.__iter__()
def valid_loc(self, row, col):
return row >= 0 and row < self.rows and col >= 0 and col < self.cols
def ortho_locs(self, row, col):
for ortho_row, ortho_col in ortho_locs(row, col):
if self.valid_loc(ortho_row, ortho_col):
yield ortho_row, ortho_col
def adj_locs(self, row, col):
for adj_row, adj_col in adj_locs(row, col):
if self.valid_loc(adj_row, adj_col):
yield adj_row, adj_col
def make_mirror(self, value):
return [[value for _ in row] for row in self.grid]
def build_grid(rows, cols, value):
return Grid([[value for _ in range(cols)] for _ in range(rows)])
def print_grid(grid, formatter=lambda v: v):
for row in grid:
for col in row:
print(formatter(col), end="")
print("")
|
def GetByTitle(type, title):
type = type.upper()
if type != 'ANIME' and type != 'MANGA':
return False
variables = {
'type' : type,
'search' : title
}
return variables
|
class BaseModel(object):
@classmethod
def connect(cls):
"""
Args:
None
Returns:
None
"""
raise NotImplementedError('model.connect not implemented!')
@classmethod
def create(cls, data):
"""
Args:
data(dict)
Returns:
model_vo(object)
"""
raise NotImplementedError('model.create not implemented!')
def update(self, data):
"""
Args:
data(dict)
Returns:
model_vo(object)
"""
raise NotImplementedError('model.update not implemented!')
def delete(self):
"""
Args:
None
Returns:
None
"""
raise NotImplementedError('model.delete not implemented!')
def terminate(self):
"""
Args:
None
Returns:
None
"""
raise NotImplementedError('model.terminate not implemented!')
@classmethod
def get(cls, **conditions):
"""
Args:
conditions(kwargs)
- key(str) : value(any)
Returns:
model_vo(object)
"""
raise NotImplementedError('model.get not implemented!')
@classmethod
def filter(cls, **conditions):
"""
Args:
conditions(kwargs)
- key(str) : value(any)
Returns:
model_vos(list)
"""
raise NotImplementedError('model.filter not implemented!')
def to_dict(self):
"""
Args:
None
Returns:
model_data(dict)
"""
raise NotImplementedError('model.to_dict not implemented!')
@classmethod
def query(cls, **query):
"""
Args:
query(kwargs)
- filter(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in'
},
...
]
- filter_or(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in'
},
...
]
- sort(dict)
{
'key' : 'field(str)',
'desc' : True | False
}
- page(dict)
{
'start': (int),
'limit' : (int)
}
- distinct(str): 'field'
- only(list): ['field1', 'field2', '...']
- exclude(list): ['field1', 'field2', '...']
- minimal(bool)
- count_only(bool)
Returns:
model_vos(list)
total_count(int)
"""
raise NotImplementedError('model.query not implemented!')
@classmethod
def stat(cls, **query):
"""
Args:
query(kwargs)
- filter(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in
datetime_lt | datetime_lte | datetime_gt | datetime_gte | timediff_lt | timediff_lte
timediff_gt | timediff_gte'
},
...
]
- filter_or(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in
datetime_lt | datetime_lte | datetime_gt | datetime_gte | timediff_lt | timediff_lte
timediff_gt | timediff_gte'
},
...
]
- aggregate(dict)
{
'unwind': [
{
'path': 'key path(str)'
}
],
'group': {
'keys': [
{
'key': 'field(str)',
'name': 'alias name(str)'
},
...
],
'fields': [
{
'key': 'field(str)',
'name': 'alias name(str)',
'operator': 'count | sum | avg | max | min | size | add_to_set | merge_objects'
},
...
]
}
'count': {
'name': 'alias name(str)'
}
}
- sort(dict)
{
'name' : 'field(str)',
'desc' : True | False
}
- page(dict)
{
'start': (int),
'limit' : (int)
}
Returns:
values(list)
"""
raise NotImplementedError('model.stat not implemented!')
|
def queryValue(cur, sql, fields=None, error=None) :
row = queryRow(cur, sql, fields, error);
if row is None : return None
return row[0]
def queryRow(cur, sql, fields=None, error=None) :
row = doQuery(cur, sql, fields)
try:
row = cur.fetchone()
return row
except Exception as e:
if error:
print(error, e)
else :
print(e)
return None
def doQuery(cur, sql, fields=None) :
row = cur.execute(sql, fields)
return row
|
HEADERS_FOR_HTTP_GET = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
AGE_CATEGORIES = [
'JM10', 'JW10',
'JM11-14', 'JW11-14',
'JM15-17', 'JW15-17',
'SM18-19', 'SW18-19',
'SM20-24', 'SW20-24',
'SM25-29', 'SW25-29',
'SM30-34', 'SW30-34',
'VM35-39', 'VW35-39',
'VM40-44', 'VW40-44',
'VM45-49', 'VW45-49',
'VM50-54', 'VW50-54',
'VM55-59', 'VW55-59',
'VM60-64', 'VW60-64',
'VM65-69', 'VW65-69',
'VM70-74', 'VW70-74',
'VM75-79', 'VW75-79',
'VM---', 'VW---'
]
|
#
# PySNMP MIB module MICOM-IFDNA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MICOM-IFDNA-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:03 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:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
micom_oscar, = mibBuilder.importSymbols("MICOM-OSCAR-MIB", "micom-oscar")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter64, NotificationType, iso, Bits, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, Unsigned32, TimeTicks, Integer32, MibIdentifier, Gauge32, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "NotificationType", "iso", "Bits", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "Unsigned32", "TimeTicks", "Integer32", "MibIdentifier", "Gauge32", "ModuleIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
micom_ifdna = MibIdentifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18)).setLabel("micom-ifdna")
ifDna = MibIdentifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1))
ifNvDna = MibIdentifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2))
mcmIfDnaTable = MibTable((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1), )
if mibBuilder.loadTexts: mcmIfDnaTable.setStatus('mandatory')
mcmIfDnaEntry = MibTableRow((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1), ).setIndexNames((0, "MICOM-IFDNA-MIB", "mcmIfDnaIfIndex"), (0, "MICOM-IFDNA-MIB", "mcmIfDnaType"))
if mibBuilder.loadTexts: mcmIfDnaEntry.setStatus('mandatory')
mcmIfDnaIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mcmIfDnaIfIndex.setStatus('mandatory')
mcmIfDnaType = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("provisioned", 1), ("learnt", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mcmIfDnaType.setStatus('mandatory')
mcmIfDNADigits = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 34))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mcmIfDNADigits.setStatus('mandatory')
mcmIfDnaStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("valid", 1), ("active", 2), ("invalid", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mcmIfDnaStatus.setStatus('mandatory')
nvmIfDnaTable = MibTable((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1), )
if mibBuilder.loadTexts: nvmIfDnaTable.setStatus('mandatory')
nvmIfDnaEntry = MibTableRow((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1), ).setIndexNames((0, "MICOM-IFDNA-MIB", "nvmIfDnaIfIndex"), (0, "MICOM-IFDNA-MIB", "nvmIfDnaType"))
if mibBuilder.loadTexts: nvmIfDnaEntry.setStatus('mandatory')
nvmIfDnaIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nvmIfDnaIfIndex.setStatus('mandatory')
nvmIfDnaType = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("provisioned", 1), ("learnt", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nvmIfDnaType.setStatus('mandatory')
nvmIfDNADigits = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 34))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nvmIfDNADigits.setStatus('mandatory')
nvmIfDnaStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("valid", 1), ("active", 2), ("invalid", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nvmIfDnaStatus.setStatus('mandatory')
mibBuilder.exportSymbols("MICOM-IFDNA-MIB", nvmIfDnaStatus=nvmIfDnaStatus, mcmIfDnaType=mcmIfDnaType, mcmIfDnaTable=mcmIfDnaTable, mcmIfDnaEntry=mcmIfDnaEntry, micom_ifdna=micom_ifdna, mcmIfDnaIfIndex=mcmIfDnaIfIndex, ifNvDna=ifNvDna, mcmIfDnaStatus=mcmIfDnaStatus, nvmIfDnaTable=nvmIfDnaTable, nvmIfDnaEntry=nvmIfDnaEntry, ifDna=ifDna, nvmIfDnaType=nvmIfDnaType, nvmIfDNADigits=nvmIfDNADigits, mcmIfDNADigits=mcmIfDNADigits, nvmIfDnaIfIndex=nvmIfDnaIfIndex)
|
a = 5
b = 3
def timeit_1():
print(a + b)
c = 8
def timeit_2():
print(a + b + c)
|
def some_but_not_all(seq, pred):
has = [False,False]
for it in seq:
has[bool(pred(it))] = True
# exit as fast as possible
if all(has):
return True
# sequennce is scanned with only True or False predictions.
return False
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' A short description of this file
A slightly longer description of this file
can be found under the shorter desription.
'''
def get_code():
''' Get mysterious code... '''
return '100111011111101010110110101100'
|
class StdoutMock():
def __init__(self, *args, **kwargs):
self.content = ''
def write(self, content):
self.content += content
def read(self):
return self.content
def __str__(self):
return self.read()
|
"""
uci_bootcamp_2021/examples/functions.py
examples on how to use functions
"""
def y(x, slope, initial_offset):
"""
This is a docstring. it is a piece of living documentation that is attached to the function.
Note: different companies have different styles for docstrings, and this one doesn't fit any of them!
this is just a small example of how to write a function in python, using simple math for demonstration.
"""
return slope * x + initial_offset
def y(x: float, slope: float, initial_offset: float = 0) -> float:
"""Same function as above, but this time with type annotations!"""
return slope * x + initial_offset
|
def flatten(list):
final = []
for item in list:
final += item
return final
def flattenN(list):
if type(list[0]) != type([]):
return list
return flattenN(flatten(list))
list = [[[1,2],[3,4]],[[3,4],["hello","there"]]]
result = flattenN(list)
print(result)
|
def imp_notas(quantidade, valor):
return '{:.0f} nota(s) de R$ {:.2f}'.format(quantidade, valor)
def imp_moedas(quantidade, valor):
return '{:.0f} moeda(s) de R$ {:.2f}'.format(quantidade, valor)
numero = float(input())
numero += 0.0001
if numero >= 0 or numero <= 1000000.00:
notas = [100.00, 50.00, 20.00, 10.00, 5.00, 2.00]
moedas = [1.00, 0.50, 0.25, 0.10, 0.05, 0.01]
dcp_notas = []
dcp_moedas = []
for nota in notas:
dcp_notas.append( (numero // nota) )
numero = numero - ( ( numero // nota ) * nota )
for moeda in moedas:
dcp_moedas.append( (numero // moeda) )
numero = numero - ( ( numero // moeda ) * moeda )
print('NOTAS:')
for i in range(6):
print(imp_notas(dcp_notas[i], notas[i]))
print('MOEDAS:')
for i in range(6):
print(imp_moedas(dcp_moedas[i], moedas[i]))
|
class Wizard:
def __init__(self, app):
self.app = app
def skip_wizard(self):
driver = self.app.driver
driver.find_element_by_class_name("skip").click()
|
def linked_sort(a_to_sort, a_linked, key=str):
res = sorted(zip(a_to_sort, a_linked), key=key)
for i in range(len(a_to_sort)):
a_to_sort[i], a_linked[i] = res[i]
return a_to_sort
|
# -*- coding: utf-8 -*-
# :copyright: (c) 2011 - 2015 by Arezqui Belaid.
# :license: MPL 2.0, see COPYING for more details.
__version__ = '1.0.3'
__author__ = "Arezqui Belaid"
__contact__ = "[email protected]"
__homepage__ = "http://www.star2billing.org"
__docformat__ = "restructuredtext"
|
def print_stats(num_broke, num_profitors, sample_size, profits, loses, type):
broke_percent = (num_broke / sample_size) * 100
profit_percent = (num_profitors / sample_size) * 100
try:
survive_profit_percent = (num_profitors / (sample_size - num_broke)) * 100
except ZeroDivisionError:
survive_profit_percent = 0
try:
avg_profit = sum(profits) / len(profits)
except ZeroDivisionError:
avg_profit = 0
try:
avg_loses = sum(loses) / len(loses)
except ZeroDivisionError:
avg_loses = 0
print(f'\n{type} Percentage Broke: {broke_percent}%')
print(f'{type} Percentage Profited: {profit_percent}%')
print(f'{type} Percentage Survivors Profited: {survive_profit_percent}%')
print(f'{type} Avergage Profit: {avg_profit}')
print(f'{type} Avergage Loses: {avg_loses}')
print(f' {type} Expected Profit: {avg_profit * (profit_percent/ 100)}')
print(f' {type} Expected Loss: {avg_loses * (1 - (profit_percent / 100))}')
|
class Similarity:
def __init__(self, path, score):
self.path = path
self.score = score
@classmethod
def from_dict(cls, adict):
return cls(
path=adict['path'],
score=adict['score'],
)
def to_dict(self):
return {
'path': self.path,
'score': self.score
}
def __eq__(self, other):
return self.to_dict() == other.to_dict()
|
"""Aluguel por KM e dia"""
# Uso de operadores aritmeticos
dia = float(input('Quantos dias passou com o carro: '))
km = float(input('Quantos Km você andou com o carro: '))
pdia = dia * 60 # Cobrança p/dia
pkm = km * 0.15 # cobrança po km
pfim = pdia + pkm # Soma final
print('Você passou {} dias com o carro e rodou\n'
'{}Km com ele, o preço final a ser pago é de: R${}'.format(dia, km, pfim))
|
EFFICIENTDET = {
'efficientdet-d0': {'input_size': 512,
'backbone': 'B0',
'W_bifpn': 64,
'D_bifpn': 2,
'D_class': 3},
'efficientdet-d1': {'input_size': 640,
'backbone': 'B1',
'W_bifpn': 88,
'D_bifpn': 3,
'D_class': 3},
'efficientdet-d2': {'input_size': 768,
'backbone': 'B2',
'W_bifpn': 112,
'D_bifpn': 4,
'D_class': 3},
'efficientdet-d3': {'input_size': 896,
'backbone': 'B3',
'W_bifpn': 160,
'D_bifpn': 5,
'D_class': 4},
'efficientdet-d4': {'input_size': 1024,
'backbone': 'B4',
'W_bifpn': 224,
'D_bifpn': 6,
'D_class': 4},
'efficientdet-d5': {'input_size': 1280,
'backbone': 'B5',
'W_bifpn': 288,
'D_bifpn': 7,
'D_class': 4},
'efficientdet-d6': {'input_size': 1408,
'backbone': 'B6',
'W_bifpn': 384,
'D_bifpn': 8,
'D_class': 5},
'efficientdet-d7': {'input_size': 1636,
'backbone': 'B6',
'W_bifpn': 384,
'D_bifpn': 8,
'D_class': 5},
}
|
# Refaça o DESAFIO 9, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.
n = int(input('Quer a tabuada de que número? '))
print(f'{"=" * 30}')
print(f'A tabuada do número {n} é: ')
print(f'{"=" * 30}')
for i in range(0, 11):
print(f'{n} X {i} = {n * i}')
print(f'{"=" * 30}')
|
month = int(input("Enter month: "))
year = int(input("Enter year: "))
if month == 1:
monthName = "January"
numberOfDaysInMonth = 31
elif month == 2:
monthName = "February"
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
numberOfDaysInMonth = 29
else:
numberOfDaysInMonth = 28
elif month == 3:
monthName = "March"
numberOfDaysInMonth = 31
elif month == 4:
monthName = "April"
numberOfDaysInMonth = 30
elif month == 5:
monthName = "May"
numberOfDaysInMonth = 31
elif month == 6:
monthName = "June"
numberOfDaysInMonth = 30
elif month == 7:
monthName = "July"
numberOfDaysInMonth = 31
elif month == 8:
monthName = "August"
numberOfDaysInMonth = 31
elif month == 9:
monthName = "September"
numberOfDaysInMonth = 30
elif month == 10:
monthName = "October"
numberOfDaysInMonth = 31
elif month == 11:
monthName = "November"
numberOfDaysInMonth = 30
else:
monthName = "December"
numberOfDaysInMonth = 31
print(monthName, year, "has", numberOfDaysInMonth, "days")
|
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
# print('A soma vale {}'.format(n1 + n2))
s = n1 + n2
sub = n1 - n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
print('A soma é {}, a subtração é {}, a multiplicação é {} e a divisão é {}'.format(s, sub, m, d))
print('A divisão inteira é {} e a potência é {}'.format(di, e))
# para formatar utilizase dentro das {} a formtação, ex.: 3 casas decimais {:.3f}
|
'''
Reversed
OBS: Não confunda com a função reserve() que estudamos nas listas.
Afunção reverse() só funciona em listas.
Já a função reversed() funciona com qualquer iterável.
Sua função é inverter o iterável.
A função reversed() retorna um iterável chamado List Reverse Iterator
'''
# Exemplos
lista = [1, 2, 4, 5, 6]
res = reversed(lista)
print(res)
print(type(res))
# Podemos converter o elemento retornado para uma Lista, Tupla ou conjunto
# Lista
print(list(reversed(lista)))
# Tupla
print(tuple(reversed(lista)))
# OBs: Em conjuntos, não definimos a ordem dos elementos
# Conjunto (Set)
print(set(reversed(lista)))
# Podemso iterar sobre o reversed
for letra in reversed('Geek University'):
print(letra, end='')
# Podemos fazer o mesmo sem o uso do for
print(''.join(list(reversed('Geek University'))))
# Já vimos como fazer isso mais fdacil com o slice
print('Geek University'[::-1])
|
# Problem: Given as an input two strings, X = x_{1} x_{2}... x_{m}, and Y = y_{1} y_{2}... y_{m}, output the alignment of the strings, character by character,
# so that the net penalty is minimised.
gap_penalty = 3 # cost of gap
mismatch_penalty = 2 # cost of mismatch
memoScore = {}
memoSequence = {}
def sequenceAlignment(seq1, seq2):
if (seq1,seq2) in memoScore:return memoScore[(seq1,seq2)] # memoization
if seq1 == "" and seq2 == "" : # base case
memoSequence[(seq1,seq2)] = ["",""]
return 0
elif seq1 == "" or seq2== "" :
maxim = max(len(seq1),len(seq2))
memoSequence[(seq1,seq2)] = [seq1.ljust(maxim,"_"), seq2.ljust(maxim,"_")]
return gap_penalty*maxim
penalty = 0 if seq1[0] == seq2[0] else mismatch_penalty
nogap = sequenceAlignment( seq1[1:],seq2[1:] ) + penalty # cost of match/mistmatch
seq1gap = sequenceAlignment( seq1,seq2[1:] ) + gap_penalty # cost of gap in sequence 1
seq2gap = sequenceAlignment( seq1[1:],seq2 ) + gap_penalty # cost of gap in sequence 2
if seq1gap < nogap and seq1gap <= seq2gap:
result = seq1gap
newSeq1 = "_" + memoSequence[(seq1,seq2[1:])][0]
newSeq2 = seq2[0] + memoSequence[(seq1,seq2[1:])][1]
elif seq2gap < nogap and seq2gap <= seq1gap:
result = seq2gap
newSeq1 = seq1[0] + memoSequence[(seq1[1:],seq2)][0]
newSeq2 = "_" + memoSequence[(seq1[1:],seq2)][1]
else:
result = nogap
newSeq1 = seq1[0] + memoSequence[(seq1[1:],seq2[1:])][0]
newSeq2 = seq2[0] + memoSequence[(seq1[1:],seq2[1:])][1]
memoScore[(seq1,seq2)] = result
memoSequence[(seq1,seq2)] = [newSeq1,newSeq2]
return result
# Testing
sequence1 = "AGGGCT"
sequence2 = "AGGCA"
sequenceAlignment(sequence1,sequence2)
finalsequence = memoSequence[(sequence1,sequence2)]
print("First sequence : ", finalsequence[0])
print("Second sequence : ", finalsequence[1])
print("Min penalty : ",memoScore[(sequence1,sequence2)] )
|
A = int(input())
B = set("aeiou")
for i in range(A):
S = input()
count = 0
for j in range(len(S)):
if S[j] in B:
count += 1
print(count)
|
# Configuration for running the Avalon Music Server under Gunicorn
# http://docs.gunicorn.org
# Note that this configuration omits a bunch of features that Gunicorn
# has (such as running as a daemon, changing users, error and access
# logging) because it is designed to be used when running Gunicorn
# with supervisord and a separate public facing web server (such as
# Nginx).
# Bind the server to an address only accessible locally. We'll be
# running Nginx which will proxy to Gunicorn and act as the public-
# facing web server.
bind = 'localhost:8000'
# Use three workers in addition to the master process. Since the Avalon
# Music Server is largely CPU bound, you can increase the number of
# request that can be handled by increasing this number (up to a point!).
# The Gunicorn docs recommend 2N + 1 where N is the number of CPUs you
# have.
workers = 3
# Make sure to load the application only in the main process before
# spawning the worker processes. This will save us memory when using
# multiple worker processes since the OS will be be able to take advantage
# of copy-on-write optimizations.
preload_app = True
|
"""
Generator expressions are lazily evaluated, which means that they generate and
return each value only when the generator is iterated. This is often useful when
ITERATING THROUGH LARGE DATEBASES, avoiding the need to create a duplicate of
the dataset in memory.
"""
for square in (x**2 for x in range(100)):
print(square)
"""
Another common use case is to avoid iterating over an entire iterable if doing
so is not necessary.
"""
|
#check if number is prime or not
n = int(input("enter a number "))
for i in range(2, n):
if n % i == 0:
print("not a prime number")
break
else:
print("it is a prime number")
|
#
# PySNMP MIB module EXTREME-EAPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-BASE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:07:14 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:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection")
extremeAgent, = mibBuilder.importSymbols("EXTREME-BASE-MIB", "extremeAgent")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter64, IpAddress, Integer32, Gauge32, Counter32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, NotificationType, ModuleIdentity, ObjectIdentity, TimeTicks, Bits, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "IpAddress", "Integer32", "Gauge32", "Counter32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "NotificationType", "ModuleIdentity", "ObjectIdentity", "TimeTicks", "Bits", "Unsigned32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
extremeEaps = ModuleIdentity((1, 3, 6, 1, 4, 1, 1916, 1, 18))
if mibBuilder.loadTexts: extremeEaps.setLastUpdated('0007240000Z')
if mibBuilder.loadTexts: extremeEaps.setOrganization('Extreme Networks, Inc.')
if mibBuilder.loadTexts: extremeEaps.setContactInfo('www.extremenetworks.com')
if mibBuilder.loadTexts: extremeEaps.setDescription('Ethernet Automatic Protection Switching information')
extremeEapsTable = MibTable((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1), )
if mibBuilder.loadTexts: extremeEapsTable.setStatus('current')
if mibBuilder.loadTexts: extremeEapsTable.setDescription('This table contains EAPS information about all EAPS domains on this device.')
extremeEapsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1), ).setIndexNames((0, "EXTREME-EAPS-MIB", "extremeEapsName"))
if mibBuilder.loadTexts: extremeEapsEntry.setStatus('current')
if mibBuilder.loadTexts: extremeEapsEntry.setDescription('An individual entry of this table contains EAPS information related to that EAPS domain.')
extremeEapsName = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: extremeEapsName.setStatus('current')
if mibBuilder.loadTexts: extremeEapsName.setDescription('The EAPS domain name.')
extremeEapsMode = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("invalid", 0), ("master", 1), ("transit", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: extremeEapsMode.setStatus('current')
if mibBuilder.loadTexts: extremeEapsMode.setDescription('This indicates the mode of the EAPS domain.')
extremeEapsState = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("idle", 0), ("complete", 1), ("failed", 2), ("linksup", 3), ("linkdown", 4), ("preforwarding", 5), ("init", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: extremeEapsState.setStatus('current')
if mibBuilder.loadTexts: extremeEapsState.setDescription('This indicates the current EAPS state of this EAPS domain.')
extremeEapsPrevState = MibScalar((1, 3, 6, 1, 4, 1, 1916, 1, 18, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("idle", 0), ("complete", 1), ("failed", 2), ("linksup", 3), ("linkdown", 4), ("preforwarding", 5), ("init", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: extremeEapsPrevState.setStatus('current')
if mibBuilder.loadTexts: extremeEapsPrevState.setDescription('This indicates the previous EAPS state of this EAPS domain. Used in state change traps information.')
mibBuilder.exportSymbols("EXTREME-EAPS-MIB", extremeEapsEntry=extremeEapsEntry, extremeEapsMode=extremeEapsMode, PYSNMP_MODULE_ID=extremeEaps, extremeEapsState=extremeEapsState, extremeEapsName=extremeEapsName, extremeEapsPrevState=extremeEapsPrevState, extremeEaps=extremeEaps, extremeEapsTable=extremeEapsTable)
|
# -*- coding: utf-8 -*-
operation = input()
total = 0
for i in range(144):
N = float(input())
line = i // 12
if (i > (13 * line)):
total += N
answer = total if (operation == 'S') else (total / 66)
print("%.1f" % answer)
|
# -*- coding: utf-8 -*-
"""Top-level package for light_tester."""
__author__ = """Gary Cremins"""
__email__ = '[email protected]'
__version__ = '0.1.0'
|
S = [3, 1, 3, 1]
N = len(S)-1
big_val = 1 << 62 # left bitwise shift is equivalent to raising 2 to the power of the positions shifted. so, big_val = 2 ^ 62.
A = [[big_val for i in range(N+1)] for j in range(N+1)]
def matrix_chain_cost(i, j):
global A
if i == j:
return 0
if A[i][j] != big_val:
return A[i][j]
for k in range(i, j):
A[i][j] = min(A[i][j], matrix_chain_cost(i, k) + matrix_chain_cost(k+1, j) + S[i-1] * S[k] * S[j])
return A[i][j]
print("Minimum cost of multiplication is", matrix_chain_cost(1, N))
|
# Function: flips a pattern by mirror image
# Input:
# string - string pattern
# direction - flip horizontally or vertically
# Ouput: modified string pattern
def flip(st, direction):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
st_out = ''
if (direction == 'Flip Horizontally'):
row_strings = row_strings[::-1]
for row in row_strings:
st_out += row + '\n'
else:
for row in row_strings:
st_out += row[::-1] + '\n'
return(st_out)
# Function: reflects pattern vertically
# Input:
# st - string pattern
# space - positive integer value, gap between original pattern and reflected pattern
# direction - 'Reflect Left' or 'Reflect Right', direction to perform vertical reflection
# Output:
# modified string pattern
def reflect_v(st, space, direction):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
space_st = ""
if (direction == "Reflect Left"):
# Add spaces on the left of pattern
for row in row_strings:
row = space*"-" + row
space_st = space_st + row + "\n"
new_row_strings = space_st.split("\n")
reflected_row_strings = new_row_strings[:len(row_strings)]
st_out = ""
for row in reflected_row_strings:
if space >= 0:
row = row[::-1] + row
# Overlap
else:
row = row[:0:-1] + row
st_out = st_out + row + "\n"
else:
# Add spaces on the right of pattern
for row in row_strings:
row = row + space*"-"
space_st = space_st + row + "\n"
new_row_strings = space_st.split("\n")
reflected_row_strings = new_row_strings[:len(row_strings)]
st_out = ""
for row in reflected_row_strings:
if space >= 0:
row = row + row[::-1]
# Overlap
else:
row = row + row[len(row_strings[0])-2::-1]
st_out = st_out + row + "\n"
return st_out
# Function: reflect pattern horizontally
# Input:
# st - pattern string
# spacing - positive integer value, gap between original and reflected pattern
# direction - 'Reflect above' or 'Reflect below', direction to reflect horizontally
# Output: modified string pattern
def reflect_h(st, spacing, direction):
row_strings = st.split("\n")
reflect_st = ""
if spacing >= 0 :
row_strings = row_strings[:-1]
reflected_row_strings = list(reversed(row_strings))
row_length = len(row_strings[0])
# Create string for spacing area
spacing_st = 2*spacing*(row_length*'-' + '\n')
for row in reflected_row_strings:
reflect_st = reflect_st + row + "\n"
if (direction == 'Reflect Above'):
st_out = reflect_st + spacing_st + st
else:
st_out = st + spacing_st + reflect_st
# Overlap
else:
row_strings = row_strings[:-1]
reflected_row_strings = list(reversed(row_strings[1:]))
for row in reflected_row_strings:
reflect_st = reflect_st + row + "\n"
if (direction == 'Reflect Above'):
st_out = reflect_st + st
else:
st_out = st + reflect_st
return(st_out)
# Function: stack string pattern horizontally (by copying original string pattern and placing it above original string pattern)
# Input:
# st - string pattern
# space - positive integer, space between original pattern and copied pattern
# Output: modified string pattern
def stack_h(st, space):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
st_out = ''
for row in row_strings:
st_out += row + space*'-' + row + '\n'
return(st_out)
# Function: stack string pattern horizontally (by copying original string pattern and placing it to the right of original string pattern)
# Input:
# st - string pattern
# space - positive integer, space between original pattern and copied pattern
# Output: modified string pattern
def stack_v(st, space):
row_strings = st.split("\n")
row_length = len(row_strings[0])
spacing_st = space*(row_length*'-' + '\n')
st_out = st + spacing_st + st
return(st_out)
# Function: copies original string pattern top left or bottom right direction
# Input:
# st - string pattern
# space - positive integer, space between original pattern and copied pattern
# Output: modified string pattern
def stack_d(st, space, direction):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
row_height = len(row_strings)
row_length = len(row_strings[0])
left_pattern = ''
right_pattern = ''
st_out = ''
spacing_st = (row_length + space)*'-'
for row in row_strings:
left_pattern += row + spacing_st + '\n'
right_pattern += spacing_st + row + '\n'
if (direction == 'Stack Left'):
st_out += left_pattern + right_pattern
else:
st_out += right_pattern + left_pattern
return(st_out)
# Function: joins two string pattern horizontally
# Input:
# st1, st2 - string patterns
# space - positive integer, gap between two joined patterns
# Output: modified string pattern
def join_patterns(st1, st2, space):
pattern_1 = st1.split("\n")
pattern_1 = pattern_1[:-1]
pattern_2 = st2.split("\n")
pattern_2 = pattern_2[:-1]
height = max(len(pattern_1), len(pattern_2))
space_to_add_p1 = math.ceil( (height - len(pattern_1))/2 )
space_to_add_p2 = math.ceil( (height - len(pattern_2))/2 )
p1 = add_basket_space(st1, space_to_add_p1, 0)
p2 = add_basket_space(st2, space_to_add_p2, 0)
pattern_1 = p1.split("\n")
pattern_1 = pattern_1[:-1]
pattern_2 = p2.split("\n")
pattern_2 = pattern_2[:-1]
st_out = ''
for a,b in zip(pattern_1, pattern_2):
st_out += a + space*'-' + b + '\n'
return(st_out)
|
matrix = [[dot == '#' for dot in line.strip()] for line in open('input.txt')]
diffs = [(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1) if (x, y) != (0, 0)]
corners = [(x, y) for x in (0, len(matrix)-1) for y in (0, len(matrix[0])-1)]
for x, y in corners:
matrix[x][y] = True
def neighbors(matrix, x, y):
for i, j in diffs:
if 0 <= i+x < len(matrix) and 0 <= y+j < len(matrix[0]):
yield matrix[x+i][y+j]
else:
yield False
for i in range(100):
new_matrix = [[False] * len(row) for row in matrix]
for x in range(len(matrix)):
for y in range(len(matrix[0])):
neighbor_count = sum(neighbors(matrix, x, y))
if matrix[x][y]:
new_matrix[x][y] = neighbor_count in (2, 3)
else:
new_matrix[x][y] = neighbor_count == 3
matrix = new_matrix
for x, y in corners:
matrix[x][y] = True
print(sum(sum(row) for row in matrix))
|
def multiply(a, b):
c = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
for k in range(3):
c[i][j] += a[i][k] * b[k][j]
return c
q = int(input())
for _ in range(q):
x, y, z, t = input().split()
x = float(x)
y = float(y)
z = float(z)
t = int(t)
m = [
[1 - x, y, 0],
[0, 1 - y, z],
[x, 0, 1 - z],
]
mat = None
while t > 0:
if t & 1 == 1:
if mat is None:
mat = [[m[i][j] for j in range(3)] for i in range(3)]
else:
mat = multiply(mat, m)
m = multiply(m, m)
t >>= 1
print(*[sum(mat[i]) for i in range(3)])
|
"""
exchanges. this acts as a routing table
"""
BITMEX = "BITMEX"
DERIBIT = "DERIBIT"
DELTA = "DELTA"
BITTREX = "BITTREX"
KUCOIN = "KUCOIN"
BINANCE = "BINANCE"
KRAKEN = "KRAKEN"
HITBTC = "HITBTC"
CRYPTOPIA = "CRYPTOPIA"
OKEX = "OKEX"
NAMES = [BITMEX, DERIBIT, DELTA, OKEX, BINANCE]
def exchange_exists(name):
return name in NAMES
|
# Exercise 3.1: Rewrite your pay computation to give the employee 1.5 times the
# rate for hours worked above 40 hours.
# Enter Hours: 45
# Enter Rate: 10
# Pay: 475.0
# Python for Everybody: Exploring Data Using Python 3
# by Charles R. Severance
hours = float(input("Enter hours: "))
rate_per_hour = float(input("Enter rate per hour: "))
additional_hours = hours - 40
gross_pay = 0
if additional_hours > 0:
hours_with_rate_per_hour = hours - additional_hours
gross_pay = hours_with_rate_per_hour * rate_per_hour
modified_rate_per_hour = rate_per_hour * 1.5
gross_pay += additional_hours * modified_rate_per_hour
else:
gross_pay = hours * rate_per_hour
print(gross_pay)
|
class BaseEmployee():
"The base class for an employee."
# Note: Unlike c#, on initiliazing a child class, the base contructor is not called
# unless specifically called.
def __init__(self, id, city):
"Constructor for the base employee class."
print('Base constructor called.');
self.id = id;
self.city = city;
def __del__(self):
"Will be called on destruction of employee object. Can also be called explicitly."
print(self.__class__.__name__, 'destroyed');
def printEmployee(self):
print("Id:", self.id, "Name:", self.name, "City:", self.city);
|
ix.enable_command_history()
app = ix.application
clarisse_win = app.get_event_window()
ix.application.open_edit_color_space_window(clarisse_win)
ix.disable_command_history()
|
distanca = int(input())
tempo = (2 * distanca)
print('%d minutos' %tempo)
|
def sayhello(name=None):
if name is None:
return "Hello World, Everyone!"
else:
return f"Hello World, {name}"
|
def binary_and(a: int , b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
"""
if a < 0 or b < 0:
raise ValueError('The value of both number must be positive')
a_bin = str(bin(a))[2:] # remove the leading "0b"
b_bin = str(bin(b))[2:] # remove the leading "0b"
max_length = max( len(a_bin) , len(b_bin) )
return '0b' + "".join(
str( int( a_bit == '1' and b_bit == '1' ) )
for a_bit , b_bit in zip(a_bin.zfill(max_length) , b_bin.zfill(max_length))
)
if __name__ == '__main__':
print( binary_and(2 , 600) )
|
def imgcd(m,n):
for i in range(1,min(m,n)+1):
if m%i==0 and n%i==0:
mcrf=i
return mcrf
a=input()
b=input()
c=imgcd(int(a),int(b))
print(c)
|
class Tape(object):
blank = " "
def __init__(self, tape):
self.tape = tape
self.head = 0
|
def extractOntimestoryWordpressCom(item):
'''
Parser for 'ontimestory.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if chp == 2019:
return None
badwords = [
'Dark Blue Kiss',
'2moons2',
'2Moons2',
'Love By Chance',
'Love by Chance',
'Theory of Love',
]
if any([bad in item['title'] for bad in badwords]):
return None
if item['tags'] == ['Bez kategorii']:
titlemap = [
('My Artist is Reborn – Chapter ', 'My Artist is Reborn', 'translated'),
('MAIR – Chapter ', 'My Artist is Reborn', 'translated'),
('TOFUH – Chapter ', 'The only favourite ugly husband', 'translated'),
('Tensei Shoujo no Rirekisho', 'Tensei Shoujo no Rirekisho', 'translated'),
('Master of Dungeon', 'Master of Dungeon', 'oel'),
]
for titlecomponent, name, tl_type in titlemap:
if titlecomponent.lower() in item['title'].lower():
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
tagmap = [
('spare tire is gone', 'spare tire is gone', 'translated'),
('devil venerable also wants to know', 'devil venerable also wants to know', 'translated'),
('tofuh', 'The Only Favourite Ugly Husband', 'translated'),
('turn on the love system', 'turn on the love system', 'translated'),
('mair', 'My Artist is Reborn', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
''''
Problem:
Determine if two strings are permutations.
Assumptions:
String is composed of lower 128 ASCII characters.
Capitalization matters.
'''
def isPerm(s1, s2):
if len(s1) != len(s2):
return False
arr1 = [0] * 128
arr2 = [0] * 128
for c, d in zip(s1, s2):
arr1[ord(c)] += 1
arr2[ord(d)] += 1
for i in xrange(len(arr1)):
if arr1[i] != arr2[i]:
return False
return True
def test():
s1 = "read"
s2 = "dear"
assert isPerm(s1, s2) == True
s1 = "read"
s2 = "red"
assert isPerm(s1, s2) == False
s1 = "read"
s2 = "race"
assert isPerm(s1, s2) == False
s1 = "Read"
s2 = "read"
assert isPerm(s1, s2) == False
print("Test passed")
test()
|
#Write a function to find the longest common prefix string amongst an array of strings.
#If there is no common prefix, return an empty string "".
def longest_common_prefix(strs) -> str:
common = ""
strs.sort()
for i in range(0, len(strs[0])):
if strs[0][i] == strs[-1][i]:
common += strs[0][i]
if strs[0][i] != strs[-1][i]:
break
return common
print(longest_common_prefix(["flow", "flower", "flowing"]))
|
class RestApiBaseTest(object):
def assert_items(self, items, cls):
"""Asserts that all items in a collection are instances of a class
"""
for item in items:
assert isinstance(item, cls)
def assert_has_valid_head(self, response, expected):
"""Asserts a response has a head string with an expected value
"""
assert 'head' in response
head = response['head']
assert isinstance(head, str)
assert head == expected
def assert_has_valid_link(self, response, expected_ending):
"""Asserts a response has a link url string with an expected ending
"""
assert link in response['link']
self.assert_valid_url(link, expected_ending)
def assert_has_valid_paging(self, js_response, pb_paging,
next_link=None, previous_link=None):
"""Asserts a response has a paging dict with the expected values.
"""
assert 'paging' in js_response
js_paging = js_response['paging']
if pb_paging.next:
assert 'next_position' in js_paging
if next_link is not None:
assert 'next' in js_paging
self.assert_valid_url(js_paging['next'], next_link)
else:
assert 'next' not in js_paging
def assert_has_valid_error(self, response, expected_code):
"""Asserts a response has only an error dict with an expected code
"""
assert 'error' in response
assert len(response) == 1
error = response['error']
assert 'code' in error
assert error['code'] == expected_code
assert 'title' in error
assert isinstance(error['title'], str)
assert 'message' in error
assert isinstance(error['message'], str)
def assert_has_valid_data_list(self, response, expected_length):
"""Asserts a response has a data list of dicts of an expected length.
"""
assert 'data' in response
data = response['data']
assert isinstance(data, list)
assert expected_length == len(data)
self.assert_items(data, dict)
def assert_has_valid_url(self, url, expected_ending=''):
"""Asserts a url is valid, and ends with the expected value
"""
assert isinstance(url, str)
assert url.startswith('http')
assert url.endswith(expected_ending)
def aasert_check_block_seq(blocks, *expected_ids):
if not isinstance(blocks, list):
blocks = [blocks]
consensus = None
for block, expected_id in zip(blocks, expected_ids):
assert isinstance(block, dict)
assert expected_id == block['header_signature']
assert isinstance(block['header'], dict)
assert consensus == b64decode(block['header']['consensus'])
batches = block['batches']
assert isinstance(batches, list)
assert len(batches) == 1
assert isinstance(batches, dict)
assert check_batch_seq(batches, expected_id)
return True
def assert_check_batch_seq(signer_key , batches , *expected_ids):
if not isinstance(batches, list):
batches = [batches]
for batch, expected_id in zip(batches, expected_ids):
assert expected_id == batch['header_signature']
assert isinstance(batch['header'], dict)
txns = batch['transactions']
assert isinstance(txns, list)
assert len(txns) == 1
assert isinstance(txns, dict)
assert check_transaction_seq(txns, expected_id) == True
return True
def assert_check_transaction_seq(txns , *expected_ids):
if not isinstance(txns, list):
txns = [txns]
payload = None
for txn, expected_id in zip(txns, expected_ids):
assert expected_id == txn['header_signature']
assert payload == b64decode(txn['payload'])
assert isinstance(txn['header'], dict)
assert expected_id == txn['header']['nonce']
return True
def assert_check_batch_nonce(self, response):
pass
def assert_check_family(self, response):
assert 'family_name' in response
assert 'family_version' in response
def assert_check_dependency(self, response):
pass
def assert_check_content(self, response):
pass
def assert_check_payload_algo(self):
pass
def assert_check_payload(self, response):
pass
def assert_batcher_public_key(self, signer_key , batch):
assert 'public_key' == batch['header']['signer_public_key']
def assert_signer_public_key(self, signer_key , batch):
assert 'public_key' == batch['header']['signer_public_key']
def aasert_check_batch_trace(self, trace):
assert bool(trace)
def assert_check_consensus(self):
pass
def assert_state_root_hash(self):
pass
def assert_check_previous_block_id(self):
pass
def assert_check_block_num(self):
pass
|
'''Programa clássico sobre média de notas de um aluno'''
n1 = float(input('Prineira nota: '))
n2 = float(input('Segunda nota: '))
media = (n1 + n2)/ 2
print('Sua média foi: {}'.format(media))
if media < 5.0:
print('Você está reprovado.')
elif media >= 7.0:
print("Você está aprovado. Parabéns!")
else:
print('Você está de recuperação.')
|
def target_file():
return ".html"
def target_domain():
return "https://lyricsmania.com/"
def artist_query(name):
return target_domain() + str.lower(name) + "_lyrics" + target_file()
if __name__ == "__main__":
print(artist_query("Lizzo"))
|
load("@bazel_skylib//lib:paths.bzl", "paths")
GlslLibraryInfo = provider("Set of GLSL header files", fields = ["hdrs", "includes"])
SpirvLibraryInfo = provider("Set of Spirv files", fields = ["spvs", "includes"])
def _export_headers(ctx, virtual_header_prefix):
strip_include_prefix = ctx.attr.strip_include_prefix
include_prefix = ctx.attr.include_prefix
outs = []
for hdr in ctx.files.hdrs:
path = hdr.owner.name
if strip_include_prefix:
if path.startswith(strip_include_prefix):
out = path.lstrip(strip_include_prefix)
out = out.lstrip("/")
else:
fail("{} is not a prefix of {}".format(strip_include_prefix, path))
else:
out = path
if include_prefix:
out = paths.join(include_prefix, out)
name = out.replace("/", "_") + "_export"
out = paths.join(
virtual_header_prefix,
out,
)
symlink = ctx.actions.declare_file(out)
ctx.actions.symlink(
output = symlink,
target_file = hdr,
)
outs.append(symlink)
return outs
def _compile_files(ctx, includes):
dephdrs = []
for dep in ctx.attr.deps:
glsllibraryinfo = dep[GlslLibraryInfo]
includes.extend(glsllibraryinfo.includes)
dephdrs.extend(
glsllibraryinfo.hdrs,
)
args = ctx.actions.args()
args.add("--target-env={}".format(ctx.attr.target_env))
args.add("--target-spv={}".format(ctx.attr.target_spv))
args.add("-std={}{}".format(ctx.attr.std_version, ctx.attr.std_profile))
args.add_all(includes, format_each = "-I%s", uniquify = True)
args.add_all(ctx.attr.defines, format_each = "-D%s", uniquify = True)
if ctx.attr.debug:
args.add("-g")
if ctx.attr.optimize:
args.add("-O")
strip_output_prefix = ctx.attr.strip_output_prefix
output_prefix = ctx.attr.output_prefix
outputs = []
for src in ctx.files.srcs:
path = src.owner.name
if strip_output_prefix:
if path.startswith(strip_output_prefix):
output_path = path.lstrip(strip_output_prefix)
output_path = output_path.lstrip("/")
else:
fail("{} is not a prefix of {}".format(strip_output_prefix, path))
else:
output_path = path
if output_prefix:
output_path = paths.join(output_prefix, output_path)
output_path = output_path + ".spv"
output_file = ctx.actions.declare_file(output_path)
outputs.append((output_path, output_file))
argsio = ctx.actions.args()
argsio.add_all(["-o", output_file.path, src])
ctx.actions.run(
outputs = [output_file],
inputs = ctx.files.srcs + ctx.files.hdrs + dephdrs,
executable = ctx.files.glslc[0],
arguments = [args, argsio],
)
return outputs
def _glsl_library_impl(ctx):
# compile the files
this_build_file_dir = paths.dirname(ctx.build_file_path)
this_package_dir = paths.join(this_build_file_dir, ctx.attr.name)
spirvs = {spv[0]: spv[1] for spv in _compile_files(ctx, [this_package_dir])}
# Make sure they are correctly exposed to other packages
virtual_header_prefix = "_virtual_includes/{}".format(ctx.attr.name)
hdrs = _export_headers(ctx, virtual_header_prefix)
includes = [paths.dirname(ctx.build_file_path)]
for include in ctx.attr.includes:
path = paths.normalize(paths.join(
this_build_file_dir,
virtual_header_prefix,
include,
))
includes.append(path)
includes.append(paths.join(ctx.bin_dir.path, path))
providers = [
DefaultInfo(
files = depset(hdrs + spirvs.values()),
runfiles = ctx.runfiles(
files = spirvs.values(),
),
),
GlslLibraryInfo(
hdrs = hdrs,
includes = includes,
),
CcInfo(), # So it can be used as a dep for cc_library/binary and have spirvs embedded as runfiles
]
if spirvs:
# Compute output location for spv files
# This will be used to populate the includes variable of the SpirvLibraryInfo provider
# Check if this could made more resilient
spirvs_root = paths.join(ctx.bin_dir.path, spirvs.values()[0].owner.workspace_root)
providers.append(SpirvLibraryInfo(
spvs = spirvs.values(),
includes = [spirvs_root],
))
return providers
glsl_library = rule(
implementation = _glsl_library_impl,
attrs = {
"include_prefix": attr.string(),
"strip_include_prefix": attr.string(),
"output_prefix": attr.string(),
"strip_output_prefix": attr.string(),
"srcs": attr.label_list(allow_files = [
"vert",
"tesc",
"tese",
"geom",
"frag",
# compute
"comp",
# mesh shaders
"mesh",
"task",
# ray tracing
"rgen",
"rint",
"rahit",
"rchit",
"rmiss",
"rcall",
# generic, for inclusion
"glsl",
]),
"hdrs": attr.label_list(allow_files = ["glsl"]),
"includes": attr.string_list(default = ["./"]),
"deps": attr.label_list(
providers = [GlslLibraryInfo],
),
"std_version": attr.string(
default = "460",
values = ["410", "420", "430", "440", "450", "460"],
),
"std_profile": attr.string(
default = "core",
values = ["core", "compatibility", "es"],
),
"target_spv": attr.string(
default = "spv1.3",
values = ["spv1.0", "spv1.1", "spv1.2", "spv1.3", "spv1.4", "spv1.5"],
),
"target_env": attr.string(
default = "vulkan1.2",
values = [
"vulkan1.0",
"vulkan1.1",
"vulkan1.2",
"vulkan", # Same as vulkan1.0
"opengl4.5",
"opengl", # Same as opengl4.5
],
),
"defines": attr.string_list(),
"debug": attr.bool(default = True),
"optimize": attr.bool(default = True),
"glslc": attr.label(
allow_single_file = True,
default = "@shaderc//:glslc",
),
},
)
|
node = S(input, "application/json")
node.prop("comment", "42!")
propertyNode = node.prop("comment")
value = propertyNode.stringValue()
|
def moeda(funcao, moeda='R$'):
return f'{moeda}{funcao:.2f}'.replace('.', ',')
def aumentar(p, taxa):
res = p * (1 + taxa/100)
return res
def diminuir(p, taxa):
res = p * (1 - taxa/100)
return res
def dobro(p):
res = p * 2
return res
def metade(p):
res = p / 2
return res
|
class Solution:
def naive(self,root):
self.res = 0
def dfs(tree,s):
s_ = s*10+tree.val
if tree.left==None and tree.right==None:
self.res+=s_
return
if tree.left:
dfs(tree.left,s_)
if tree.right:
dfs(tree.right,s_)
dfs(root,0)
return self.res
|
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
op=['a']*n
k=k-n
i=n-1
while k:
k+=1
if k/26>=1:
op[i]='z'
i-=1
k=k-26
else:
op[i]=chr(k+96)
k=0
return ''.join(op)
|
# -*- coding: utf-8 -*-
"""An implementation of learning priority sort algorithm_learning with NTM.
Input sequence length: "1 ~ 20: (1*2+1)=3 ~ (20*2+1)=41"
Input dimension: "8"
Output sequence length: equal to input sequence length.
Output dimension: equal to input dimension.
"""
|
def summation(n,term):
total,k=0,1
while k<=n:
total,k = term(k) + total, k+1
return total
def square(x):
return x*x
def pi_summantion(n):
return summation(n, lambda x: 8 / ((4*x-3) * (4*x-1)))
def suqare_summantio(n):
return summation(n, square)
print(pi_summantion(1e6))
print(suqare_summantio(4))
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 14:05:03 2020
Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed
Book Chapter 2 Finger Exercises
Using While Loop
@author: Atanas Kozarev - github.com/ultraasi-atanas
"""
numXs = int(input('How many times should I print the letter X? '))
toPrint = ''
# concatenate X to toPrint numXs times
while numXs > 0:
toPrint = toPrint + 'X'
numXs -= 1
print(toPrint)
|
def sort_2d_np(edges):
"""
edges: (m x 2)
Sort ascendngly according to each column.
Example:
edges = array(
[[9, 8],
[3, 6],
[1, 3],
[8, 6],
[3, 2],
[9, 1],
[5, 1]]
)
sorted_edges = array(
[[1, 3],
[3, 2],
[3, 6],
[5, 1],
[8, 6],
[9, 1],
[9, 8]]
)
"""
sort_idx = np.arange(len(edges))
sort_dim1 = edges[:,1].argsort()
sort_idx = sort_idx[sort_dim1]
edges = edges[sort_dim1]
sort_dim0 = edges[:,0].argsort()
sort_idx = sort_idx[sort_dim0]
edges = edges[sort_dim0]
return (sort_idx, edges)
def softmax_np(x):
assert isinstance(x, np.ndarray)
assert len(x.shape) == 1
x = np.exp(x)
return x/x.sum()
def l1_normalize_np(x):
assert isinstance(x, np.ndarray)
assert len(x.shape) == 1
return x/x.sum()
def diag_mask_np(n):
return np.array([[i, i] for i in range(n)])
|
# Der größte gemeinsame Teiler (ggT) von zwei Zahlen
# ist die größte Zahl, durch die man beide Zahlen teilen kann.
# Beispiel: Größter gemeinsamer Teiler von 4 und 6 ist 2.
# Die englische Bezeichnung ist greatest common divisor (gcd) für ggT.
def gcd(a, b):
while a != b:
if b > a:
a, b = b, a
a = a - b
return a
|
class PhotoAlbum:
def __init__(self, pages: int):
self.pages = pages
self.photos = [[] for _ in range(self.pages)]
@classmethod
def from_photos_count(cls, photos_count: int):
pages_count = photos_count // 4
if photos_count % 4 != 0:
pages_count += 1
return cls(pages_count)
def add_photo(self, label: str):
for index, current_page in enumerate(self.photos):
if len(current_page) < 4:
current_page.append(label)
return f"{label} photo added successfully on page {index + 1} slot {len(current_page)}"
return "No more free slots"
def display(self):
matrix = []
for row in self.photos:
current_sheet = []
for col in row:
current_sheet.append(str([]))
matrix.append(' '.join(current_sheet))
result = []
result.append("-----------")
for row in matrix:
result.append(row)
result.append("-----------")
return '\n'.join(result)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: PB/error.py
#
# 错误类
#
__all__ = [
"PBError",
"PBStateCodeError",
]
class PBError(Exception):
""" PB 错误类 """
pass
class PBStateCodeError(PBError):
""" PB 异常请求码 """
pass
|
print('hii'+str(5))
print(int(8)+5);
print(float(8.5)+5);
print(int(8.5)+5);
#print(int('C'))
|
def compare(v1, operator, v2):
if operator == ">":
return v1 > v2
elif operator == "<":
return v1 < v2
elif operator == ">=":
return v1 >= v2
elif operator == "<=":
return v1 <= v2
elif operator == "=" or "==":
return v1 == v2
elif operator == "!=":
return v1 != v2
|
# 変数を文字列に埋め込んで出力 : 文字列メソッドformat()
s = 'Alice'
i = 25
print('{} is {} years old'.format(s, i))
# インデックスを指定
print('{0} is {1} years old / {0}{0}{0}'.format(s, i))
# キーワード引数として指定
print('{name} is {age} years old / {age}{age}{age}'.format(name=s, age=i))
|
def return_load(**kwargs):
if kwargs['_type'] == 'Point':
load = PointLoad(**kwargs)
elif kwargs['_type'] == 'Uniform':
load = UniformLoad(**kwargs)
else:
print('Invalid type: returned default `PointLoad`')
return PointLoad()
return load
class PointLoad(object):
"""
docstring for PointLoad class
"""
def __init__(self, **kwargs):
self._position = kwargs['position'] if 'position' in kwargs else 0
self._force = kwargs['force'] if 'force' in kwargs else 0
self._moment = kwargs['moment'] if 'moment' in kwargs else 0
def __str__(self):
return 'Point Load:\n\tposition: {pos}\tforce: {force}\tmoment: {moment}\n'.format(
pos=self.position, force=self.force, moment=self.moment)
@property
def type(self):
return 'Point'
@property
def position(self):
return self._position
@position.setter
def position(self, value):
self._position = value if value >= 0 else self._position
@property
def force(self):
return self._force
@force.setter
def force(self, value):
self._force = value
@property
def moment(self):
return self._moment
@moment.setter
def moment(self, value):
self._moment = value
class UniformLoad(object):
"""
docstring for UniformLoad
"""
def __init__(self, **kwargs):
"""
:param start: start position
:param end: end position
:param line: line pressure
"""
self._start = kwargs['start'] if 'start' in kwargs else 0
self._end = kwargs['end'] if 'end' in kwargs else 0
self._line_pressure = kwargs['line_pressure'] if 'line_pressure' in kwargs else 0
def __str__(self):
return 'Uniform Load:\n\tstart: {start}\tend: {end}pressure: {line}\n'.format(
start=self.start, end=self.end, line=self.line_pressure)
@property
def start(self):
return self._start
@start.setter
def start(self, value):
self._start = value if 0 < value < self._end else self._start
@property
def end(self):
return self._end
@end.setter
def end(self, value):
self._end = value if value > self._start else self._end
@property
def line_pressure(self):
return self._line_pressure
@line_pressure.setter
def line_pressure(self, value):
self._line_pressure = value
@property
def position(self):
return (self.start + self.end) / 2
@property
def length(self):
return self.end - self.start
@property
def force(self):
return self.length * self.line_pressure
@property
def moment(self):
return 0
|
#pythran export fib_pythran(int)
def fib_pythran(n):
i, sum, last, curr = 0, 0, 0, 1
if n <= 2:
return 1
while i < n - 1:
sum = last + curr
last = curr
curr = sum
i += 1
return sum
#pythran export count_doubles_pythran_zip(str, int)
def count_doubles_pythran_zip(val, n):
total = 0
for c1, c2 in zip(val, val[1:]):
if c1 == c2:
total += 1
return total
#pythran export count_doubles_pythran(str, int)
def count_doubles_pythran(val, n):
total = 0
last = val[0]
for i in range(1, n):
cur = val[i]
if last == cur:
total += 1
last = cur
return total
#pythran export sum2d_pythran(int[][], int, int)
def sum2d_pythran(arr, m, n):
result = 0.0
for i in range(m):
for j in range(n):
result += arr[i,j]
return result
#pythran export mandel_pythran(int, int, int)
def mandel_pythran(x, y, max_iters):
i = 0
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z * z + c
if (z.real * z.real + z.imag * z.imag) >= 4:
return i
return 255
#pythran export fractal_pythran(float, float, float, float, uint8[][], int)
def fractal_pythran(min_x, max_x, min_y, max_y, image, iters):
height = image.shape[0]
width = image.shape[1]
pixel_size_x = (max_x - min_x) / width
pixel_size_y = (max_y - min_y) / height
for x in range(width):
real = min_x + x * pixel_size_x
for y in range(height):
imag = min_y + y * pixel_size_y
color = mandel_pythran(real, imag, iters)
image[y, x] = color
return image
|
#
# PySNMP MIB module PNNI-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PNNI-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:41:07 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:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint")
extensions, = mibBuilder.importSymbols("CENTILLION-ROOT-MIB", "extensions")
lecsConfIndex, = mibBuilder.importSymbols("LAN-EMULATION-ELAN-MIB", "lecsConfIndex")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Unsigned32, Bits, ModuleIdentity, MibIdentifier, IpAddress, iso, NotificationType, Gauge32, Counter64, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Counter32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Bits", "ModuleIdentity", "MibIdentifier", "IpAddress", "iso", "NotificationType", "Gauge32", "Counter64", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Counter32", "ObjectIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
cnPnniExt = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 3, 5))
cnPnniMainExt = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 3, 5, 1))
cnPnnilecsExt = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 3, 5, 2))
cnPnniTdbOverload = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 3, 5, 3))
cnPnniAdminStatus = MibScalar((1, 3, 6, 1, 4, 1, 930, 3, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cnPnniAdminStatus.setStatus('mandatory')
if mibBuilder.loadTexts: cnPnniAdminStatus.setDescription('The desired state of PNNI in the switching system. Setting this object to disabled(2) disables PNNI capability in the switch. Setting it to enabled(1) enables PNNI capability.')
cnPnniCurNodes = MibScalar((1, 3, 6, 1, 4, 1, 930, 3, 5, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cnPnniCurNodes.setStatus('mandatory')
if mibBuilder.loadTexts: cnPnniCurNodes.setDescription('The number of PNNI logical nodes currently configured in the switching system.')
lecsConfExtTable = MibTable((1, 3, 6, 1, 4, 1, 930, 3, 5, 2, 1), )
if mibBuilder.loadTexts: lecsConfExtTable.setStatus('mandatory')
if mibBuilder.loadTexts: lecsConfExtTable.setDescription('This table contains the configuration information that are additional to the existing lecsConfTable')
lecsConfExtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 930, 3, 5, 2, 1, 1), ).setIndexNames((0, "LAN-EMULATION-ELAN-MIB", "lecsConfIndex"))
if mibBuilder.loadTexts: lecsConfExtEntry.setStatus('mandatory')
if mibBuilder.loadTexts: lecsConfExtEntry.setDescription('Each entry represents a LECS this agent maintains in this extension table. A row in this table is not valid unless the same row is valid in the lecsConfTable defined in af1129r5.mib')
lecsConfExtScope = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 3, 5, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 104))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: lecsConfExtScope.setStatus('mandatory')
if mibBuilder.loadTexts: lecsConfExtScope.setDescription('PNNI scope value')
cnPnniMemConsumptionLowwater = MibScalar((1, 3, 6, 1, 4, 1, 930, 3, 5, 3, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cnPnniMemConsumptionLowwater.setStatus('mandatory')
if mibBuilder.loadTexts: cnPnniMemConsumptionLowwater.setDescription('The value of low memory watermark. If memory allocated to PNNI task is less than this value, then the Database resynchronization be attempted.')
cnPnniMemConsumptionHighwater = MibScalar((1, 3, 6, 1, 4, 1, 930, 3, 5, 3, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cnPnniMemConsumptionHighwater.setStatus('mandatory')
if mibBuilder.loadTexts: cnPnniMemConsumptionHighwater.setDescription('The value of high memory watermark. If memory allocated to PNNI task is greater than this value, then the node will enter to topology database overload state.')
cnPnniOverLoadRetryTime = MibScalar((1, 3, 6, 1, 4, 1, 930, 3, 5, 3, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cnPnniOverLoadRetryTime.setStatus('mandatory')
if mibBuilder.loadTexts: cnPnniOverLoadRetryTime.setDescription('The value of the database resynch attempt timer in seconds.')
mibBuilder.exportSymbols("PNNI-EXT-MIB", lecsConfExtEntry=lecsConfExtEntry, cnPnniTdbOverload=cnPnniTdbOverload, lecsConfExtTable=lecsConfExtTable, cnPnniOverLoadRetryTime=cnPnniOverLoadRetryTime, cnPnniMainExt=cnPnniMainExt, cnPnniCurNodes=cnPnniCurNodes, cnPnniMemConsumptionHighwater=cnPnniMemConsumptionHighwater, cnPnniExt=cnPnniExt, cnPnniMemConsumptionLowwater=cnPnniMemConsumptionLowwater, lecsConfExtScope=lecsConfExtScope, cnPnnilecsExt=cnPnnilecsExt, cnPnniAdminStatus=cnPnniAdminStatus)
|
"""
@author Huaze Shen
@date 2019-10-05
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def delete_duplicates(head):
if head is None or head.next is None:
return head
pre = head
while pre:
cur = pre
while cur.next and cur.val == cur.next.val:
cur = cur.next
pre.next = cur.next
pre = pre.next
return head
if __name__ == '__main__':
head_ = ListNode(1)
head_.next = ListNode(2)
head_.next.next = ListNode(3)
head_.next.next.next = ListNode(3)
head_.next.next.next.next = ListNode(4)
head_.next.next.next.next.next = ListNode(4)
head_.next.next.next.next.next.next = ListNode(5)
result = delete_duplicates(head_)
while result:
print(result.val)
result = result.next
|
# flake8: noqa
bm25 = BatchRetrieve(index, "BM25")
axiom = (ArgUC() & QTArg() & QTPArg()) | ORIG()
# Re-rank top-20 documents with KwikSort.
kwiksort = bm25 % 20 >> \
KwikSortReranker(axiom, index)
pipeline = kwiksort ^ bm25
|
ciphertext = "WAPSD EXTCO EEREF SELIO RSARC LIETE OIHHP VASTF EGBER IPAPN TOEGI AIATH DDHIY EACYE RQAEN OHRTE TEVME BGHMF EIOWS GFHCL XEUUC OMTOT LERES SDEWW ORCCS HEURE ATTEG ALSEB APXET IURWV RTEEH IOTLO SNACN NULCV LCMTH HHCOH TIOTD ASNAL TSANA CASOR LEKAS TATCW INTLO TRYER YLTND RILER AOMAX OITDE ECOIA HAALS TYIOA DAEHI OTSTE IEYES HHSNG EHCAT SOUAC EHSST TCODN FSOTS TIIGN LTTNL DUBST TCMIM EHTAO IUUPF TSTTI PUEAY OAEOA EEALA LWGWM GNHYU IAAHD TORYA OLVMH RHTGY IHNNM UAARL MMHID HYFCP GRAET MTCNT HIIIO RCVCL BOTSA OFRNR YEHTG IFHEA WLYSC EEEEY UVEIM SOEUE TAYHN NITEK AERAW DSIAE QTDIE HET".replace(" ","")
def getLineLength(l_cipher,line,key):
n = key
q = l_cipher // (2*n-2)
r = l_cipher % (2*n-2)
assert type(q) is int
if line == 1:
return (q+1) if r >= 1 else q
elif line == key:
return (q+1) if r >= key else q
else:
if r >= (2*n-2) - (line - 2):
return 2*q + 2
elif r >= line:
return 2*q + 1
else:
return 2*q
def sumRowIndex(l_cipher,row,key):
sum = 0
for line in range (1,row+1):
sum += getLineLength(l_cipher,line,key)
return sum
def decrypt(cipher,key):
plain = ''
l = len(cipher)
for i in range (1,l+1):
# i = nq + r
n = key
q = i // (2*n-2)
r = i % (2*n-2)
if r >= key + 1:
row = key - (r-key)
column = 2*q + 2
elif r == key:
row = key
column = q + 1
elif r >= 2:
row = r
column = 2*q +1
elif r == 1:
row = 1
column = q+1
else:
row = 2
column = 2*q
print(i, sumRowIndex(l,row-1,key)+column)
print(plain)
plain += cipher[sumRowIndex(l,row-1,key)+column-1]
return plain
test_vector = 'WECRL TEERD SOEEF EAOCA IVDEN'.replace(' ','')
print(decrypt(ciphertext,17))
|
class PractitionerTemplate:
def __init__(self):
super().__init__()
def practitioner_default(self, data_list):
keys = []
for data in data_list:
key = f"{data.get('rowid')},{data.get('employee_id')}"
keys.append(key)
return keys
|
def update_bit(num, bit, value):
mask = ~(1 << bit)
return (num & mask) | (value << bit)
def get_bit(num, bit):
return (num & (1 << bit)) != 0
def insert_bits(n, m, i, j):
for bit in range(i, j + 1):
n = update_bit(n, bit, get_bit(m, bit - i))
return n
def insert_bits_mask(n, m, i, j):
mask = (~0 << (j + 1)) + ~(~0 << i)
n = n & mask
m = m << i
return n | m
n = 2**11
m = 0b10011
i = 2
j = 6
bin(insert_bits(n, m, 2, 6))
bin(insert_bits_mask(n, m, 2, 6))
|
nodes = [[1,3], [0,2], [1,3], [0,2]]
otherNodes = [[1,2,3], [0,2], [0,1,3], [0,2]]
def isBipartite(nodes):
colors = [0] * len(nodes)
for index, node in enumerate(nodes):
if colors[index] == 0 and not properColor(nodes, colors, 1, index):
return False
return True
def properColor(graph, colors, color, nodeNum):
if colors[nodeNum] != 0:
return colors[nodeNum] == color
colors[nodeNum] = color
for children in graph[nodeNum]:
if not properColor(graph, colors, -color, children):
return False
return True
print(isBipartite(nodes))
print(isBipartite(otherNodes))
|
manipulated_string = input()
while True:
line = input()
if line == "end":
break
command_element = line.split(' ')
command = command_element[0]
first_condition = int(command_element[1])
if command == 'Right':
for i in range(first_condition):
manipulated_string = manipulated_string[-1] + manipulated_string[0:len(manipulated_string)-1]
elif command == 'Left':
for i in range(first_condition):
manipulated_string = manipulated_string[1:len(manipulated_string)] + manipulated_string[0]
elif command == 'Delete':
second_condition = int(command_element[2])
manipulated_string = manipulated_string.replace(manipulated_string[first_condition:second_condition+1], '')
elif command == 'Insert':
second_condition = command_element[2]
if first_condition == 0:
manipulated_string = second_condition + manipulated_string
else:
manipulated_string = manipulated_string[0:first_condition] + second_condition + manipulated_string[(first_condition+1):len(manipulated_string)]
else:
print(f'Unsolved command: {command}')
print(manipulated_string)
|
c = {a: 1, b: 2}
fun(a, b, **c)
# EXPECTED:
[
...,
LOAD_NAME('fun'),
...,
BUILD_TUPLE(2),
...,
CALL_FUNCTION_EX(1),
...,
]
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if not head:
return head
d1 = ListNode(-1)
temp1 = d1
d2 = ListNode(-1)
temp2 = d2
temp = head
while temp:
if temp.val < x:
temp1.next = temp
temp = temp.next
temp1 = temp1.next
temp1.next = None
else:
temp2.next = temp
temp = temp.next
temp2 = temp2.next
temp2.next = None
temp1.next = d2.next
return d1.next
|
entrada = 'Gilberto'
saida = '{:+^12}'.format(entrada)
print(saida)
entrada = 'sensoriamento remoto'
saida = entrada.capitalize()
print(saida)
entrada = 'sensoriamento remoto'
saida = entrada.title()
print(saida)
entrada = 'GilberTo'
saida = entrada.lower()
print(saida)
entrada = 'Gilberto'
saida = '{:*<10}'.format(entrada)
print(saida)
entrada = 'Gilberto'
saida = '{:*>10}'.format(entrada)
print(saida)
entrada = ' Gilberto'
saida = entrada.strip()
print(saida)
entrada = '[email protected]'
saida = entrada.partition('@')
print(saida)
entrada = 'CBERS_4_PAN5M_20180308'
saida = entrada.split('_')
print(saida)
entrada = 'Gilberto@@@'
saida = entrada.strip('@')
print(saida)
entrada = '@@Gilberto@@@'
saida = entrada.strip('@')
print = saida
|
n = int(input())
l = {}
for i in range(n):
k = input()
if k in l:
l[k] += 1
else:
l[k] = 1
print(len(l))
for i in l:
print(l[i], end=" ")
|
# @Time: 2022/4/12 20:29
# @Author: chang liu
# @Email: [email protected]
# @File:4-3-Creating-New-Iteration-Patterns-With-Generators.py
def frange(start, stop, increment):
x = start
while x < stop:
yield x
x += increment
# for n in frange(1, 5, 0.6):
# print(n)
def countdown(n):
print(f"starting counting from {n}")
while n > 0:
yield n
n -= 1
print("Done")
g = countdown(3)
print(next(g))
print(next(g))
print(next(g))
#stuck in yield point
# print(next(g))
print("*" * 30)
i = iter([])
print(next(i))
|
"""
Created on 20 Feb 2019
@author: Frank Ypma
"""
class Location:
"""
Simple x,y coordinate wrapper
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
|
def test_get_key(case_data):
"""
Test :meth:`.get_key`.
Parameters
----------
case_data : :class:`.CaseDat`
A test case. Holds the key maker to test and the correct key
it should produce.
Returns
-------
None : :class`NoneType`
"""
_test_get_key(
key_maker=case_data.key_maker,
molecule=case_data.molecule,
key=case_data.key,
)
def _test_get_key(key_maker, molecule, key):
"""
Test :meth:`.get_key`.
Parameters
----------
key_maker : :class:`.MoleculeKeyMaker`
The key maker to test.
molecule : :class:`.Molecule`
The molecule to pass to the `key_maker`.
key : :class:`object`
The correct key of `molecule`.
Returns
-------
None : :class:`NoneType`
"""
assert key_maker.get_key(molecule) == key
|
# https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3251/
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
inc = True
incd = False
decd = False
for i,elmnt in enumerate(arr):
if i == 0:continue
if (inc == True) and (arr[i]>arr[i-1]):
incd = True
continue
else:
inc = False
if (inc == False) and (incd == True) and (arr[i]<arr[i-1]):
decd = True
continue
else:
return False
if incd == True and decd==True:
return True
|
def get_input() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt") as f:
return [int(l[:-1]) for l in f.readlines()]
def has_pair(sum_val: int, vals: list) -> bool:
for idx_i, i in enumerate(vals):
for j in vals[idx_i+1:]:
if i + j == sum_val:
return True
return False
def find_invalid(numbers: list, preamble: int) -> int:
for idx, val in enumerate(numbers[preamble:]):
if not has_pair(val, numbers[idx:preamble+idx]):
return val
def part1(vals: list, preamble: int) -> int:
return find_invalid(vals, preamble)
def part2(vals: list, preamble: int) -> int:
invalid_number = find_invalid(vals, preamble)
count = len(vals)
for x in range(count):
set_sum = vals[x]
for y in range(x+1, count):
set_sum += vals[y]
if set_sum == invalid_number:
return min(vals[x:y]) + max(vals[x:y])
if set_sum > invalid_number:
break
def main():
file_input = get_input()
print(f"Part 1: {part1(file_input, 25)}")
print(f"Part 2: {part2(file_input, 25)}")
def test():
test_input = [
35,
20,
15,
25,
47,
40,
62,
55,
65,
95,
102,
117,
150,
182,
127,
219,
299,
277,
309,
576,
]
assert part1(test_input, 5) == 127
assert part2(test_input, 5) == 62
if __name__ == "__main__":
test()
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################
# Institut Villebon, UE 3.1
# Projet : mon_via_navigo
# Auteur : C.Lavrat, B. Marie Joseph, S. Sonko
# Date de creation : 27/12/15
# Date de derniere modification : 27/12/15
##############################################
class Station:
"""
The Station module
==================
This class creates stations and contains all the informations of the stations
Parameters
----------
:param name: name of the station
:param position: position of the station
:param in_line: line of the station
:type name: str
:type position: list format [x,y]
:type in_line: str
:Example:
>>>Orsay_Ville = Station("Orsay Ville",[1.5,3.14],"RER B")
>>>
Function of information
-----------------------
_eq_(self, station):
| tells if two stations are the same or not
_lt_(self, station):
| gives the first station in the alphabeter range
_hash_(self):
| returns hash(self.name + self.in_line)
_str_(self):
| Prints a textual representation of the current station
.. Date:: 27/12/2015
.. author:: Cyril
"""
#------------------------------------------------------------------------------#
#initialisation of the class : #
#------------------------------------------------------------------------------#
def __init__(self, name, position, in_line=""):
"""
The __init__ fonction
=====================
this function is the constructor of the station's module
Parameters
----------
:param name: name of the station
:param position: position of the station
:param in_line: line of the station
:type name: str
:type position: list format [x,y]
:type in_line: str
:Example:
>>>Orsay_Ville = Station("Orsay Ville",[1.5,3.14],"RER B")
>>>
Module attribute
--------------
:param name: name of the station
:param position: position of the station
:param in_line: line of the station
:type name: str
:type position: list format [x,y]
:type in_line: str
.. Date:: 27/12/2015
.. author:: Cyril
"""
#INPUT TESTS
#----------------------------------------------------------------------#
#name of the station
#test of the type of name
if type(name) == type(str()) :
self.name = name
else :
raise TypeError(str(name)+" is not a str")
#----------------------------------------------------------------------#
#test of the type of position
#position of the station
if type(position) == type(list()) :
self.position = position
else :
raise TypeError(str(position)+" is not a list")
#----------------------------------------------------------------------#
#test of the type of in_line
#line of the station
if type(in_line) == type(str()):
self.in_line = in_line
else :
raise TypeError(str(in_line)+" is not a str")
#======================================================================#
################################################################################
# Fonction of information #
################################################################################
#------------------------------------------------------------------------------#
# __eq__(self, station) : Say if two station are the same or not #
#------------------------------------------------------------------------------#
def _eq_(self, station):
"""
The _eq_ function
===================
Tells if two stations are the same or not, using the hash value.
:Example:
>>>Orsay_Ville = Station("Orsay Ville",[1.5,3.14],"RER B")
>>>Orsay = Station("Orsay Ville",[1.5,3.14],"RER B")
>>>Orsay_Ville._eq_("Orsay")
True
.. Date:: 27/12/2015
.. Author:: Cyril
"""
#if the hash value of the station is the same
if self._hash_() == hash(station.name + station.in_line):
#the station is the same
return True
else:
#the station is not the same
return False
#======================================================================#
#------------------------------------------------------------------------------#
# __lt__(self, station) : Return the first station in the alphabetical order. #
#------------------------------------------------------------------------------#
def _lt_(self, station):
"""
The _lt_ function
===================
Returns the first station in the alphabetical order.
:Example:
>>>Palaiseau = Station("Palaiseau",[1.4,15.7],"RER B")
>>>Palaiseau_villebon = Station("Palaiseau Villebon",[1.4,18.14],"RER B")
>>>Orsay_Ville._lt_()
Palaiseau
.. Date:: 27/12/2015
.. author:: Cyril
"""
#----------------------------------------------------------------------#
#if the station are not the same
if not self._eq_(station):
if not str(station.name) > str(self.name):
if not str(station.in_line) > str(self.in_line):
return station.name
else:
#print(self.name)
return self.name
else:
return self.name
#----------------------------------------------------------------------#
#if the station are the same
else:
raise ValueError("/!\ : this station are the same")
#======================================================================#
#------------------------------------------------------------------------------#
# __hash__(self) : Return a hash value for the station and line. #
#------------------------------------------------------------------------------#
def _hash_(self):
"""
The _hash_ function
=====================
Returns a hash value for the station and line.
Two stations with the same informations have the same hash value.
The reverse is not necessarily true, but it can be true.
/!\ warning : the hash value is different between two runs
:Example:
>>>Orsay_Ville = Station("Orsay Ville",[1.5,3.14],"RER B")
>>>Orsay_Ville._hash_()
-4599906160503219187
.. Date:: 27/12/2015
.. author:: Cyril
"""
return hash(self.name + self.in_line)
#======================================================================#
#------------------------------------------------------------------------------#
# __str__(self) : return a textuel representation of the current station #
#------------------------------------------------------------------------------#
def _str_(self):
"""
The _str_ function
====================
returns a textual representation of the current station
:Example:
>>>orsay_ville = Station("Orsay Ville",[1.618,3.141],"RER B")
>>>print(orsay_ville._str_())
************************
* Station Informations *
************************
Name = Orsay Ville
Position = [1.618,3.141]
Line = RER B
************************
.. Date:: 27/12/2015
.. author:: Cyril
"""
#creation of a msg with all the information
msg = "************************\n"
msg += "* Station Informations *\n"
msg += "************************\n"
msg += "Name = " + str(self.name) + "\n"
msg += "Position = " + str(self.position) + "\n"
msg += "Line = " + str(self.in_line) + "\n"
msg += "************************"
return msg
#======================================================================#
if __name__ == '__main__':
"""
The __main__ function
=====================
.. Date:: 27/12/2015
.. author:: Cyril
"""
print("If you whant to test your programm run the tests in the joigned file \n")
|
"""
Profile ../profile-datasets-py/div52_zen50deg/034.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div52_zen50deg/034.py"
self["Q"] = numpy.array([ 1.607768, 4.15376 , 5.83064 , 7.181963, 6.558055,
7.26391 , 9.444143, 8.659606, 7.119357, 7.498499,
7.80505 , 7.015238, 5.997863, 6.461718, 6.713751,
6.317727, 5.925691, 5.606566, 5.591775, 5.563366,
5.50166 , 5.412027, 5.309597, 5.19215 , 5.07004 ,
4.94703 , 4.840709, 4.738037, 4.61194 , 4.488335,
4.347817, 4.211848, 4.110768, 4.013981, 3.964719,
3.936519, 3.917997, 3.918496, 3.918994, 3.929766,
3.94131 , 3.95369 , 3.967018, 3.979784, 3.981906,
3.983964, 3.981617, 3.976198, 3.97578 , 4.001344,
4.026361, 4.359103, 4.782813, 5.49391 , 6.649441,
7.793169, 9.087655, 10.35708 , 11.34142 , 12.2309 ,
13.14354 , 14.07536 , 15.22698 , 16.88403 , 18.59387 ,
20.82526 , 23.01806 , 26.52261 , 29.98615 , 33.67396 ,
37.337 , 42.52849 , 47.95533 , 57.36908 , 67.46491 ,
77.61677 , 87.64669 , 99.15107 , 110.2237 , 120.0812 ,
129.429 , 138.2167 , 158.5282 , 182.8389 , 211.6201 ,
246.1618 , 291.4563 , 350.1063 , 394.3911 , 459.7997 ,
520.9591 , 545.405 , 570.1204 , 578.4676 , 516.3112 ,
211.9946 , 206.087 , 200.4205 , 194.9806 , 189.7593 ,
184.7422 ])
self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02,
7.69000000e-02, 1.37000000e-01, 2.24400000e-01,
3.45400000e-01, 5.06400000e-01, 7.14000000e-01,
9.75300000e-01, 1.29720000e+00, 1.68720000e+00,
2.15260000e+00, 2.70090000e+00, 3.33980000e+00,
4.07700000e+00, 4.92040000e+00, 5.87760000e+00,
6.95670000e+00, 8.16550000e+00, 9.51190000e+00,
1.10038000e+01, 1.26492000e+01, 1.44559000e+01,
1.64318000e+01, 1.85847000e+01, 2.09224000e+01,
2.34526000e+01, 2.61829000e+01, 2.91210000e+01,
3.22744000e+01, 3.56504000e+01, 3.92566000e+01,
4.31001000e+01, 4.71882000e+01, 5.15278000e+01,
5.61259000e+01, 6.09895000e+01, 6.61252000e+01,
7.15398000e+01, 7.72395000e+01, 8.32310000e+01,
8.95203000e+01, 9.61138000e+01, 1.03017000e+02,
1.10237000e+02, 1.17777000e+02, 1.25646000e+02,
1.33846000e+02, 1.42385000e+02, 1.51266000e+02,
1.60496000e+02, 1.70078000e+02, 1.80018000e+02,
1.90320000e+02, 2.00989000e+02, 2.12028000e+02,
2.23441000e+02, 2.35234000e+02, 2.47408000e+02,
2.59969000e+02, 2.72919000e+02, 2.86262000e+02,
3.00000000e+02, 3.14137000e+02, 3.28675000e+02,
3.43618000e+02, 3.58966000e+02, 3.74724000e+02,
3.90892000e+02, 4.07474000e+02, 4.24470000e+02,
4.41882000e+02, 4.59712000e+02, 4.77961000e+02,
4.96630000e+02, 5.15720000e+02, 5.35232000e+02,
5.55167000e+02, 5.75525000e+02, 5.96306000e+02,
6.17511000e+02, 6.39140000e+02, 6.61192000e+02,
6.83667000e+02, 7.06565000e+02, 7.29886000e+02,
7.53627000e+02, 7.77789000e+02, 8.02371000e+02,
8.27371000e+02, 8.52788000e+02, 8.78620000e+02,
9.04866000e+02, 9.31523000e+02, 9.58591000e+02,
9.86066000e+02, 1.01395000e+03, 1.04223000e+03,
1.07092000e+03, 1.10000000e+03])
self["CO2"] = numpy.array([ 322.2185, 322.2177, 322.2171, 322.2167, 322.2169, 322.2167,
322.216 , 322.2162, 322.2167, 322.2166, 322.2165, 322.2167,
322.2171, 322.2169, 322.2168, 322.217 , 322.2171, 322.2172,
322.2172, 322.2172, 322.2172, 322.2173, 322.2173, 322.2173,
322.2174, 322.2174, 322.2174, 322.2175, 322.2175, 322.2176,
322.2176, 322.4306, 322.6597, 322.9027, 323.1607, 323.4357,
323.7267, 324.0347, 324.3597, 324.7017, 325.0627, 325.4417,
325.8397, 326.2567, 326.6937, 327.1507, 327.6277, 328.1257,
328.6447, 329.1847, 329.7467, 330.3306, 330.9364, 331.5652,
332.2168, 332.2164, 332.216 , 332.2156, 332.2152, 332.2149,
332.2146, 332.2143, 332.2139, 332.2134, 332.2128, 332.2121,
332.2114, 332.2102, 332.209 , 332.2078, 332.2066, 332.2049,
332.2031, 332.1999, 332.1966, 332.1932, 332.1899, 332.1861,
332.1824, 332.1791, 332.176 , 332.1731, 332.1663, 332.1583,
332.1487, 332.1372, 332.1222, 332.1027, 332.088 , 332.0662,
332.0459, 332.0378, 332.0296, 332.0268, 332.0475, 332.1486,
332.1505, 332.1524, 332.1542, 332.156 , 332.1576])
self["T"] = numpy.array([ 192.746, 186.766, 205.5 , 228.794, 244.789, 247.272,
249.779, 252.472, 253.77 , 252.084, 246.384, 236.666,
225.418, 216.538, 209.571, 202.537, 196.983, 193.159,
191.01 , 190.352, 191.525, 193.726, 196.206, 198.563,
199.985, 200.848, 200.204, 199.38 , 197.937, 196.596,
195.898, 195.224, 194.96 , 194.72 , 195.053, 195.626,
196.417, 197.677, 198.902, 200.162, 201.395, 202.587,
203.737, 204.862, 206.087, 207.283, 208.229, 208.996,
209.692, 210.093, 210.485, 210.601, 210.629, 210.612,
210.525, 210.436, 210.279, 210.125, 209.894, 209.645,
209.628, 209.817, 210.239, 211.178, 212.165, 213.568,
214.947, 216.387, 217.804, 219.193, 220.559, 221.911,
223.243, 224.56 , 225.858, 227.197, 228.524, 229.97 ,
231.429, 233.013, 234.662, 236.389, 238.08 , 239.729,
241.3 , 242.737, 244.119, 245.455, 246.488, 247.294,
247.983, 249.017, 249.685, 249.92 , 249.496, 238.373,
238.373, 238.373, 238.373, 238.373, 238.373])
self["O3"] = numpy.array([ 1.17268 , 1.17593 , 1.182457 , 1.193728 , 1.21701 ,
1.242897 , 1.266096 , 1.287477 , 1.349363 , 1.574502 ,
1.972782 , 2.510987 , 3.092075 , 3.618445 , 4.030167 ,
4.557568 , 5.133355 , 5.533019 , 5.719022 , 5.730295 ,
5.611414 , 5.333457 , 4.99594 , 4.627713 , 4.326831 ,
4.069157 , 3.91057 , 3.765929 , 3.595285 , 3.427744 ,
3.234277 , 3.047081 , 2.863011 , 2.684474 , 2.51928 ,
2.362425 , 2.227439 , 2.132595 , 2.040322 , 1.946594 ,
1.854912 , 1.731223 , 1.571967 , 1.415704 , 1.224755 ,
1.038302 , 0.8721727 , 0.7211843 , 0.5823831 , 0.4935311 ,
0.4065938 , 0.334958 , 0.2690924 , 0.2104054 , 0.1619372 ,
0.1159878 , 0.09491241, 0.07424563, 0.06642134, 0.06238607,
0.06036811, 0.06014346, 0.06024959, 0.06107934, 0.0620737 ,
0.06424653, 0.06638255, 0.06890043, 0.0713821 , 0.07347392,
0.07548728, 0.07692545, 0.07823204, 0.07906522, 0.07979273,
0.08028852, 0.08074569, 0.08076829, 0.08075714, 0.08061033,
0.08056312, 0.08062999, 0.08069894, 0.08072594, 0.08061984,
0.08051027, 0.08041131, 0.08032214, 0.08014305, 0.07974273,
0.07928489, 0.0788656 , 0.07837151, 0.07775992, 0.07733472,
0.07882192, 0.07882239, 0.07882283, 0.07882326, 0.07882367,
0.07882407])
self["CTP"] = 500.0
self["CFRACTION"] = 0.0
self["IDG"] = 0
self["ISH"] = 0
self["ELEVATION"] = 0.0
self["S2M"]["T"] = 238.373
self["S2M"]["Q"] = 214.057055538
self["S2M"]["O"] = 0.0788217567578
self["S2M"]["P"] = 949.354
self["S2M"]["U"] = 1.17723
self["S2M"]["V"] = 0.821594
self["S2M"]["WFETC"] = 100000.0
self["SKIN"]["SURFTYPE"] = 0
self["SKIN"]["WATERTYPE"] = 1
self["SKIN"]["T"] = 233.614
self["SKIN"]["SALINITY"] = 35.0
self["SKIN"]["FOAM_FRACTION"] = 0.0
self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3])
self["ZENANGLE"] = 50.0
self["AZANGLE"] = 0.0
self["SUNZENANGLE"] = 0.0
self["SUNAZANGLE"] = 0.0
self["LATITUDE"] = 82.4134
self["GAS_UNITS"] = 2
self["BE"] = 0.0
self["COSBK"] = 0.0
self["DATE"] = numpy.array([1992, 12, 15])
self["TIME"] = numpy.array([18, 0, 0])
|
#--- Exercicio 1 - Impressão de dados com a função Print
#--- Imprima nome, sobrenome e idade cada um em uma nova linha
nome = 'Pablo'
sobrenome = 'Schumacher'
idade=16
print(f'Nome: {nome}\nSobrenom: {sobrenome}\nIdade: {idade}')
|
"""The markdown module."""
# pylint: disable=invalid-name
def bold(text):
"""Bold.
Args:
text (str): text to make bold.
Returns:
str: bold text.
"""
return '**' + text + '**'
def code(text, inline=False, lang=''):
"""Code.
Args:
text (str): text to make code.
inline (bool, optional): format as inline code, ignores the lang argument. Defaults to False.
lang (str, optional): set the code block language. Defaults to ''.
Returns:
str: code text.
"""
if inline:
return '`{}`'.format(text)
return '```{}\r\n'.format(lang) + text + '\r\n```'
def cr():
"""Carriage Return (Line Break).
Returns:
str: Carriage Return.
"""
return '\r\n'
def h1(text):
"""Heading 1.
Args:
text (str): text to make heading 1.
Returns:
str: heading 1 text.
"""
return '# ' + text + '\r\n'
def h2(text):
"""Heading 2.
Args:
text (str): text to make heading 2.
Returns:
str: heading 2 text.
"""
return '## ' + text + '\r\n'
def h3(text):
"""Heading 3.
Args:
text (str): text to make heading 3.
Returns:
str: heading 3 text.
"""
return '### ' + text + '\r\n'
def h4(text):
"""Heading 4.
Args:
text (str): text to make heading 4.
Returns:
str: heading 4 text.
"""
return '#### ' + text + '\r\n'
def newline():
"""New Line.
Returns:
str: New Line.
"""
return '\r\n'
def paragraph(text):
"""Paragraph.
Args:
text (str): text to make into a paragraph.
Returns:
str: paragraph text.
"""
return text + '\r\n'
def sanitize(text):
"""Sanitize text.
This attempts to remove formatting that could be mistaken for markdown.
Args:
text (str): text to sanitise.
Returns:
str: sanitised text.
"""
if '```' in text:
text = text.replace('```', '(3xbacktick)')
if '|' in text:
text = text.replace('|', '(pipe)')
if '_' in text:
text = text.replace('_', r'\_')
return text
def table_header(columns=None):
"""Table header.
Creates markdown table headings.
Args:
text (tuple): column headings.
Returns:
str: markdown table header.
"""
line_1 = '|'
line_2 = '|'
for c in columns:
line_1 += ' ' + c + ' |'
line_2 += ' --- |'
line_1 += '\r\n'
line_2 += '\r\n'
return line_1 + line_2
def table_row(columns=None):
"""Table row.
Creates markdown table row.
Args:
text (tuple): column data.
Returns:
str: markdown table row.
"""
row = '|'
for c in columns:
row += ' ' + c + ' |'
row += '\r\n'
return row
def url(text, url_):
"""Url
Args:
text (str): text for url.
url (str): url for text.
Returns:
str: url.
"""
return '[' + text + '](' + url_ + ')'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.