content
stringlengths 7
1.05M
|
---|
print("********************************")
print("********** QUESTÃO 01 **********")
print("********************************")
print("******** RAUL BARCELOS *********")
print()
print("Olá mundo")
|
"""
quant_test
~~~~~~
The quant_test package - a Python package template project that is intended
to be used as a cookie-cutter for developing new Python packages.
"""
|
#zadanie 1
i=1
j=1
k=1
ciag=[1,1]
while len(ciag)<50:
k=i+j
j=i
i=k
ciag.append(k)
print(ciag)
#zadanie 2
wpisane=str(input("Proszę wpisać dowolne słowa po przecinku "))
zmienne=wpisane.split(",")
def funkcja(*args):
'''Funkcja sprawdza długość słów i usuwa te, które są za krótkie'''
lista=[]
lista2=[]
wartosc = int(input("Proszę wpisać jakąś wartość "))
for arg in args:
lista.append(arg)
dlugosc=len(arg)
if len(arg)>wartosc:
lista2.append(arg)
procenty=(len(lista2)/len(lista))*100
return procenty,lista,lista2
print(funkcja(zmienne))
#zadanie 3
liczby=list(input("Proszę wpisać liczby po przecinku: "))
unikalna_lista=[]
n=1
a=liczby[n]
unikalna_lista.append(liczby[0])
while n<len(liczby):
if liczby[n]!=unikalna_lista[n-1]:
unikalna_lista.append(a)
n+=1 |
def solution(absolutes, signs):
answer = 0
for i in range(len(absolutes)):
if signs[i] is True:
answer += int(absolutes[i])
else:
answer -= int(absolutes[i])
return answer
#1. for문 (len(absolutes)), if signs[i] is true: answer += absolutes[i], else: answer -= absolutes[i]
#2. sum(absolutes) |
num = int(input('Digite um número inteiro: '))
print(f'O número: {num}'
f'\nO antecessor: {num - 1}'
f'\nO sucessor: {num + 1}')
|
class Solution:
def maxArea(self, ls):
n = len(ls) - 1
v, left, right = [], 0, n
while 0 <= left < right <= n:
h = min(ls[left], ls[right])
v += [h * (right - left)]
while ls[left] <= h and left < right:
left += 1
while ls[right] <= h and left < right:
right -= 1
return max(v)
|
def _check_stamping_format(f):
if f.startswith("{") and f.endswith("}"):
return True
return False
def _resolve_stamp(ctx, string, output):
stamps = [ctx.info_file, ctx.version_file]
args = ctx.actions.args()
args.add_all(stamps, format_each = "--stamp-info-file=%s")
args.add(string, format = "--format=%s")
args.add(output, format = "--output=%s")
ctx.actions.run(
executable = ctx.executable._stamper,
arguments = [args],
inputs = stamps,
tools = [ctx.executable._stamper],
outputs = [output],
mnemonic = "Stamp",
)
utils = struct(
resolve_stamp = _resolve_stamp,
check_stamping_format = _check_stamping_format,
)
|
__author__ = "Rob MacKinnon <rome@villagertech.com>"
__package__ = "DOMObjects"
__name__ = "DOMObjects.schema"
__license__ = "MIT"
class DOMSchema(object):
""" @abstract Structure object for creating more advanced DOM trees
@params children [dict] Default structure of children
@params dictgroups [dict] Default structure of dictgroups
@params props [dict] Default structure of properties
@example Sample object
_schema = DOMSchema()
_schema.children=
_settings_schema.children = {
"sip": {},
"schedules": {},
"favorites": {
"dictgroups": ["sip", "http"]
}
}
"""
def __init__(self,
children: dict = {},
dictgroups: dict = {},
props: dict = {}):
""" @abstract Object initializer and bootstraps first object.
@params children [dict] Default structure of children
@params dictgroups [dict] Default structure of dictgroups
@params props [dict] Default structure of properties
@returns [DOMSchema] object
"""
self.dictgroups = dictgroups
self.children = children
self.props = props
@property
def keys(self) -> list:
""" @abstract Returns all top-level keys in schema
@returns [list] of keys
"""
_keys = list()
_keys.extend(self.children.keys())
_keys.extend(self.dictgroups.keys())
_keys.extend(self.props.keys())
return _keys
|
"""
1375. Substring With At Least K Distinct Characters
"""
class Solution:
"""
@param s: a string
@param k: an integer
@return: the number of substrings there are that contain at least k distinct characters
"""
def kDistinctCharacters(self, s, k):
# Write your code here
n = len(s)
left = 0
count = [0] * 256
distinct_count = 0
substring_count = 0
for right in range(n):
count[ord(s[right])] += 1
if count[ord(s[right])] == 1:
distinct_count += 1
while left <= right and distinct_count >= k:
substring_count += n - right
count[ord(s[left])] -= 1
if count[ord(s[left])] == 0:
distinct_count -= 1
left += 1
return substring_count
|
people = 20
cats = 30
dogs = 15
if people < cats:
print("고양이가 너무 많아요! 세상은 멸망합니다!")
if people > cats:
print("고양이가 많지 않아요! 세상은 지속됩니다!")
if people < dogs:
print("세상은 침에 젖습니다!")
if people > dogs:
print("세상은 말랐습니다!")
dogs += 5
if people >= dogs:
print("사람은 개보다 많거나 같습니다")
if people <= dogs:
print("사람은 개보다 적거나 같습니다.")
if people == dogs:
print("사람은 개입니다.")
|
# -- encoding:utf-8 -- #
'''
Crie uma variável com a string “ instituto de ciências matemáticas e de computação” e faça:
a. Concatene (adicione) uma outra string chamada “usp”
b. Concatene (adicione) uma outra informação: 2021
c. Verifique o tamanho da nova string (com as informações adicionadas das questões a e b), com referência a caracteres e espaços
d. Transforme a string inteiramente em maiúsculo
e. Transforme a string inteiramente em minúsculo
f. Retire o espaço que está no início da string e imprima a string
g. Substitua todas as letras ‘a’ por ‘x’
h. Separe a string em palavras únicas
i. Verifique quantas palavras existem na string
j. Separe a string por meio da palavra “de”
k. Verifique agora quantas palavras/frases foram formadas quando houve a separação pela palavra “de”
l. Junte as palavras que foram separadas (pode usar a separação resultante da questão h ou j)
m. Junte as palavras que foram separadas, mas agora separadas por uma barra invertida, não por espaços (pode usar a separação resultante da questão h ou j)
'''
texto = " instituto de ciências matemáticas e de computação"
#a)
texto = texto + " usp"
print(texto)
#b)
texto = texto + " 2021"
print(texto)
#c)
tamanho = len(texto)
print(tamanho)
#d)
print(texto.upper())
#e)
print(texto.lower())
#f)
print(texto[1:])
print(texto.strip())
#g)
print(texto.replace('a', 'x'))
#h
separar = texto.split()
print(separar)
#i)
print(separar)
#j)
separar2 = texto.split('de')
print(separar2)
#k)
print(len(separar2))
#l)
juntar = " ".join(separar)
print(juntar)
#m)
juntar2 = "/".join(separar)
print(juntar2)
|
def extract_stack_from_seat_line(seat_line: str) -> float or None:
# Seat 3: PokerPete24 (40518.00)
if 'will be allowed to play after the button' in seat_line:
return None
return float(seat_line.split(' (')[1].split(')')[0])
|
def infer_from_clause(table_names, graph, columns):
tables = list(table_names.keys())
if len(tables) == 1: # no JOINS needed - just return the simple "FROM" clause.
return f"FROM {tables[0]} "
else: # we have to deal with multiple tables - and find the shortest path between them
join_clauses, cross_join_clauses = generate_path_by_graph(graph, table_names, tables)
if len(_tables_in_join_clauses(join_clauses)) >= 3:
join_clauses = _find_and_remove_star_table(columns, join_clauses)
stringified_join_clauses = []
for idx, (start, start_alias, end, end_alias, entry_column, exit_column) in enumerate(join_clauses):
# the first case is kind of an exception case, as we need to write two tables, for example: "A AS T1 JOIN B AS T2 ON ....".
# All the following joins will only be "... JOIN T2 ON ...."
if idx == 0:
stringified_join_clauses.append(
f"{start} JOIN {end} ON {start_alias}.{entry_column} = {end_alias}.{exit_column}")
else:
stringified_join_clauses.append(f"JOIN {end} ON {start_alias}.{entry_column} = {end_alias}.{exit_column}")
# that's the cross-join exception cases. We have to add them for syntactical correctness, even though it will not result
# in a good query at execution.
for table, table_alias in cross_join_clauses:
if len(stringified_join_clauses) == 0:
stringified_join_clauses.append(f"{table}")
else:
stringified_join_clauses.append(f"JOIN {table}")
return f'FROM {" ".join(stringified_join_clauses)}'
def generate_path_by_graph(graph, table_names, tables):
join_clause = list()
cross_joins, tables_handled_by_cross_joins = _handle_standalone_tables(graph, table_names, tables)
tables_cleaned = [table for table in tables if table not in tables_handled_by_cross_joins]
idx = 0
edges = []
# We always deal with two tables at the time and try to find the shortest path between them. This might be over-simplified
# as there could be a more optimal path between all tables (see Steiner Graph), but practically it doesn't matter so much.
while idx < len(tables_cleaned) - 1:
start_table = tables_cleaned[idx]
end_table = tables_cleaned[idx + 1]
edges_for_this_path = graph.dijkstra(start_table, end_table)
if edges_for_this_path:
edges.extend(edges_for_this_path)
else:
raise Exception(f"We could not find a path between table '${start_table}' and '${end_table}'. This query can"
f"not work. Make sure you allow only questions in a fully connected schema!")
idx += 1
# now there might be duplicates - as parts of the path from A to C might be the same as from A to B.
# be aware that, as we only consider INNER JOINS, A <-> B is equal to B <-> A! So we also have to remove this edges.
edges_deduplicated = _deduplicate_edges(edges)
# now for each edge we now have to add both, the start table and the end table to the join_clause (including the PK/FK-columns).
for edge in edges_deduplicated:
if edge.start not in table_names:
table_names[edge.start] = edge.start.replace(' ', '_')
if edge.end not in table_names:
table_names[edge.end] = edge.end.replace(' ', '_')
join_clause.append((edge.start,
table_names[edge.start],
edge.end,
table_names[edge.end],
edge.entry_column,
edge.exit_column))
return join_clause, cross_joins
def _handle_standalone_tables(graph, table_names, tables):
join_clause = []
tables_handled = []
# there is a few rare cases of tables without connections to others - which will then obviously not be part of the graph.
# as we can't properly handle this cases, we just have to do a stupid cross-join with them
for table in tables:
if table not in graph.vertices:
join_clause.append((table, table_names[table]))
tables_handled.append(table)
remaining_tables = [t for t in table_names if t not in tables_handled]
# if there is only one table left after removing all the others, we can't use a graph anymore - so we need to do use a cross join as well.
if len(remaining_tables) == 1:
join_clause.append((remaining_tables[0], table_names[remaining_tables[0]]))
tables_handled.append(remaining_tables[0])
return join_clause, tables_handled
def _get_max_alias(table_names):
max_key = 1
for t, k in table_names.items():
_k = int(k[1:])
if _k > max_key:
max_key = _k
return max_key + 10
def _find_and_remove_star_table(columns, join_clause):
"""
Starting from 3 tables we have to deal with the "star-table" effect - a join with a joining table where we only wanna know e.g. the count(*) of the third table.
In that case we don't need to join the third table - we just do a count over the join with the joining table.
In general, the additional join is not an issue - but is seen as incorrect by the spider-evaluation and therefore we have to remove it.
Example:
SELECT T2.concert_name , T2.theme , count(*) FROM singer_in_concert AS T1 JOIN concert AS T2 ON T1.concert_id = T2.concert_id GROUP BY T2.concert_id ---> GOOD
SELECT T1.concert_Name, T1.Theme, count(*) FROM concert AS T1 JOIN singer_in_concert AS T3 JOIN singer AS T2 GROUP BY T1.concert_ID -----> BAD, REMOVE "singer" join.
"""
# unfortunately auto tuple unpacking doesn't work anymore in python 3, therefore this comment: a "column" contains the 3 elements "aggregator, "column name", "table".
star_tables = list(map(lambda column: column[2], filter(lambda column: column[1] == '*', columns)))
# remove duplicates
star_tables = list(set(star_tables))
assert len(star_tables) <= 1, "The case of having multiple star-joins is currently not supported (and not part of the spider-dataset)"
if len(star_tables) == 1:
star_table = star_tables[0]
# we need to make sure the table we try to remove is not used at any other place - e.g. in the SELECT or in the WHERE clause.
# only then we can safely remove it
if len(list(filter(lambda column: column[1] != '*' and column[2] == star_table, columns))) == 0:
# we only remove star-tables if they are the start or end table in the graph.
# remember, an join_clause tuple looks like this: (start, start_alias, end, end_alias, entry_column, exit_column)
start_edge = join_clause[0]
start_edge_from, _, start_edge_to, _, _, _ = start_edge
end_edge = join_clause[len(join_clause) - 1]
end_edge_from, _, end_edge_to, _, _, _ = end_edge
if start_edge_from == star_table:
if second_table_in_edge_is_availabe_elswhere(start_edge_to, join_clause[1:]):
return join_clause[1:]
if end_edge_to == star_table:
if second_table_in_edge_is_availabe_elswhere(end_edge_from, join_clause[:-1]):
return join_clause[:-1]
return join_clause
def second_table_in_edge_is_availabe_elswhere(second_table, remaining_edges):
"""
By removing an edge, we basically remove two tables. If there schema is a "normal" schema, where the edges are "A --> B", "B --> C"
this is not an issue.
We we though have a non-linear schema, like "A --> B", "A --> C" we can't just remove the first edge - we would loose B completely!
To avoid this we make sure the second table in the edge we plan to remove is available in another edge.
A schema where we have to deal with this issue is e.g. "flight_2", where two relations go from "flights" to "airports".
"""
for edge in remaining_edges:
start, _, end, _, _, _ = edge
if second_table == start or second_table == end:
return True
return False
def _deduplicate_edges(edges):
deduplicated = []
for e1 in edges:
found_match = False
for e2 in deduplicated:
# make sure two edges do not match - while paying no attention to the direction of the edge!
# more complex might make it necessary to also include the foreign key/primary key here, as you could theoretically have multiple relationships between two tables.
if (e1.start == e2.start and e1.end == e2.end) or (e1.start == e2.end and e1.end == e2.start):
found_match = True
if not found_match:
deduplicated.append(e1)
return deduplicated
def _tables_in_join_clauses(join_clauses):
unique_tables = set()
for clause in join_clauses:
start_table, _, end_table, _, _, _ = clause
unique_tables.add(start_table)
unique_tables.add(end_table)
return list(unique_tables)
|
"""70 · Binary Tree Level Order Traversal II"""
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A tree
@return: buttom-up level order a list of lists of integer
"""
def levelOrderBottom(self, root):
# write your code here
if not root:
return []
res = []
queue = collections.deque([root])
while queue:
temp = []
for _ in range(len(queue)):
node = queue.popleft()
temp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temp)
return res[::-1]
###
if not root:
return []
queue = [[root]]
index = 0
res = [[root.val]]
while index < len(queue):
curr_level = queue[index]
index += 1
next_level = []
next_level_vals = []
for node in curr_level:
if node.left:
next_level.append(node.left)
next_level_vals.append(node.left.val)
if node.right:
next_level.append(node.right)
next_level_vals.append(node.right.val)
if next_level:
queue.append(next_level)
res.append(next_level_vals)
return res[::-1]
|
def comment_dialog(data=None):
"""
Function takes in a JSON object, and uses the following format:
https://api.slack.com/dialogs
Returns created JSON object, then is sent back to Slack.
"""
text = ""
state = ""
project_holder = None
item_holder = None
if data is not None:
if data["type"] == "message_action":
text = data["message"]["text"] + "\n"
# get attachment images from the massage
if "attachments" in data["message"]:
text += "Attachments:\n"
for att in data["message"]["attachments"]:
text += att["title"] + ":\n"
if "image_url" in att:
text += att["image_url"] + "\n"
# get files from the massage
if "files" in data["message"]:
text += "Attach files:\n"
for file in data["message"]["files"]:
text += file["title"] + ":\n"
text += file["url_private"] + "\n"
if data["type"] == "interactive_message":
if data["callback_id"] == "bot_project":
label = data["original_message"]["attachments"][0]["fallback"]
project_holder = [
{
"label": label,
"value": data["actions"][0]["value"]
}
]
state = data["actions"][0]["value"]
elif data["callback_id"] == "bot_item":
label = data["original_message"]["attachments"][0]["fallback"]
item_holder = [
{
"label": label,
"value": data["actions"][0]["value"]
}
]
return {
"title": "JamaConnect - Comment",
"submit_label": "Submit",
"callback_id": "comment",
"elements": [
{
"label": "Search Projects:",
"type": "select",
"name": "project",
"optional": "true",
"data_source": "external",
"selected_options": project_holder
},
{
"label": "Project ID:",
"type": "select",
"name": "project_id",
"optional": "true",
"data_source": "external",
"selected_options": project_holder
},
{
"label": "Item ID or Name:",
"type": "select",
"name": "item",
"data_source": "external",
"min_query_length": 0,
"selected_options": item_holder
},
{
"type": "textarea",
"label": "Comment",
"name": "comment",
"value": text
}
],
"state": state
}
|
class Table:
# Constructor
# Defauls row and col to 0 if less than 0
def __init__(self, col_count, row_count, headers = [], border_size = 0):
self.col_count = col_count if col_count >= 0 else 0
self.row_count = row_count if row_count >= 0 else 0
self.border_size = border_size if border_size > 0 else 0
self.headers = headers
# Getters
def get_row_count(self):
return self.row_count
def get_border_size(self):
return self.border_size
def get_col_count(self):
return self.col_count
def get_headers(self):
return self.headers
# Setters
def set_row_count(self, count):
self.row_count = count
def set_border_size(self, new_border_size):
# Pre-Condition: must be between 0 and 5
if border_size > 5 or border_size < 0:
raise Exception("Border size must be a number between 0 and 5 inclusively")
self.border_size = new_border_size
def set_headers(self, headers):
# Pre-condition: headers length must be equal to column count
if len(headers) != self.col_count:
raise Exception("Headers amount must be the same as column count")
self.headers = headers
# Mutators
def add_rows(self, count):
# Pre-Condition: count to add must be greater than 0
if count < 1:
raise Exception("Number of rows to add must be greater than 0")
self.row_count += count
def delete_rows(self, count):
# Pre-Condition: count to remove must be greater than 0
if count < 1:
raise Exception("Number of rows to delete must be greater than 0")
new_total = self.row_count - count
self.row_count = new_total if count < self.row_count else 0
def add_cols(self, col_amt_to_add, headers = []):
if len(headers) > 0:
if len(headers) != col_amt_to_add:
raise Exception("Headers amount must be the same as column count to add")
self.add_headers(headers)
else:
if len(self.headers) > 0:
raise Exception("Please send through desired header names for columns")
self.col_count += col_amt_to_add
def delete_cols(self, col_amt_to_delete, headers = []):
if len(headers) > 0:
if len(headers) != col_amt_to_delete:
raise Exception("Headers amount must be the same as column count to delete")
self.delete_headers(headers)
else:
if len(self.headers) > 0:
raise Exception("Please send through desired header names for columns removal")
self.col_count -= col_amt_to_delete
def add_headers(self, headers):
self.headers = self.headers + headers
# Must add the columns if adding Headers
self.col_count = len(self.headers)
def delete_headers(self, headers):
print(headers)
print(self.headers)
for header in headers:
if header in self.headers:
self.headers.remove(header)
# Must decrement the column count if removing headers
self.col_count = len(self.headers)
def make_table(self):
reasonable_border = self.border_size > 0
added_border_element = ["<br>\n","<table border=\"" + str(border_size) +"\">\n"]
elements = added_border_element if reasonable_border else ["<br>\n","<table>\n"]
col_counter = 0
row_counter = 0
file = open("table.html", "a")
if len(self.headers) > 0:
elements.append("\t<tr>\n")
for n in self.headers:
elements.append("\t\t<th>" + n + "</th>\n")
elements.append("\t</tr>\n")
while row_counter < self.row_count:
elements.append("\t<tr>\n")
while col_counter < self.col_count:
elements.append("\t\t<td>test</td>\n")
col_counter += 1
elements.append("\t</tr>\n")
row_counter += 1
col_counter = 0
elements.append("</table>\n")
file.writelines(elements)
file.close()
col = 0
row = 0
header = ""
headers = []
border_size = -1
while col < 1 or col > 100:
col = input("How many columns do you want (1 to 100)? ")
col = int(col)
while row < 1 or col > 100:
row = input("How many rows do you want (1 to 100)? ")
row = int(row)
while header != "Y" and header != "N":
header = input("Do you want headers? Y/N ")
# If headers are wanted, give them names
if header == "Y":
header = True
for n in range(col):
headers.append(input("Header #" + str(n + 1) + ": "))
else:
header = False
while border_size < 0 or border_size > 5:
border_size = input("Enter a number for border size 1 to 5 ")
border_size = int(border_size)
# DEMOOOOOO
table = Table(col, row, headers, border_size)
table.make_table()
table.add_headers(["1", "2", "4"])
print("Here are your current headers: ")
print(table.get_headers())
print("Here is your current border size: ")
print(table.get_border_size())
table.make_table()
table.delete_cols(3, ["1", "2", "4"])
print("Here are your headers now: ")
print(table.get_headers())
print("Let's check your column count: ")
print(table.get_col_count())
# table.delete_cols(4) # should throw error
table.set_row_count(3)
table.add_rows(5)
print("Row count should be 8 because I just set it to 3 and added 5: ")
print(table.get_row_count())
|
class cluster(object):
def __init__(self,members=[]):
self.s=set(members)
def merge(self, other):
self.s.union(other.s)
return self
class clusterManager(object):
def __init__(self,clusters={}):
self.c=clusters
def merge(self, i, j):
self.c[i]=self.c[j]=self.c[i].merge(self.c[j])
def count(self):
return len(set(self.c.values()))
def zombieCluster(zombies):
cm=clusterManager(clusters={i:cluster(members=[i]) for i in xrange(len(zombies))})
for i,row in enumerate(zombies):
for j,column in enumerate(row):
if column == '1':
cm.merge(i,j)
return cm.count()
|
#backslash and new line ignored
print("one\
two\
three")
|
jogador = dict()
partidas = list()
jogador['nome'] = str(input('Nome do jogador: '))
tot = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
for c in range(0, tot):
partidas.append(int(input(f' Quantos gols na partida {c}? ')))
jogador['gols'] = partidas[:]
jogador['total'] = sum(partidas)
print(30*'-=')
print(jogador)
print(30*'-=')
for k, v in jogador.items():
print(f'O campo {k} tem o valor {v}')
print(30*'-=')
print(f'O jogador {jogador["nome"]} jogou {len(jogador["gols"])} partidas.')
for i, v in enumerate(jogador["gols"]):
print(f' => Na partida {i}, fez {v} gols.')
print(f'Foi um total de {jogador["total"]} gols.')
# Ou
# jogador = dict()
# partidas = list()
# p = tot = 0
# jogador['nome'] = str(input('Nome do Jogador: '))
# quant = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
# while p < quant:
# jogos = int(input(f' Quantos gols na partida {p}? '))
# partidas.append(jogos)
# tot += jogos
# p += 1
# jogador['gols'] = partidas
# jogador['total'] = tot
# print(30*'-=')
# print(jogador)
# print(30*'-=')
# for k, v in jogador.items():
# print(f'O campo {k} tem o valor {v}')
# print(30*'-=')
# print(f'O jogador {jogador["nome"]} jogou {quant} partidas.')
# for c, g in enumerate(partidas):
# print(f' => Na partida {c}, fez {g} gols.')
# print(f'Foi um total de {jogador["total"]} gols.') |
# modelo anterior - Enquanto cont até 10 for verdade, será repetido
cont = 1
while cont <= 10:
print(cont, ' ...', end='')
cont += 1
print('FIM')
# Usando o Enquanto VERDADE ele vai repetir para sempre, temos que colocar uma condição PARA=BREAK
n = s = 0
while True:
n = int(input('Digite um número: [Digite 999 para PARAR] '))
if n == 999:
break
s += n
print(f'A soma vale {s}') |
#skip.runas import Image; im = Image.open("Scribus.gif"); image_list = list(im.getdata()); cols, rows = im.size; res = range(len(image_list)); sobelFilter(image_list, res, cols, rows)
#runas cols = 100; rows = 100 ;image_list=[x%10+y%20 for x in xrange(cols) for y in xrange(rows)]; sobelFilter(image_list, cols, rows)
#bench cols = 1000; rows = 500 ;image_list=[x%10+y%20 for x in xrange(cols) for y in xrange(rows)]; sobelFilter(image_list, cols, rows)
#pythran export sobelFilter(int list, int, int)
def sobelFilter(original_image, cols, rows):
edge_image = range(len(original_image))
for i in xrange(rows):
edge_image[i * cols] = 255
edge_image[((i + 1) * cols) - 1] = 255
for i in xrange(1, cols - 1):
edge_image[i] = 255
edge_image[i + ((rows - 1) * cols)] = 255
for iy in xrange(1, rows - 1):
for ix in xrange(1, cols - 1):
sum_x = 0
sum_y = 0
sum = 0
#x gradient approximation
sum_x += original_image[ix - 1 + (iy - 1) * cols] * -1
sum_x += original_image[ix + (iy - 1) * cols] * -2
sum_x += original_image[ix + 1 + (iy - 1) * cols] * -1
sum_x += original_image[ix - 1 + (iy + 1) * cols] * 1
sum_x += original_image[ix + (iy + 1) * cols] * 2
sum_x += original_image[ix + 1 + (iy + 1) * cols] * 1
sum_x = min(255, max(0, sum_x))
#y gradient approximatio
sum_y += original_image[ix - 1 + (iy - 1) * cols] * 1
sum_y += original_image[ix + 1 + (iy - 1) * cols] * -1
sum_y += original_image[ix - 1 + (iy) * cols] * 2
sum_y += original_image[ix + 1 + (iy) * cols] * -2
sum_y += original_image[ix - 1 + (iy + 1) * cols] * 1
sum_y += original_image[ix + 1 + (iy + 1) * cols] * -1
sum_y = min(255, max(0, sum_y))
#GRADIENT MAGNITUDE APPROXIMATION
sum = abs(sum_x) + abs(sum_y)
#make edges black and background white
edge_image[ix + iy * cols] = 255 - (255 & sum)
return edge_image
|
#Ex004b
algo = (input('\033[34m''Digite algo: ''\033[m'))
print('São letras ou palavras?: \033[33m{}\033[m'.format(algo.isalpha()))
print('Está em maiúsculo?: \033[34m{}\033[m'.format(algo.isupper()))
print('Está em minúsculo?: \033[35m{}\033[m'.format(algo.islower()))
print('Está captalizada?: \033[36m{}\033[m'.format(algo.istitle()))
print('Só tem espaço?: \033[31m{}\033[m'.format(algo.isspace()))
print('É numérico?: \033[32m{}\033[m'.format(algo.isnumeric()))
print('xD')
|
# This file is only used to generate documentation
# VM class
class vm():
def getGPRState():
"""Obtain the current general purpose register state.
:returns: GPRState (an object containing the GPR state).
"""
pass
def getFPRState():
"""Obtain the current floating point register state.
:returns: FPRState (an object containing the FPR state).
"""
pass
def setGPRState(gprState):
"""Set the general purpose register state.
:param grpState: An object containing the GPR state.
"""
pass
def setFPRState(fprState):
"""Set the current floating point register state.
:param fprState: An object containing the FPR state
"""
pass
def run(start, stop):
"""Start the execution by the DBI from a given address (and stop when another is reached).
:param start: Address of the first instruction to execute.
:param stop: Stop the execution when this instruction is reached.
:returns: True if at least one block has been executed.
"""
pass
def call(function, args):
"""Call a function using the DBI (and its current state).
:param function: Address of the function start instruction.
:param args: The arguments as a list [arg0, arg1, arg2, ...].
:returns: (True, retValue) if at least one block has been executed.
"""
pass
def addCodeCB(pos, cbk, data):
"""Register a callback event for a specific instruction event.
:param pos: Relative position of the event callback (:py:const:`pyqbdi.PREINST` / :py:const:`pyqbdi.POSTINST`).
:param cbk: A function to be called back.
:param data: User defined data passed to the callback.
:returns: The id of the registered instrumentation (or :py:const:`pyqbdi.INVALID_EVENTID` in case of failure).
"""
pass
def addCodeAddrCB(address, pos, cbk, data):
"""Register a callback for when a specific address is executed.
:param address: Code address which will trigger the callback.
:param pos: Relative position of the event callback (:py:const:`pyqbdi.PREINST` / :py:const:`pyqbdi.POSTINST`).
:param cbk: A function to be called back.
:param data: User defined data passed to the callback.
:returns: The id of the registered instrumentation (or :py:const:`pyqbdi.INVALID_EVENTID` in case of failure).
"""
pass
def addCodeRangeCB(start, end, pos, cbk, data):
"""Register a callback for when a specific address range is executed.
:param start: Start of the address range which will trigger the callback.
:param end: End of the address range which will trigger the callback.
:param pos: Relative position of the event callback (:py:const:`pyqbdi.PREINST` / :py:const:`pyqbdi.POSTINST`).
:param cbk: A function to be called back.
:param data: User defined data passed to the callback.
:returns: The id of the registered instrumentation (or :py:const:`pyqbdi.INVALID_EVENTID` in case of failure).
"""
pass
def addMnemonicCB(mnemonic, pos, cbk, data):
"""Register a callback event if the instruction matches the mnemonic.
:param mnemonic: Mnemonic to match.
:param pos: Relative position of the event callback (:py:const:`pyqbdi.PREINST` / :py:const:`pyqbdi.POSTINST`).
:param cbk: A function to be called back.
:param data: User defined data passed to the callback.
:returns: The id of the registered instrumentation (or :py:const:`pyqbdi.INVALID_EVENTID` in case of failure).
"""
pass
def deleteInstrumentation(id):
"""Remove an instrumentation.
:param id: The id of the instrumentation to remove.
:returns: True if instrumentation has been removed.
"""
pass
def deleteAllInstrumentations():
"""Remove all the registered instrumentations.
"""
pass
def addMemAddrCB(address, type, cbk, data):
"""Add a virtual callback which is triggered for any memory access at a specific address matching the access type. Virtual callbacks are called via callback forwarding by a gate callback triggered on every memory access. This incurs a high performance cost.
:param address: Code address which will trigger the callback.
:param type: A mode bitfield: either :py:const:`pyqbdi.MEMORY_READ`, :py:const:`pyqbdi.MEMORY_WRITE` or both (:py:const:`pyqbdi.MEMORY_READ_WRITE`).
:param cbk: A function to be called back.
:param data: User defined data passed to the callback.
:returns: The id of the registered instrumentation (or :py:const:`pyqbdi.INVALID_EVENTID` in case of failure).
"""
pass
def addMemRangeCB(start, end, type, cbk, data):
"""Add a virtual callback which is triggered for any memory access in a specific address range matching the access type. Virtual callbacks are called via callback forwarding by a gate callback triggered on every memory access. This incurs a high performance cost.
:param start: Start of the address range which will trigger the callback.
:param end: End of the address range which will trigger the callback.
:param type: A mode bitfield: either :py:const:`pyqbdi.MEMORY_READ`, :py:const:`pyqbdi.MEMORY_WRITE` or both (:py:const:`pyqbdi.MEMORY_READ_WRITE`).
:param cbk: A function to be called back.
:param data: User defined data passed to the callback.
:returns: The id of the registered instrumentation (or :py:const:`pyqbdi.INVALID_EVENTID` in case of failure).
"""
pass
def addMemAccessCB(type, cbk, data):
"""Register a callback event for every memory access matching the type bitfield made by an instruction.
:param type: A mode bitfield: either :py:const:`pyqbdi.MEMORY_READ`, :py:const:`pyqbdi.MEMORY_WRITE` or both (:py:const:`pyqbdi.MEMORY_READ_WRITE`).
:param cbk: A function to be called back.
:param data: User defined data passed to the callback.
:returns: The id of the registered instrumentation (or :py:const:`pyqbdi.INVALID_EVENTID` in case of failure).
"""
pass
def recordMemoryAccess(type):
"""Add instrumentation rules to log memory access using inline instrumentation and instruction shadows.
:param type: Memory mode bitfield to activate the logging for: either :py:const:`pyqbdi.MEMORY_READ`, :py:const:`pyqbdi.MEMORY_WRITE` or both (:py:const:`pyqbdi.MEMORY_READ_WRITE`).
:returns: True if inline memory logging is supported, False if not or in case of error.
"""
pass
def getInstAnalysis(type):
""" Obtain the analysis of an instruction metadata. Analysis results are cached in the VM. The validity of the returned object is only guaranteed until the end of the callback, else a deepcopy of the object is required.
:param type: Properties to retrieve during analysis (pyqbdi.ANALYSIS_INSTRUCTION, pyqbdi.ANALYSIS_DISASSEMBLY, pyqbdi.ANALYSIS_OPERANDS, pyqbdi.ANALYSIS_SYMBOL).
:returns: A :py:class:`InstAnalysis` object containing the analysis result.
"""
pass
def getInstMemoryAccess():
"""Obtain the memory accesses made by the last executed instruction.
:returns: A list of memory accesses (:py:class:`MemoryAccess`) made by the instruction.
"""
pass
def getBBMemoryAccess():
"""Obtain the memory accesses made by the last executed basic block.
:returns: A list of memory accesses (:py:class:`MemoryAccess`) made by the basic block.
"""
pass
def precacheBasicBlock(pc):
"""Pre-cache a known basic block
:param pc: Start address of a basic block
:returns: True if basic block has been inserted in cache.
"""
pass
def clearCache(start, end):
"""Clear a specific address range from the translation cache.
:param start: Start of the address range to clear from the cache.
:param end: End of the address range to clear from the cache.
"""
pass
def clearAllCache():
"""Clear the entire translation cache.
"""
pass
def addVMEventCB(mask, cbk, data):
"""Register a callback event for a specific VM event.
:param mask: A mask of VM event type which will trigger the callback.
:param cbk: A function to be called back.
:param data: User defined data passed to the callback.
:returns: The id of the registered instrumentation (or :py:const:`pyqbdi.INVALID_EVENTID` in case of failure).
"""
pass
def addInstrumentedModule(name):
"""Add the executable address ranges of a module to the set of instrumented address ranges.
:param name: The module's name.
:returns: True if at least one range was added to the instrumented ranges.
"""
pass
def addInstrumentedModuleFromAddr(addr):
""" Add the executable address ranges of a module to the set of instrumented address ranges using an address belonging to the module.
:param addr: An address contained by module's range.
:returns: True if at least one range was added to the instrumented ranges.
"""
pass
def addInstrumentedRange(start, end):
"""Add an address range to the set of instrumented address ranges.
:param start: Start address of the range (included).
:param end: End address of the range (excluded).
"""
pass
def instrumentAllExecutableMaps():
"""Adds all the executable memory maps to the instrumented range set.
:returns: True if at least one range was added to the instrumented ranges.
"""
pass
def removeAllInstrumentedRanges():
"""Remove all instrumented ranges.
"""
pass
def removeInstrumentedModule(name):
"""Remove the executable address ranges of a module from the set of instrumented address ranges.
:param name: The module's name.
:returns: True if at least one range was removed from the instrumented ranges.
"""
pass
def removeInstrumentedModuleFromAddr(addr):
"""Remove the executable address ranges of a module from the set of instrumented address ranges using an address belonging to the module.
:param addr: An address contained by module's range.
:returns: True if at least one range was removed from the instrumented ranges.
"""
pass
def removeInstrumentedRange(start, end):
"""Remove an address range from the set of instrumented address ranges.
:param start: Start address of the range (included).
:param end: End address of the range (excluded).
"""
pass
# PyQBDI module functions
def alignedAlloc(size, align):
"""Allocate a block of memory of a specified sized with an aligned base address.
:param size: Allocation size in bytes.
:param align: Base address alignement in bytes.
:returns: Pointer to the allocated memory (as a long) or NULL in case an error was encountered.
"""
pass
def alignedFree():
"""
"""
pass
def allocateVirtualStack(ctx, stackSize):
"""Allocate a new stack and setup the GPRState accordingly.
The allocated stack needs to be freed with alignedFree().
:param ctx: GPRState which will be setup to use the new stack.
:param stackSize: Size of the stack to be allocated.
:returns: A tuple (bool, stack) where 'bool' is true if stack allocation was successfull. And 'stack' the newly allocated stack pointer.
"""
pass
def simulateCall(ctx, returnAddress, args):
"""Simulate a call by modifying the stack and registers accordingly.
:param ctx: GPRState where the simulated call will be setup. The state needs to point to a valid stack for example setup with allocateVirtualStack().
:param returnAddress: Return address of the call to simulate.
:param args: A list of arguments.
"""
pass
def getModuleNames():
""" Get a list of all the module names loaded in the process memory.
:returns: A list of strings, each one containing the name of a loaded module.
"""
pass
def getCurrentProcessMaps():
""" Get a list of all the memory maps (regions) of the current process.
:returns: A list of :py:class:`MemoryMap` object.
"""
pass
def readMemory(address, size):
"""Read a memory content from a base address.
:param address: Base address
:param size: Read size
:returns: Bytes of content.
.. warning::
This API is hazardous as the whole process memory can be read.
"""
pass
def writeMemory(address, bytes):
"""Write a memory content to a base address.
:param address: Base address
:param bytes: Memory content
.. warning::
This API is hazardous as the whole process memory can be written.
"""
pass
def decodeFloat(val):
""" Decode a float stored as a long.
:param val: Long value.
"""
pass
def encodeFloat(val):
"""Encode a float as a long.
:param val: Float value
"""
pass
# Various objects
class MemoryMap:
""" Map of a memory area (region).
"""
range = (0, 0xffff)
""" A range of memory (region), delimited between a start and an (excluded) end address. """
permission = 0
""" Region access rights (PF_READ, PF_WRITE, PF_EXEC). """
name = ""
""" Region name (useful when a region is mapping a module). """
class InstAnalysis:
""" Object containing analysis results of an instruction provided by the VM.
"""
mnemonic = ""
""" LLVM mnemonic (warning: None if !ANALYSIS_INSTRUCTION) """
address = 0
""" Instruction address """
instSize = 0
""" Instruction size (in bytes) """
affectControlFlow = False
""" true if instruction affects control flow """
isBranch = False
""" true if instruction acts like a 'jump' """
isCall = False
""" true if instruction acts like a 'call' """
isReturn = False
""" true if instruction acts like a 'return' """
isCompare = False
""" true if instruction is a comparison """
isPredicable = False
""" true if instruction contains a predicate (~is conditional) """
mayLoad = False
""" true if instruction 'may' load data from memory """
mayStore = False
""" true if instruction 'may' store data to memory """
disassembly = ""
""" Instruction disassembly (warning: None if !ANALYSIS_DISASSEMBLY) """
numOperands = 0
""" Number of operands used by the instruction """
operands = []
""" A list of :py:class:`OperandAnalysis` objects.
(warning: empty if !ANALYSIS_OPERANDS) """
symbol = ""
""" Instruction symbol (warning: None if !ANALYSIS_SYMBOL or not found) """
symbolOffset = 0
""" Instruction symbol offset """
module = ""
""" Instruction module name (warning: None if !ANALYSIS_SYMBOL or not found) """
class OperandAnalysis:
""" Object containing analysis results of an operand provided by the VM.
"""
# Common fields
type = 0
""" Operand type (pyqbdi.OPERAND_IMM, pyqbdi.OPERAND_REG, pyqbdi.OPERAND_PRED) """
value = 0
""" Operand value (if immediate), or register Id """
size = 0
""" Operand size (in bytes) """
# Register specific fields
regOff = 0
""" Sub-register offset in register (in bits) """
regCtxIdx = 0
""" Register index in VM state """
regName = ""
""" Register name """
regAccess = 0
""" Register access type (pyqbdi.REGISTER_READ, pyqbdi.REGISTER_WRITE, pyqbdi.REGISTER_READ_WRITE) """
class VMState:
""" Object describing the current VM state.
"""
event = 0
""" The event(s) which triggered the callback (must be checked using a mask: event & pyqbdi.BASIC_BLOCK_ENTRY). """
basicBlockStart = 0
""" The current basic block start address which can also be the execution transfer destination. """
basicBlockEnd = 0
""" The current basic block end address which can also be the execution transfer destination. """
sequenceStart = 0
""" The current sequence start address which can also be the execution transfer destination. """
sequenceEnd = 0
""" The current sequence end address which can also be the execution transfer destination. """
class MemoryAccess:
""" Describe a memory access
"""
instAddress = 0
""" Address of instruction making the access. """
accessAddress = 0
""" Address of accessed memory. """
value = 0
""" Value read from / written to memory. """
size = 0
""" Size of memory access (in bytes). """
type = 0
""" Memory access type (pyqbdi.MEMORY_READ, pyqbdi.MEMORY_WRITE, pyqbdi.MEMORY_READ_WRITE). """
GPRState = None
""" GPRState object, a binding to :cpp:type:`QBDI::GPRState`
"""
FPRState = None
""" FPRState object, a binding to :cpp:type:`QBDI::FPRState`
"""
|
# -*- coding: utf-8 -*-
"""Scrapy settings."""
BOT_NAME = 'krkbipscraper'
SPIDER_MODULES = ['krkbipscraper.spiders']
NEWSPIDER_MODULE = 'krkbipscraper.spiders'
ITEM_PIPELINES = ['krkbipscraper.pipelines.JsonWriterPipeline']
|
def sum_digit(n):
total = 0
while n != 0:
total += n % 10
n /= 10
return total
def factorial(n):
if n <= 0:
return 1
return n * factorial(n - 1)
|
# Copyright (c) 2020
# Author: xiaoweixiang
"""Contains purely network-related utilities.
"""
|
class Global:
sand_box = True
app_key = None
# your secret
secret = None
callback_url = None
server_url = None
log = None
def __init__(self, config):
Global.sand_box = config.get_env()
Global.app_key = config.get_app_key()
Global.secret = config.get_secret()
Global.callback_url = config.get_callback_url()
Global.log = config.get_log()
@staticmethod
def get_env():
return Global.sand_box
@staticmethod
def get_app_key():
return Global.app_key
@staticmethod
def get_secret():
return Global.secret
@staticmethod
def get_callback_url():
return Global.callback_url
@staticmethod
def get_log():
return Global.log
@staticmethod
def get_server_url():
return Global.server_url
@staticmethod
def get_access_token_url():
return Global.get_server_url() + "/token"
@staticmethod
def get_api_server_url():
return Global.get_server_url() + "/api/v1/"
@staticmethod
def get_authorize_url():
return Global.get_server_url() + "/authorize" |
DEFAULT_KUBE_VERSION=1.14
KUBE_VERSION="kubeVersion"
USER_ID="userId"
DEFAULT_USER_ID=1
CLUSTER_NAME="clusterName"
CLUSTER_MASTER_IP="masterHostIP"
CLUSTER_WORKER_IP_LIST="workerIPList"
FRAMEWORK_TYPE= "frameworkType"
FRAMEWORK_VERSION="frameworkVersion"
FRAMEWORK_RESOURCES="frameworkResources"
FRAMEWORK_VOLUME_SIZE= "storageVolumeSizegb"
FRAMEWORK_ASSIGN_DPU_TYPE= "dpuType"
FRAMEWORK_ASSIGN_DPU_COUNT= "count"
FRAMEWORK_INSTANCE_COUNT="instanceCount"
FRAMEWORK_SPEC="spec"
FRAMEWORK_IMAGE_NAME="imageName"
FRAMEWORK_DPU_ID="dpuId"
FRAMEWORK_DPU_COUNT="count"
CLUSTER_ID="clusterId"
FRAMEWORK_DEFAULT_PVC="/home/user/"
DEFAULT_FRAMEWORK_TYPE="POLYAXON"
DEFAULT_FRAMEWORK_VERSION="0.4.4"
POLYAXON_TEMPLATE="templates/polyaxon_config"
POLYAXON_CONFIG_FILE="/home/user/polyaxonConfig.yaml"
POLYAXON_DEFAULT_NAMESPACE="polyaxon"
TENSORFLOW_TEMPLATE="templates/tensorflow-gpu"
DEFAULT_PATH="/home/user/"
##########Cluster Info####################
POD_IP="podIp"
POD_STATUS="podStatus"
POD_HOST_IP="hostIp"
##########End Of Cluster Info####################
PVC_MAX_ITERATIONS=50
SLEEP_TIME=5
GLUSTER_DEFAULT_MOUNT_PATH="/volume"
CONTAINER_VOLUME_PREFIX="volume"
MAX_RETRY_FOR_CLUSTER_FORM=10
##############Cluster Related ####################33
CLUSTER_NODE_READY_COUNT=60
CLUSTER_NODE_READY_SLEEP=6
CLUSTER_NODE_NAME_PREFIX="worker"
NO_OF_GPUS_IN_GK210_K80=2
POLYAXON_NODE_PORT_RANGE_START=30000
POLYAXON_NODE_PORT_RANGE_END=32767
DEFAULT_CIDR="10.244.0.0/16"
GFS_STORAGE_CLASS="glusterfs"
GFS_STORAGE_REPLICATION="replicate:2"
HEKETI_REST_URL="http://10.138.0.2:8080"
DEFAULT_VOLUME_MOUNT_PATH="/volume"
GLUSTER_DEFAULT_REP_FACTOR=2
POLYAXON_DEFAULT_HTTP_PORT=80
POLYAXON_DEFAULT_WS_PORT=1337
SUCCESS_MESSAGE_STATUS="SUCCESS"
ERROR_MESSAGE_STATUS="SUCCESS"
ROLE="role"
IP_ADDRESS="ipAddress"
INTERNAL_IP_ADDRESS="internalIpAddress"
ADD_NODE_USER_ID="hostUserId"
ADD_NODE_PASSWORD="password"
####Polyaxon GetClusterInfo###
QUOTA_NAME="quotaName"
QUOTA_USED="used"
QUOTA_LIMIT="limit"
DEFAULT_QUOTA="default"
VOLUME_NAME="volumeName"
MOUNT_PATH_IN_POD="volumePodMountPath"
VOLUME_TOTAL_SIZE="totalSize"
VOLUME_FREE="free"
NVIDIA_GPU_RESOURCE_NAME="requests.nvidia.com/gpu"
EXECUTOR="executor"
MASTER_IP="masterIP"
GPU_COUNT="gpuCount"
NAME="name"
KUBE_CLUSTER_INFO="kubeClusterInfo"
ML_CLUSTER_INFO="mlClusterInfo"
POLYAXON_DEFAULT_USER_ID="root"
POLYAXON_DEFAULT_PASSWORD="rootpassword"
POLYAXON_USER_ID="polyaxonUserId"
POLYAXON_PASSWORD="polyaxonPassword"
DEFAULT_DATASET_VOLUME_NAME="vol_f37253d9f0f35868f8e3a1d63e5b1915"
DEFAULT_DATASET_MOUNT_PATH="/home/user/dataset"
DEFAULT_CLUSTER_VOLUME_MOUNT_PATH="/home/user/volume"
DEFAULT_GLUSTER_SERVER="10.138.0.2"
DEFAULT_DATASET_VOLUME_SIZE="10Gi"
CLUSTER_VOLUME_MOUNT_PATH="volumeHostMountPath"
DATASET_VOLUME_MOUNT_POINT="dataSetVolumemountPointOnHost"
DATASET_VOLUME_MOUNT_PATH_IN_POD_REST= "volumeDataSetPodMountPoint"
DATASET_VOLUME_MOUNT_PATH_IN_POD="/dataset"
DYNAMIC_GLUSTERFS_ENDPOINT_STARTS_WITH="glusterfs-dynamic-" |
# Python3
def makeArrayConsecutive2(statues):
return (max(statues) - min(statues) + 1) - len(statues)
|
"""from django.contrib import admin
from .models import DemoModel
admin.site.register(DemoModel)"""
|
'''
>List of functions
1. contain(value,limit) - contains a value between 0 to limit
'''
def contain(value,limit):
if value<0:
return value+limit
elif value>=limit:
return value-limit
else:
return value |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# from unittest import mock
# from datakit_dworld.push import Push
def test_push(capsys):
"""Sample pytest test function with a built-in pytest fixture as an argument.
"""
# cmd = Greeting(None, None, cmd_name='dworld push')
# parsed_args = mock.Mock()
# parsed_args.greeting = 'Hello world!'
# cmd.run(parsed_args)
# out, err = capsys.readouterr()
# assert 'Hello world!' in out
|
# ┌─────────────────────────────────────────────────────────────────────────────────────
# │ PYOB SET LABEL MIXIN
# └─────────────────────────────────────────────────────────────────────────────────────
class PyObSetLabelMixin:
"""A mixin class for PyOb set label methods"""
# ┌─────────────────────────────────────────────────────────────────────────────────
# │ LABEL SINGULAR
# └─────────────────────────────────────────────────────────────────────────────────
@property
def label_singular(self):
"""Returns a singular label for the PyOb set"""
# Determine if PyOb set is mixed
is_mixed = self.count() > 1 and self._PyObClass is None
# Get PyOb label
ob_label = "Mixed" if is_mixed else self.ob_label_singular
# Return singular label
return self.__class__.__name__.replace("Ob", ob_label + " ")
# ┌─────────────────────────────────────────────────────────────────────────────────
# │ LABEL PLURAL
# └─────────────────────────────────────────────────────────────────────────────────
@property
def label_plural(self):
"""Returns a plural label for the PyOb set"""
# Return plural label
return self.label_singular + "s"
# ┌─────────────────────────────────────────────────────────────────────────────────
# │ OB LABEL SINGULAR
# └─────────────────────────────────────────────────────────────────────────────────
@property
def ob_label_singular(self):
"""Returns a singular label based on related PyOb if any"""
# Return singular label
return (self._PyObClass and self._PyObClass.label_singular) or "Ob"
# ┌─────────────────────────────────────────────────────────────────────────────────
# │ OB LABEL PLURAL
# └─────────────────────────────────────────────────────────────────────────────────
@property
def ob_label_plural(self):
"""Returns a plural label based on related object if any"""
# Return plural label
return (self._PyObClass and self._PyObClass.label_plural) or "Obs"
|
print('Olá, Mundo!')
print(7+4)
print('7'+'4')
print('Olá', 5)
# Toda variável é um objeto
# Um objeto é mais do que uma variável
nome = 'Gabriel'
idade = 30
peso = 79
print(nome,idade,peso)
nome = input('>>> Nome ')
idade = input('>>> Idade ')
peso = input('>>> Peso ')
print(nome,idade,peso)
print(f'Nome:{nome} ,Idade:{idade} ,Peso:{peso}')
|
# -*- coding: utf-8 -*-
"""
.. module:: pytfa
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
""" Simulation types """
QSSA = 'qssa'
TQSSA = 'tqssa'
MCA = 'mca'
ODE = 'ode'
ELEMENTARY = 'elementary'
""" Jacobian Types"""
NUMERICAL = 'numerical'
SYMBOLIC = 'symbolic'
""" MCA Types """
NET = 'net'
SPLIT = 'split'
""" Item types """
PARAMETER = 'parameter'
VARIABLE = 'variable'
""" Units """
KCAL = 'kcal'
KJ = 'kJ'
JOULE = 'JOULE'
""" OTHER """
WATER_FORMULA = 'H2O'
|
class URLShortener:
def __init__(self):
self.id_counter = 0
self.links = {}
def getURL(self, short_id):
return self.links.get(short_id)
def shorten(self, url):
short_id = self.getNextId()
self.links.update({short_id: url})
return short_id
def getNextId(self):
self.id_counter += 1
# Id got from a URL is type str anyway so it is easiest to just use
# type str everywhere after this point.
return str(self.id_counter)
|
print ('hello world')
print ('hey i did something')
print ('what happens if i do a ;');
print ('apparently nothing')
|
class Bank:
def __init__(self):
self.__agencies = [1111, 2222, 3333]
self.__costumers = []
self.__accounts = []
def insert_costumers(self, costumer):
self.__costumers.append(costumer)
def insert_accounts(self, account):
self.__accounts.append(account)
def authenticate(self, costumer):
if costumer not in self.__costumers:
return None
|
'''
Python program to determine which triples sum to zero from a given list of lists.
Input: [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]]
Output:
[False, True, True, False, True]
Input: [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]]
Output:
[True, True, False, False, False]
'''
#License: https://bit.ly/3oLErEI
def test(nums):
return [sum(t)==0 for t in nums]
nums = [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]]
print("Original list of lists:",nums)
print("Determine which triples sum to zero:")
print(test(nums))
nums = [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]]
print("\nOriginal list of lists:",nums)
print("Determine which triples sum to zero:")
print(test(nums))
|
#
# @lc app=leetcode.cn id=155 lang=python3
#
# [155] 最小栈
#
# https://leetcode-cn.com/problems/min-stack/description/
#
# algorithms
# Easy (47.45%)
# Total Accepted: 19.4K
# Total Submissions: 40.3K
# Testcase Example: '["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]'
#
# 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
#
#
# push(x) -- 将元素 x 推入栈中。
# pop() -- 删除栈顶的元素。
# top() -- 获取栈顶元素。
# getMin() -- 检索栈中的最小元素。
#
#
# 示例:
#
# MinStack minStack = new MinStack();
# minStack.push(-2);
# minStack.push(0);
# minStack.push(-3);
# minStack.getMin(); --> 返回 -3.
# minStack.pop();
# minStack.top(); --> 返回 0.
# minStack.getMin(); --> 返回 -2.
#
#
#
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self._min = None
self._stack = []
def push(self, x: int) -> None:
if self._min is None:
self._min = x
else:
self._min = min(self._min, x)
self._stack.append(x)
def pop(self) -> None:
self._stack.pop(-1)
if self._stack:
self._min = min(self._stack)
else:
self._min = None
def top(self) -> int:
return self._stack[-1]
def getMin(self) -> int:
return self._min
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
class AliasNotFound(Exception):
def __init__(self, alias):
self.alias = alias
class AliasAlreadyExists(Exception):
def __init__(self, alias):
self.alias = alias
class UnexpectedServerResponse(Exception):
def __init__(self, response):
self.response = response
|
def differentiate(fxn: str) -> str:
if fxn == "x":
return "1"
dividedFxn = getFirstLevel(fxn)
coeffOrTrig: str = dividedFxn[0]
exponent: str = dividedFxn[2]
insideParentheses: str = dividedFxn[1]
if coeffOrTrig.isalpha():
ans = computeTrig(coeffOrTrig, insideParentheses)
ans = ans + "*" + differentiate(insideParentheses)
if ans.endswith("*1"):
ans = list(ans)
ans.pop()
ans.pop()
ans = "".join(ans)
return ans
if len(exponent) != 0:
if len(coeffOrTrig) != 0 and coeffOrTrig.isnumeric():
ans = computeExpWithCoeff(coeffOrTrig, insideParentheses, exponent)
ans = ans + "*" + differentiate(insideParentheses)
ans = ans.replace("^1", "")
if ans.endswith("*1"):
ans = list(ans)
ans.pop()
ans.pop()
ans = "".join(ans)
return ans
else:
ans = computeExpWithoutCoeff(insideParentheses, exponent)
ans = ans + "*" + differentiate(insideParentheses)
ans = ans.replace("^1", "")
if ans.endswith("*1"):
ans = list(ans)
ans.pop()
ans.pop()
ans = "".join(ans)
return ans
if len(coeffOrTrig) == 0 and len(exponent) == 0:
ans = "1" + "*" + differentiate(insideParentheses)
ans = ans.replace("^1", "")
if ans.endswith("*1"):
ans = list(ans)
ans.pop()
ans.pop()
ans = "".join(ans)
return ans
def getFirstLevel(function: str) -> list:
indexOfOpen = function.find("(")
indexOfClose = function.rfind(")")
function = list(function)
function[indexOfOpen] = "|"
function[indexOfClose] = "|"
function = "".join(function)
assert function.count("|") == 2, "| != 2" # assert division by 2
return function.split("|")
def computeTrig(trig: str, inside: str) -> str:
if trig == "sin":
return "(cos({}))".format(inside)
elif trig == "cos":
return "(-sin({}))".format(inside)
elif trig == "tan":
return "(sec({})^2)".format(inside)
if trig == "sec":
return "(sec({})tan({}))".format(inside, inside)
if trig == "csc":
return "(-csc({})cot({}))".format(inside, inside)
if trig == "cot":
return "(-csc({})^2)".format(inside)
def computeExpWithCoeff(coeff: str, inside: str, exp: str) -> str:
cf = int(coeff)
expnt = int(exp.replace("^", ""))
cf = cf * expnt
expnt -= 1
return "{}({})^{}".format(cf, inside, expnt)
def computeExpWithoutCoeff(inside: str, exp: str) -> str:
expnt = int(exp.replace("^", ""))
cf = int(exp.replace("^", ""))
expnt -= 1
return "{}({})^{}".format(cf, inside, expnt)
OTHER_RECURSIVE_FUNCTIONS = [
"getFirstLevel",
"computeTrig",
"computeExpWithCoeff",
"computeExpWithoutCoeff",
]
print(differentiate("3(x)^3"))
|
class register:
plugin_dict = {}
plugin_name = []
@classmethod
def register(cls, plugin_name):
def wrapper(plugin):
cls.plugin_dict[plugin_name] = plugin
return plugin
return wrapper |
# num1 = input("Digite um número inteiro: ")
#
#
# try:
#
# if num1.isnumeric() :
# num1 = int(num1)
# if (num1 % 2) == 0 :
# print("Você digitou um número par.")
# elif (num1 % 2) != 0:
# print("Você digitou um número ímpar.")
# else:
# print("Você não digitou um número válido.")
# else:
# print("Você não digitou um número inteiro.")
# except:
# print("Você não digitou um número.")
###################################################################################################################################
#hora_atual = input("Qual o horário atual? ")
###################################################################################################################################
nome = input("Por favor, digite seu primeiro nome: ")
try:
if nome.isnumeric():
print("Você não digitou um nome válido.")
else:
if len(nome) <= 4:
print("Seu nome é curto.")
elif (len(nome) == 5) or (len(nome) == 6):
print("Seu nome é normal.")
elif len(nome) > 6:
print("Seu nome é muito grande.")
else:
print("Você não digitou um nome válido.1")
except:
print("Você não digitou um nome válido.")
|
#B
def average(As :list) -> float:
return float(sum(As)/len(As))
def main():
# input
As = list(map(int, input().split()))
# compute
# output
print(average(As))
if __name__ == '__main__':
main()
|
if __name__ == '__main__':
pass
RESULT = 1
# DO NOT REMOVE NEXT LINE - KEEP IT INTENTIONALLY LAST
assert RESULT == 1, ''
|
class ToolNameAPI:
thing = 'thing'
toolname_tool = 'example'
tln = ToolNameAPI()
the_repo = "reponame"
author = "authorname"
profile = "authorprofile" |
class BaseFunction:
def __init__(self, name, n_calls, internal_ns):
self._name = name
self._n_calls = n_calls
self._internal_ns = internal_ns
@property
def name(self):
return self._name
@property
def n_calls(self):
return self._n_calls
@property
def internal_ns(self):
return self._internal_ns
class Lines:
def __init__(self, line_str, n_calls, internal, external):
self._line_str = line_str
self._n_calls = n_calls
self._internal = internal
self._external = external
@property
def text(self):
return self._line_str
@property
def n_calls(self):
return self._n_calls
@property
def internal(self):
return self._internal
@property
def external(self):
return self._external
@property
def total(self):
return self.internal + self.external
class Function(BaseFunction):
def __init__(self, name, lines, n_calls, internal_ns):
self._name = name
self._lines = lines
self._n_calls = n_calls
self._internal_ns = internal_ns
@property
def lines(self):
return self._lines
@property
def name(self):
return self._name
@property
def n_calls(self):
return self._n_calls
@property
def internal_ns(self):
return self._internal_ns
@property
def total(self):
tot = 0
for line in self.lines:
tot += line.total
return tot + self.internal_ns
class Profile:
@staticmethod
def from_data(data):
profile = Profile()
profile._functions = []
for key, fdata in data['functions'].items():
lines = []
for line in fdata['lines']:
line = Lines(line['line_str'], line['n_calls'],
line['internal_ns'], line['external_ns'])
lines.append(line)
func = Function(lines=lines, name=fdata['name'],
n_calls=fdata['n_calls'],
internal_ns=fdata['internal_ns'])
profile._functions.append(func)
return profile
@property
def functions(self):
return self._functions
|
"""The PWM channel to use."""
CHANNEL0 = 0
"""Channel zero."""
CHANNEL1 = 1
"""Channel one."""
|
S = str(input())
if S[0]==S[1] or S[1]==S[2] or S[2]==S[3]:
print("Bad")
else:
print("Good") |
def main():
squareSum = 0 #(1 + 2)^2 square of the sums
sumSquare = 0 #1^2 + 2^2 sum of the squares
for i in range(1, 101):
sumSquare += i ** 2
squareSum += i
squareSum = squareSum ** 2
print(str(squareSum - sumSquare))
if __name__ == '__main__':
main()
|
def find_space(board):
for i in range(0,9):
for j in range(0,9):
if board[i][j]==0:
return (i,j)
return None
def check(board,num,r,c):
for i in range(0,9):
if board[r][i]==num and c!=i:
return False
for i in range(0,9):
if board[i][c]==num and r!=i:
return False
x=r//3
y=c//3
for i in range(x*3,x*3+3):
for j in range(y*3,y*3+3):
if board[i][j]==num and r!=i and c!=j:
return False
return True
def enter_datas(board):
for i in range(1,10):
print("Enter the Datas in Row ",i)
x=[int(i) for i in input().split()]
board.append(x)
def show(board):
for i in range(0,9):
for j in range(0,9):
if j==2 or j==5:
print(board[i][j]," | ",end="")
else:
print(board[i][j],end=" ")
if i==2 or i==5:
print("\n-----------------------\n")
else:
print("\n")
def solve(board):
x=find_space(board)
if not x:
return True
else:
r,c=x
for i in range(1,10):
if check(board,i,r,c):
board[r][c]=i
if solve(board):
return True
board[r][c]=0
return False
board=[]
enter_datas(board)
show(board)
solve(board)
print("\n\n")
show(board)
'''
Enter the Datas in a Row
7 8 0 4 0 0 1 2 0
Enter the Datas in a Row
6 0 0 0 7 5 0 0 9
Enter the Datas in a Row
0 0 0 6 0 1 0 7 8
Enter the Datas in a Row
0 0 7 0 4 0 2 6 0
Enter the Datas in a Row
0 0 1 0 5 0 9 3 0
Enter the Datas in a Row
9 0 4 0 6 0 0 0 5
Enter the Datas in a Row
0 7 0 3 0 0 0 1 2
Enter the Datas in a Row
1 2 0 0 0 7 4 0 0
Enter the Datas in a Row
0 4 9 2 0 6 0 0 7
''' |
# A simple list
myList = [10,20,4,5,6,2,9,10,2,3,34,14]
#print the whole list
print("The List is {}".format(myList))
# printing elemts of the list one by one
print("printing elemts of the list one by one")
for elements in myList:
print(elements)
print("")
#printing elements that are greater than 10 only
print("printing elements that are greater than 10 only")
for elements in myList:
if(elements>10):
print(elements)
#printing elements that are greater that 10 but by using a list and appending the elements on it
newList = []
for elements in myList:
if(elements <10):
newList.append(elements)
print("")
print("Print the new List \n{}".format(newList))
#print the above list part using a single line
print(" The list is {}".format([item for item in myList if item < 10]))
# here [item { This is the out put} for item { the is the for part} in myList {This Is the input list} if item <10 {This is the condition}]
#Ask the user for an input and print the elemets of list less than that number
print("Input a number : ")
num = int(input())
print(" The elemnts of the list less that {} are {}".format(num,[item for item in myList if item < num]))
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: yuxiqian
@license: MIT
@contact: akaza_akari@sjtu.edu.cn
@software: electsys-api
@file: electsysApi/shared/exception.py
@time: 2019/1/9
'''
class RequestError(BaseException):
pass
class ParseError(BaseException):
pass
class ParseWarning(Warning):
pass
|
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
for num in list(arr):
if i >= len(arr): break
arr[i] = num
if not num:
i += 1
if i < len(arr):
arr[i] = num
i += 1 |
def extractKaedesan721TumblrCom(item):
'''
Parser for 'kaedesan721.tumblr.com'
'''
bad_tags = [
'FanArt',
"htr asks",
'Spanish translations',
'htr anime','my thoughts',
'Cats',
'answered',
'ask meme',
'relay convos',
'translation related post',
'nightmare fuel',
'htr manga',
'memes',
'htrweek',
'Video Games',
'Animation',
'replies',
'jazz',
'Music',
]
if any([bad in item['tags'] for bad in bad_tags]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if "my translations" in item['tags']:
tagmap = [
('Hakata Tonkotsu Ramens', 'Hakata Tonkotsu Ramens', 'translated'),
('hakata tonktosu ramens', 'Hakata Tonkotsu Ramens', '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 |
#!/usr/bin/python3
# --- 001 > U5W2P1_Task3_w1
def solution(i):
return float(i)
if __name__ == "__main__":
print('----------start------------')
i = 12
print(solution( i ))
print('------------end------------')
|
n = int(input())
intz = [int(x) for x in input().split()]
alice = 0
bob = 0
for i, num in zip(range(n), sorted(intz)[::-1]):
if i%2 == 0:
alice += num
else:
bob += num
print(alice, bob) |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 13:35:33 2020
"""
#for finding loss of significances
x=1e-1
flag = True
a=0
while (flag):
print (((2*x)/(1-(x**2))),"......",(1/(1+x))-(1/(1-x)))
x= x*(1e-1)
a=a+1
if(a==25):
flag=False
|
class Test:
def __init__(self):
pass
def hi(self):
print("hello world") |
def rec_sum(n):
if(n<=1):
return n
else:
return(n+rec_sum(n-1))
|
class Solution(object):
def twoSum(self, nums, target):
seen = {}
output = []
for i in range(len(nums)):
k = target - nums[i]
if k in seen:
output.append(seen[k])
output.append(i)
del seen[k]
else:
seen[nums[i]] = i
return output
class Solution2(object):
"""
If there is exactly one solution
"""
def twoSum(self, nums, target):
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h:
h[num] = i
else:
return [h[n], i]
if __name__ == '__main__':
sol = Solution()
print(sol.twoSum([2,7,11,15], 9))
print(sol.twoSum([3,3], 6)) |
# Given a positive integer num consisting only of digits 6 and 9.
# Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
# Example 1:
# Input: num = 9669
# Output: 9969
# Explanation:
# Changing the first digit results in 6669.
# Changing the second digit results in 9969.
# Changing the third digit results in 9699.
# Changing the fourth digit results in 9666.
# The maximum number is 9969.
# Example 2:
# Input: num = 9996
# Output: 9999
# Explanation: Changing the last digit 6 to 9 results in the maximum number.
# Example 3:
# Input: num = 9999
# Output: 9999
# Explanation: It is better not to apply any change.
# Constraints:
# 1 <= num <= 10^4
# num's digits are 6 or 9.
# Hints:
# Convert the number in an array of its digits.
# Brute force on every digit to get the maximum number.
class Solution(object):
def maximum69Number (self, num):
"""
:type num: int
:rtype: int
"""
# https://blog.csdn.net/CSerwangjun/article/details/104053280
# M1. 模拟
return str(num).replace('6','9', 1)
# M2. 模拟
str_num = str(num)
if '6' in str_num:
pos = str_num.index('6')
list_num = list(str_num)
list_num[pos] = '9'
str_num = ''.join(list_num)
return int(str_num)
else:
return num
# M3. 模拟
s = str(num)
lst = []
for i in s:
lst.append(i)
for i in range(len(lst)):
if lst[i] == '6':
lst[i] = '9'
break
s = ''.join(lst)
return int(s)
|
#
# PySNMP MIB module HPN-ICF-VOICE-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-VOICE-IF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:41:57 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")
SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint")
hpnicfVoice, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfVoice")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
TimeTicks, Unsigned32, Gauge32, NotificationType, MibIdentifier, ModuleIdentity, Counter32, IpAddress, iso, Counter64, ObjectIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Unsigned32", "Gauge32", "NotificationType", "MibIdentifier", "ModuleIdentity", "Counter32", "IpAddress", "iso", "Counter64", "ObjectIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
hpnicfVoiceInterface = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13))
hpnicfVoiceInterface.setRevisions(('2007-12-10 17:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hpnicfVoiceInterface.setRevisionsDescriptions(('The initial version of this MIB file.',))
if mibBuilder.loadTexts: hpnicfVoiceInterface.setLastUpdated('200712101700Z')
if mibBuilder.loadTexts: hpnicfVoiceInterface.setOrganization('')
if mibBuilder.loadTexts: hpnicfVoiceInterface.setContactInfo('')
if mibBuilder.loadTexts: hpnicfVoiceInterface.setDescription('This MIB file is to provide the definition of the voice interface general configuration.')
hpnicfVoiceIfObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1))
hpnicfVoiceIfConfigTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1), )
if mibBuilder.loadTexts: hpnicfVoiceIfConfigTable.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfConfigTable.setDescription('The table contains configurable parameters for both analog voice interface and digital voice interface.')
hpnicfVoiceIfConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hpnicfVoiceIfConfigEntry.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfConfigEntry.setDescription('The entry of voice interface table.')
hpnicfVoiceIfCfgCngOn = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgCngOn.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgCngOn.setDescription('This object indicates whether the silence gaps should be filled with background noise. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgNonLinearSwitch = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgNonLinearSwitch.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgNonLinearSwitch.setDescription('This object expresses the nonlinear processing is enable or disable for the voice interface. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line. Currently, only digital voice subscriber lines can be set disabled.')
hpnicfVoiceIfCfgInputGain = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-140, 139))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgInputGain.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgInputGain.setDescription('This object indicates the amount of gain added to the receiver side of the voice interface. Unit is 0.1 db. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgOutputGain = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-140, 139))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgOutputGain.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgOutputGain.setDescription('This object indicates the amount of gain added to the send side of the voice interface. Unit is 0.1 db. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgEchoCancelSwitch = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgEchoCancelSwitch.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgEchoCancelSwitch.setDescription('This object indicates whether the echo cancellation is enabled. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgEchoCancelDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgEchoCancelDelay.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgEchoCancelDelay.setDescription("This object indicates the delay of the echo cancellation for the voice interface. This value couldn't be modified unless hpnicfVoiceIfCfgEchoCancelSwitch is enable. Unit is milliseconds. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line. The default value of this object is 32.")
hpnicfVoiceIfCfgTimerDialInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 300))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgTimerDialInterval.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgTimerDialInterval.setDescription('The interval, in seconds, between two dialing numbers. The default value of this object is 10 seconds. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 with loop-start or ground-start protocol voice subscriber line.')
hpnicfVoiceIfCfgTimerFirstDial = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 300))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgTimerFirstDial.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgTimerFirstDial.setDescription('The period of time, in seconds, before dialing the first number. The default value of this object is 10 seconds. It is applicable to FXO, FXS subscriber lines and E1/T1 with loop-start or ground-start protocol voice subscriber line.')
hpnicfVoiceIfCfgPrivateline = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgPrivateline.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgPrivateline.setDescription('This object indicates the E.164 phone number for plar mode. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgRegTone = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 10), OctetString().subtype(subtypeSpec=ConstraintsUnion(ValueSizeConstraint(0, 0), ValueSizeConstraint(2, 3), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgRegTone.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgRegTone.setDescription('This object uses 2 or 3 letter country code specify voice parameters of different countrys. This value will take effect on all voice interfaces of all cards on the device.')
mibBuilder.exportSymbols("HPN-ICF-VOICE-IF-MIB", hpnicfVoiceInterface=hpnicfVoiceInterface, hpnicfVoiceIfCfgEchoCancelDelay=hpnicfVoiceIfCfgEchoCancelDelay, hpnicfVoiceIfConfigEntry=hpnicfVoiceIfConfigEntry, PYSNMP_MODULE_ID=hpnicfVoiceInterface, hpnicfVoiceIfObjects=hpnicfVoiceIfObjects, hpnicfVoiceIfCfgNonLinearSwitch=hpnicfVoiceIfCfgNonLinearSwitch, hpnicfVoiceIfCfgTimerFirstDial=hpnicfVoiceIfCfgTimerFirstDial, hpnicfVoiceIfCfgPrivateline=hpnicfVoiceIfCfgPrivateline, hpnicfVoiceIfCfgInputGain=hpnicfVoiceIfCfgInputGain, hpnicfVoiceIfCfgRegTone=hpnicfVoiceIfCfgRegTone, hpnicfVoiceIfCfgTimerDialInterval=hpnicfVoiceIfCfgTimerDialInterval, hpnicfVoiceIfCfgCngOn=hpnicfVoiceIfCfgCngOn, hpnicfVoiceIfCfgEchoCancelSwitch=hpnicfVoiceIfCfgEchoCancelSwitch, hpnicfVoiceIfCfgOutputGain=hpnicfVoiceIfCfgOutputGain, hpnicfVoiceIfConfigTable=hpnicfVoiceIfConfigTable)
|
# standard traversal problem
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# leaf condition
if root == None:
return 0
# skeleton, since function has return, need to assign variables for following usage
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
# this is according to the definition
return max(left_depth, right_depth) + 1 |
frase = str(input('Digite uma frase: ').strip().upper())
print('A letra a aparece {} vezes'.format(frase.count('A')))
print('Sua primeira aparição é na posição {}'.format(frase.find('A') + 1))
print('Ela aparece pela última vez na posição {}'.format(frase.rfind('A') + 1))
|
class GlobalOptions:
""" Class to evaluate global options for example: project path"""
@staticmethod
def evaluate_project_path(path):
""" Method to parse the project path provided by the user"""
first_dir_from_end = None
if path[-1] != "/":
path = path + "/"
new_path = path.rsplit('/')[-2]
for directory in new_path[::-1]:
if directory != " ":
first_dir_from_end = new_path
break
return first_dir_from_end
|
gScore = 0 #use this to index g(n)
fScore = 1 #use this to index f(n)
previous = 2 #use this to index previous node
inf = 10000 #use this for value of infinity
#we represent the graph usind adjacent list
#as dictionary of dictionaries
G = {
'biratnagar' : {'itahari' : 22, 'biratchowk' : 30, 'rangeli': 25},
'itahari' : {'biratnagar' : 22, 'dharan' : 20, 'biratchowk' : 11},
'dharan' : {'itahari' : 20},
'biratchowk' : {'biratnagar' : 30, 'itahari' : 11, 'kanepokhari' :10},
'rangeli' : {'biratnagar' : 25, 'kanepokhari' : 25, 'urlabari' : 40},
'kanepokhari' : {'rangeli' : 25, 'biratchowk' : 10, 'urlabari' : 12},
'urlabari' : {'rangeli' : 40, 'kanepokhari' : 12, 'damak' : 6},
'damak' : {'urlabari' : 6}
}
def h(city):
#returns straight line distance from a city to damak
h = {
'biratnagar' : 46,
'itahari' : 39,
'dharan' : 41,
'rangeli' : 28,
'biratchowk' : 29,
'kanepokhari' : 17,
'urlabari' : 6,
'damak' : 0
}
return h[city]
def getMinimum(unvisited):
#returns city with minimum f(n)
currDist = inf
leastFScoreCity = ''
for city in unvisited:
if unvisited[city][fScore] < currDist:
currDist = unvisited[city][fScore]
leastFScoreCity = city
return leastFScoreCity
def aStar(G, start, goal):
visited = {} #we declare visited list as empty dict
unvisited = {} #we declare unvisited list as empty dict
#we now add every city to the unvisited
for city in G.keys():
unvisited[city] = [inf, inf, ""]
hScore = h(start)
#for starting node, the g(n) is 0, so f(n) will be h(n)
unvisited[start] = [0, hScore, ""]
finished = False
while finished == False:
#if there are no nodes to evaluate in unvisited
if len(unvisited) == 0:
finished = True
else:
#find the node with lowest f(n) from open list
currentNode = getMinimum(unvisited)
if currentNode == goal:
finished = True
#copy data to visited list
visited[currentNode] = unvisited[currentNode]
else:
#we examine the neighbors of currentNode
for neighbor in G[currentNode]:
#we only check unvisited neighbors
if neighbor not in visited:
newGScore = unvisited[currentNode][gScore] + G[currentNode][neighbor]
if newGScore < unvisited[neighbor][gScore]:
unvisited[neighbor][gScore] = newGScore
unvisited[neighbor][fScore] = newGScore + h(neighbor)
unvisited[neighbor][previous] = currentNode
#we now add currentNode to the visited list
visited[currentNode] = unvisited[currentNode]
#we now remove the currentNode from unvisited
del unvisited[currentNode]
return visited
def findPath(visitSequence, goal):
answer = []
answer.append(goal)
currCity = goal
while visitSequence[currCity][previous] != '':
prevCity = visitSequence[currCity][previous]
answer.append(prevCity)
currCity = prevCity
return answer[::-1]
start = 'biratnagar'
goal = 'damak'
visitSequence = aStar(G, start, goal)
path = findPath(visitSequence, goal)
print(path)
|
t=int(input(""))
while (t>0):
n=int(input(""))
f=1
for i in range(1,n+1):
f=f*i
print(f)
t=t-1
|
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for x in [2,3,5]:
while(num % x ==0):
num /= x
return num==1 |
#Area of a rectangle = width x length
#Perimeter of a rectangle = 2 x [length + width#
width_input = float (input("\nPlease enter width: "))
length_input = float (input("Please enter length: "))
areaofRectangle = width_input * length_input
perimeterofRectangle = 2 * (width_input * length_input)
print ("\nArea of Rectangle is: " , areaofRectangle, "CM")
print("\nPerimeter of Rectangle is: ", perimeterofRectangle, "CM")
|
class DNASuitEdge:
COMPONENT_CODE = 22
def __init__(self, startPoint, endPoint, zoneId):
self.startPoint = startPoint
self.endPoint = endPoint
self.zoneId = zoneId
def setStartPoint(self, startPoint):
self.startPoint = startPoint
def setEndPoint(self, endPoint):
self.endPoint = endPoint
def setZoneId(self, zoneId):
self.zoneId = zoneId
|
# This just shifts 1 to i th BIT
def BIT(i: int) -> int:
return int(1 << i)
# This class is equvalent to a C++ enum
class EventType:
Null, \
WindowClose, WindowResize, WindowFocus, WindowMoved, \
AppTick, AppUpdate, AppRender, \
KeyPressed, KeyReleased, CharInput, \
MouseButtonPressed, MouseButtonReleased, MouseMoved, MouseScrolled \
= range(0, 15)
# This class is equvalent to a C++ enum
# It uses bitstream to represent flags, so
# a single Event can have multiple flags
class EventCategory:
Null = 0
Application = BIT(0)
Input = BIT(1)
Keyboard = BIT(2)
Mouse = BIT(3)
MouseButton = BIT(4)
class Event:
Handled = False
@property
def EventType(self) -> int:
pass
@property
def Name(self) -> str:
return type(self)
@property
def CategoryFlags(self) -> int:
pass
def ToString(self) -> str:
return self.GetName()
def IsInCategory(self, category: int) -> bool:
return bool(self.CategoryFlags & category)
def __repr__(self) -> str:
return self.ToString()
class EventDispatcher:
__slots__ = ("_Event",)
def __init__(self, event: Event) -> None:
self._Event = event
def Dispach(self, func, eventType: int) -> bool:
if (self._Event.EventType == eventType):
handeled = func(self._Event)
self._Event.Handled = handeled
return True
return False
|
class Users:
usernamep = 'your_user_email'
passwordp = 'your_password'
linkp = 'https://www.instagram.com/stories/cznburak/'
|
INSTANCES = 405
ITERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50, 100]
N_ITERS = len(ITERS)
# === RESULTS GATHERING ====================================================== #
# results_m is a [INSTANCES][N_ITERS] matrix to store every test result
results_m = [[0 for x in range(N_ITERS)] for y in range(INSTANCES)]
for I in range(N_ITERS):
fin = open("tests/" + str(ITERS[I]))
out = fin.read()
fin.close()
counter = 0
for line in out.splitlines():
results_m[counter][I] = int(line)
counter += 1
# === CALCULATING AVERAGES =================================================== #
averages = [0.0 for x in range(N_ITERS)]
for I in range(INSTANCES):
for J in range(N_ITERS):
results_m[I][J] = results_m[I][J] - results_m[I][0]
if (results_m[I][N_ITERS-1] != 0):
results_m[I][J] = float(results_m[I][J] / results_m[I][N_ITERS-1])
averages[J] += results_m[I][J]
for J in range(N_ITERS):
averages[J] = averages[J]/INSTANCES
for J in range(N_ITERS-1, 1, -1):
averages[J] -= averages[J-1]
# === PRINTING RESULTS ======================================================= #
print("========================================")
print(" all tests:")
for J in range(1, N_ITERS):
if (ITERS[J] < 10):
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
elif (ITERS[J] < 100):
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
else:
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
print("========================================")
# ============================================================================ #
|
# -*- coding: utf-8 -*-
# Copyright 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
"""Defines constants for named column indices to bus matrix.
Some examples of usage, after defining the constants using the line above,
are::
Pd = bus[3, PD] # get the real power demand at bus 4
bus[:, VMIN] = 0.95 # set the min voltage magnitude to 0.95 at all buses
The index, name and meaning of each column of the bus matrix is given
below:
columns 0-12 must be included in input matrix (in case file)
0. C{BUS_I} bus number (1 to 29997)
1. C{BUS_TYPE} bus type (1 = PQ, 2 = PV, 3 = ref, 4 = isolated)
2. C{PD} real power demand (MW)
3. C{QD} reactive power demand (MVAr)
4. C{GS} shunt conductance (MW at V = 1.0 p.u.)
5. C{BS} shunt susceptance (MVAr at V = 1.0 p.u.)
6. C{BUS_AREA} area number, 1-100
7. C{VM} voltage magnitude (p.u.)
8. C{VA} voltage angle (degrees)
9. C{BASE_KV} base voltage (kV)
10. C{ZONE} loss zone (1-999)
11. C{VMAX} maximum voltage magnitude (p.u.)
12. C{VMIN} minimum voltage magnitude (p.u.)
columns 13-16 are added to matrix after OPF solution
they are typically not present in the input matrix
(assume OPF objective function has units, u)
13. C{LAM_P} Lagrange multiplier on real power mismatch (u/MW)
14. C{LAM_Q} Lagrange multiplier on reactive power mismatch (u/MVAr)
15. C{MU_VMAX} Kuhn-Tucker multiplier on upper voltage limit (u/p.u.)
16. C{MU_VMIN} Kuhn-Tucker multiplier on lower voltage limit (u/p.u.)
additional constants, used to assign/compare values in the C{BUS_TYPE} column
1. C{PQ} PQ bus
2. C{PV} PV bus
3. C{REF} reference bus
4. C{NONE} isolated bus
@author: Ray Zimmerman (PSERC Cornell)
@author: Richard Lincoln
"""
# define bus types
PQ = 1
PV = 2
REF = 3
NONE = 4
# define the indices
BUS_I = 0 # bus number (1 to 29997)
BUS_TYPE = 1 # bus type
PD = 2 # Pd, real power demand (MW)
QD = 3 # Qd, reactive power demand (MVAr)
GS = 4 # Gs, shunt conductance (MW at V = 1.0 p.u.)
BS = 5 # Bs, shunt susceptance (MVAr at V = 1.0 p.u.)
BUS_AREA = 6 # area number, 1-100
VM = 7 # Vm, voltage magnitude (p.u.)
VA = 8 # Va, voltage angle (degrees)
BASE_KV = 9 # baseKV, base voltage (kV)
ZONE = 10 # zone, loss zone (1-999)
VMAX = 11 # maxVm, maximum voltage magnitude (p.u.)
VMIN = 12 # minVm, minimum voltage magnitude (p.u.)
# included in opf solution, not necessarily in input
# assume objective function has units, u
LAM_P = 13 # Lagrange multiplier on real power mismatch (u/MW)
LAM_Q = 14 # Lagrange multiplier on reactive power mismatch (u/MVAr)
MU_VMAX = 15 # Kuhn-Tucker multiplier on upper voltage limit (u/p.u.)
MU_VMIN = 16 # Kuhn-Tucker multiplier on lower voltage limit (u/p.u.)
# Additional pandapower extensions to ppc
CID = 13 # coefficient of constant current load at rated voltage in range [0,1]
CZD = 14 # coefficient of constant impedance load at rated voltage in range [0,1]
bus_cols = 15
|
#
# PySNMP MIB module SW-VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-VLAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:12:44 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")
ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
enterprises, iso, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Counter32, Integer32, Unsigned32, Gauge32, IpAddress, ObjectIdentity, MibIdentifier, Counter64, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "iso", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Counter32", "Integer32", "Unsigned32", "Gauge32", "IpAddress", "ObjectIdentity", "MibIdentifier", "Counter64", "TimeTicks", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class MacAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6)
fixedLength = 6
class VlanIndex(Integer32):
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 4094)
class PortList(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(12, 12)
fixedLength = 12
marconi = MibIdentifier((1, 3, 6, 1, 4, 1, 326))
systems = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2))
external = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20))
dlink = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1))
dlinkcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 1))
golf = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2))
golfproducts = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1))
es2000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1, 3))
golfcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2))
marconi_mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2)).setLabel("marconi-mgmt")
es2000Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28))
swL2Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2))
swVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8))
swVlanCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1))
swMacBaseVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2))
swPortBaseVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3))
swVlanCtrlMode = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("mac-base", 3), ("ieee8021q", 4), ("port-base", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swVlanCtrlMode.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanCtrlMode.setDescription('This object controls which Vlan function will be enable (or disable) when the switch hub restart at the startup (power on) or warm start.')
swVlanInfoStatus = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("mac-base", 3), ("ieee8021q", 4), ("port-base", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swVlanInfoStatus.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanInfoStatus.setDescription('This object indicates which Vlan function be enable (or disable) in mandatoryly stage. There are no effect when change swVlanCtrlMode vlaue in the system running.')
swVlanSnmpPortVlan = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 3), VlanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swVlanSnmpPortVlan.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanSnmpPortVlan.setDescription('Indicates the Vlan which the SNMP port belongs to. The value range is 1 to 4094.')
swMacBaseVlanInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1))
swMacBaseVlanMaxNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanMaxNum.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanMaxNum.setDescription('The maximum number of Mac base Vlan allowed by the system.')
swMacBaseVlanAddrMaxNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddrMaxNum.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrMaxNum.setDescription('The maximum number of entries in Mac-based Vlan address table.')
swMacBaseVlanCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2), )
if mibBuilder.loadTexts: swMacBaseVlanCtrlTable.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlTable.setDescription('A table that contains information about MAC base Vlan entries for which the switch has forwarding and/or filtering information. This information is used by the transparent switching function in determining how to propagate a received frame.')
swMacBaseVlanCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swMacBaseVlanDesc"))
if mibBuilder.loadTexts: swMacBaseVlanCtrlEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlEntry.setDescription('A list of information about a specific MAC base Vlan configuration portlist for which the switch has some forwarding and/or filtering information.')
swMacBaseVlanDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanDesc.setDescription('A textual description of the Mac Base Vlan for memorization. The string cannot set to empty string. There is a default value for this string.')
swMacBaseVlanMacMember = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanMacMember.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanMacMember.setDescription('This object indicates the total number of MAC addresses contained in the VLAN entry.')
swMacBaseVlanCtrlState = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("enabled", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanCtrlState.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlState.setDescription('This object indicates the MacBase Vlan state.')
swMacBaseVlanAddrTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3), )
if mibBuilder.loadTexts: swMacBaseVlanAddrTable.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrTable.setDescription('A table that contains information about unicast or multicast entries for which the switch has forwarding and/or filtering information. This information is used by the transparent switching function in determining how to propagate a received frame. Note that the priority of MacBaseVlanAddr table entries is lowest than Filtering Table and FDB Table, i.e. if there is a table hash collision between the entries of MacBaseVlanAddr Table and Filtering Table inside the switch H/W address table, then Filtering Table entry overwrite the colliding entry of MacBaseVlanAddr Table. This state is same of FDB table. See swFdbFilterTable and swFdbStaticTable description also.')
swMacBaseVlanAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swMacBaseVlanAddr"))
if mibBuilder.loadTexts: swMacBaseVlanAddrEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrEntry.setDescription('A list of information about a specific unicast or multicast MAC address for which the switch has some forwarding and/or filtering information.')
swMacBaseVlanAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 1), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddr.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddr.setDescription('This object indictaes a unicast or multicast MAC address for which the bridge has forwarding and/or filtering information.')
swMacBaseVlanAddrVlanDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanAddrVlanDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrVlanDesc.setDescription('A textual description of the Mac Base Vlan for memorization.')
swMacBaseVlanAddrState = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("valid", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanAddrState.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrState.setDescription('This object indicates the MacBase Vlan Address entry state. other(1) - this entry is currently in use but the conditions under which it will remain so are different from each of the following values. invalid(2) - writing this value to the object, and then the corresponding entry will be removed from the table. valid(3) - this entry is reside in the table.')
swMacBaseVlanAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("apply", 2), ("not-apply", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddrStatus.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrStatus.setDescription('This object indicates the MacBase Vlan Address entry state. other(1) - this entry is currently in use but the conditions under which it will remain so are different from each of the following values. apply(2) - this entry is currently in use and reside in the table. not-apply(3) - this entry is reside in the table but currently not in use due to conflict with filter table.')
swPortBaseVlanTotalNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanTotalNum.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanTotalNum.setDescription('The total number of Port-Base Vlan which is in enabled state within this switch hub.')
swPortBaseVlanDefaultVlanTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2), )
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanTable.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanTable.setDescription('A table that contains default Port-Based VLAN list entries for the switch. The entry (Vid = 1,i.e. swPortBaseVlanDefaultPvid = 1) is defalut Port-Based VLAN , maintained by system.')
swPortBaseVlanDefaultVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swPortBaseVlanDefaultPvid"))
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanEntry.setDescription('A list of default Port-Based VLAN information in swPortBaseVlanDefaultVlanTable.')
swPortBaseVlanDefaultPvid = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPvid.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPvid.setDescription('This object indicates the default Port-Base Vlan ID. It occupies only 1 entry in VLAN table, with VID=1.')
swPortBaseVlanDefaultDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultDesc.setDescription('A textual description of the Port-Base Vlan.')
swPortBaseVlanDefaultPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 3), PortList()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortList.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortList.setDescription('This object indicates the port member set of the specified Vlan. Each Vlan has a octect string to indicate the port map. The most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port.')
swPortBaseVlanDefaultPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortNumber.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortNumber.setDescription('This object indicates the number of ports of the entry.')
swPortBaseVlanConfigTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3), )
if mibBuilder.loadTexts: swPortBaseVlanConfigTable.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigTable.setDescription("A table that contains Port-Based VLAN list entries for the switch. The device can't support port overlapping in Port-Based VLAN.")
swPortBaseVlanConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swPortBaseVlanConfigPvid"))
if mibBuilder.loadTexts: swPortBaseVlanConfigEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigEntry.setDescription('A list of information about a specific Port-Based VLAN configuration in swPortBaseVlanConfigTable.')
swPortBaseVlanConfigPvid = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanConfigPvid.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPvid.setDescription('This object indicates the Port-Base Vlan ID. There are up to 11 entries for current product now. The object range varies from 2 to 12.')
swPortBaseVlanConfigDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortBaseVlanConfigDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigDesc.setDescription('A textual description of the Port-Base Vlan. It cannot be a null string. And each description must be unique in the table.')
swPortBaseVlanConfigPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 3), PortList()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortBaseVlanConfigPortList.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPortList.setDescription('This object indicates which ports are belong to the Vlan. Each Vlan has a octect string to indicate with port map. The most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port.')
swPortBaseVlanConfigPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanConfigPortNumber.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPortNumber.setDescription('This object indicates the number of ports of the entry.')
mibBuilder.exportSymbols("SW-VLAN-MIB", marconi=marconi, swPortBaseVlanDefaultVlanEntry=swPortBaseVlanDefaultVlanEntry, swVlan=swVlan, swPortBaseVlanConfigTable=swPortBaseVlanConfigTable, golf=golf, swVlanCtrl=swVlanCtrl, swMacBaseVlanAddrEntry=swMacBaseVlanAddrEntry, swPortBaseVlanDefaultDesc=swPortBaseVlanDefaultDesc, swMacBaseVlanAddr=swMacBaseVlanAddr, swMacBaseVlanMacMember=swMacBaseVlanMacMember, swPortBaseVlanConfigPortNumber=swPortBaseVlanConfigPortNumber, swPortBaseVlanDefaultVlanTable=swPortBaseVlanDefaultVlanTable, swPortBaseVlan=swPortBaseVlan, swMacBaseVlanAddrMaxNum=swMacBaseVlanAddrMaxNum, swL2Mgmt=swL2Mgmt, dlinkcommon=dlinkcommon, swPortBaseVlanConfigEntry=swPortBaseVlanConfigEntry, swPortBaseVlanConfigPortList=swPortBaseVlanConfigPortList, swVlanSnmpPortVlan=swVlanSnmpPortVlan, swMacBaseVlanCtrlState=swMacBaseVlanCtrlState, PortList=PortList, external=external, swMacBaseVlanAddrStatus=swMacBaseVlanAddrStatus, swPortBaseVlanTotalNum=swPortBaseVlanTotalNum, swMacBaseVlan=swMacBaseVlan, swVlanInfoStatus=swVlanInfoStatus, swMacBaseVlanDesc=swMacBaseVlanDesc, swPortBaseVlanDefaultPvid=swPortBaseVlanDefaultPvid, dlink=dlink, MacAddress=MacAddress, swVlanCtrlMode=swVlanCtrlMode, golfproducts=golfproducts, systems=systems, swMacBaseVlanCtrlTable=swMacBaseVlanCtrlTable, swMacBaseVlanAddrVlanDesc=swMacBaseVlanAddrVlanDesc, marconi_mgmt=marconi_mgmt, swMacBaseVlanMaxNum=swMacBaseVlanMaxNum, swMacBaseVlanCtrlEntry=swMacBaseVlanCtrlEntry, swPortBaseVlanDefaultPortList=swPortBaseVlanDefaultPortList, swMacBaseVlanAddrTable=swMacBaseVlanAddrTable, swPortBaseVlanConfigPvid=swPortBaseVlanConfigPvid, swPortBaseVlanConfigDesc=swPortBaseVlanConfigDesc, VlanIndex=VlanIndex, swPortBaseVlanDefaultPortNumber=swPortBaseVlanDefaultPortNumber, golfcommon=golfcommon, swMacBaseVlanAddrState=swMacBaseVlanAddrState, es2000Mgmt=es2000Mgmt, es2000=es2000, swMacBaseVlanInfo=swMacBaseVlanInfo)
|
class DFA:
current_state = None
current_letter = None
valid = True
def __init__(
self, name, alphabet, states, delta_function, start_state, final_states
):
self.name = name
self.alphabet = alphabet
self.states = states
self.delta_function = delta_function
self.start_state = start_state
self.final_states = final_states
self.current_state = start_state
def transition_to_state_with_input(self, letter):
if self.valid:
if (self.current_state, letter) not in self.delta_function.keys():
self.valid = False
return
self.current_state = self.delta_function[(self.current_state, letter)]
self.current_letter = letter
else:
return
def in_accept_state(self):
return self.current_state in self.final_states and self.valid
def go_to_initial_state(self):
self.current_letter = None
self.valid = True
self.current_state = self.start_state
def run_with_word(self, word):
self.go_to_initial_state()
for letter in word:
self.transition_to_state_with_input(letter)
continue
return self.in_accept_state()
def run_with_letters(self, word):
self.go_to_initial_state()
for letter in word:
if self.run_with_letter(letter):
return
else:
return
def run_with_letter(self, letter):
self.transition_to_state_with_input(letter)
return self.current_state
def __len__(self):
return len(self.states)
|
class LambdaError(Exception):
def __init__(self, description):
self.description = description
class BadRequestError(LambdaError):
pass
class ForbiddenError(LambdaError):
pass
class InternalServerError(LambdaError):
pass
class NotFoundError(LambdaError):
pass
class ValidationError(LambdaError):
pass
class FormattingError(LambdaError):
pass
class EventValidationError(ValidationError):
pass
class ResultValidationError(ValidationError):
pass
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n, m = map(int, input().strip().split())
a = sorted(map(int, input().strip().split()), reverse=True)
b = sorted(map(int, input().strip().split()), reverse=True)
if a[0] > b[0]:
print(-1)
else:
min_time = 1
i = j = 0
while i < len(a):
if j < len(b) and a[i] <= b[j]:
j += 1
elif a[i] <= b[j - 1]:
min_time += 2
i += 1
print(min_time)
|
pkgname = "xrandr"
pkgver = "1.5.1"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
makedepends = ["libxrandr-devel"]
pkgdesc = "Command line interface to X RandR extension"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "https://xorg.freedesktop.org"
source = f"$(XORG_SITE)/app/{pkgname}-{pkgver}.tar.xz"
sha256 = "7bc76daf9d72f8aff885efad04ce06b90488a1a169d118dea8a2b661832e8762"
def post_install(self):
self.install_license("COPYING")
|
# Validate input
while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Pleas enter a number for your age.')
|
#
# PySNMP MIB module Fore-Common-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-Common-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:14:34 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)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Bits, MibIdentifier, enterprises, Counter64, Unsigned32, ModuleIdentity, Counter32, TimeTicks, NotificationType, ObjectIdentity, IpAddress, Gauge32, Integer32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "MibIdentifier", "enterprises", "Counter64", "Unsigned32", "ModuleIdentity", "Counter32", "TimeTicks", "NotificationType", "ObjectIdentity", "IpAddress", "Gauge32", "Integer32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
fore = ModuleIdentity((1, 3, 6, 1, 4, 1, 326))
if mibBuilder.loadTexts: fore.setLastUpdated('9911050000Z')
if mibBuilder.loadTexts: fore.setOrganization('Marconi Communications')
if mibBuilder.loadTexts: fore.setContactInfo(' Postal: Marconi Communications, Inc. 5000 Marconi Drive Warrendale, PA 15086-7502 Tel: +1 724 742 6999 Email: bbrs-mibs@marconi.com Web: http://www.marconi.com')
if mibBuilder.loadTexts: fore.setDescription('Definitions common to all FORE private MIBS.')
admin = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1))
systems = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2))
foreExperiment = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 3))
operations = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 1))
snmpErrors = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 2))
snmpTrapDest = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 3))
snmpAccess = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 4))
assembly = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 5))
fileXfr = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 6))
rmonExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 7))
preDot1qVlanMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 8))
snmpTrapLog = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 9))
ilmisnmp = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 10))
entityExtensionMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 11))
ilmiRegistry = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 14))
foreIfExtension = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 15))
frameInternetworking = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 16))
ifExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 17))
atmAdapter = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 1))
atmSwitch = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2))
etherSwitch = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 3))
atmAccess = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 5))
hubSwitchRouter = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 6))
ipoa = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 7))
stackSwitch = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 10))
switchRouter = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 15))
software = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 2))
asxd = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 2, 1))
hardware = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 1))
asx = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 1, 1))
asx200wg = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 4))
asx200bx = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 5))
asx200bxe = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 6))
cabletron9A000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 7))
asx1000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 8))
le155 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 9))
sfcs200wg = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 10))
sfcs200bx = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 11))
sfcs1000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 12))
tnx210 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 15))
tnx1100 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 16))
asx1200 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 17))
asx4000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 18))
le25 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 19))
esx3000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 20))
tnx1100b = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 21))
asx150 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 22))
bxr48000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 24))
asx4000m = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 25))
axhIp = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 26))
axhSig = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 27))
class SpansAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8)
fixedLength = 8
class AtmAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(20, 20), )
class NsapPrefix(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(13, 13)
fixedLength = 13
class NsapAddr(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(20, 20)
fixedLength = 20
class TransitNetwork(DisplayString):
subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(1, 4)
class TrapNumber(Integer32):
pass
class EntryStatus(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))
namedValues = NamedValues(("valid", 1), ("createRequest", 2), ("underCreation", 3), ("invalid", 4))
class AtmSigProtocol(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
namedValues = NamedValues(("other", 1), ("spans", 2), ("q2931", 3), ("pvc", 4), ("spvc", 5), ("oam", 6), ("spvcSpans", 7), ("spvcPnni", 8), ("rcc", 9), ("fsig", 10), ("mpls", 11), ("ipCtl", 12), ("oam-ctl", 13))
class GeneralState(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("normal", 1), ("fail", 2))
class IntegerBitString(Integer32):
pass
class ConnectionType(Integer32):
pass
mibBuilder.exportSymbols("Fore-Common-MIB", ilmiRegistry=ilmiRegistry, fore=fore, ilmisnmp=ilmisnmp, NsapPrefix=NsapPrefix, atmAccess=atmAccess, snmpTrapDest=snmpTrapDest, rmonExtensions=rmonExtensions, preDot1qVlanMIB=preDot1qVlanMIB, operations=operations, ipoa=ipoa, software=software, tnx1100=tnx1100, snmpErrors=snmpErrors, sfcs200bx=sfcs200bx, snmpAccess=snmpAccess, sfcs200wg=sfcs200wg, le25=le25, sfcs1000=sfcs1000, esx3000=esx3000, frameInternetworking=frameInternetworking, asx4000m=asx4000m, AtmAddress=AtmAddress, assembly=assembly, ConnectionType=ConnectionType, axhIp=axhIp, bxr48000=bxr48000, ifExtensions=ifExtensions, asx=asx, asxd=asxd, asx4000=asx4000, TransitNetwork=TransitNetwork, fileXfr=fileXfr, EntryStatus=EntryStatus, foreIfExtension=foreIfExtension, asx1000=asx1000, asx200bxe=asx200bxe, axhSig=axhSig, TrapNumber=TrapNumber, SpansAddress=SpansAddress, IntegerBitString=IntegerBitString, atmSwitch=atmSwitch, cabletron9A000=cabletron9A000, AtmSigProtocol=AtmSigProtocol, tnx1100b=tnx1100b, asx200bx=asx200bx, etherSwitch=etherSwitch, asx1200=asx1200, hubSwitchRouter=hubSwitchRouter, entityExtensionMIB=entityExtensionMIB, switchRouter=switchRouter, NsapAddr=NsapAddr, asx200wg=asx200wg, systems=systems, atmAdapter=atmAdapter, foreExperiment=foreExperiment, PYSNMP_MODULE_ID=fore, admin=admin, le155=le155, GeneralState=GeneralState, hardware=hardware, stackSwitch=stackSwitch, asx150=asx150, tnx210=tnx210, snmpTrapLog=snmpTrapLog)
|
class Page(object):
def __init__(self, params):
self.size = 2 ** 10
self.Time = False
self.R = False
self.M = False
|
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def print_list(self):
cur = self
while cur:
print(cur.val, end='->')
cur = cur.next
class Solution:
# 전가산기구현
def addTwoNumbers(selfself, l1: ListNode, l2: ListNode) -> ListNode:
root = head = ListNode(0)
carry = 0 # 자리올림수
while l1 or l2 or carry:
sum = 0
# 두 입력값의 합 계산
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
# 몫 (자리올림수_과 나머지(값) 계산
carry, val = divmod(sum + carry, 10)
head.next = ListNode(val)
head = head.next
return root.next
if __name__ == '__main__':
solution = Solution()
param1 = ListNode(2, ListNode(4, ListNode(5)))
param2 = ListNode(5, ListNode(6, ListNode(4)))
print(solution.addTwoNumbers(param1, param2).print_list())
|
# -*- coding: utf-8 -*-
"""
Jokes below come from the "jokes_en.py" file.
Translation to Polish: Tomasz Rozynek - provided under CC BY-SA 3.0
"""
neutral = [
"W 2030 roku Beata z ulgą usunęła Python'a 2.7 ze swoich maszyn. 'No!' westchnęła, by za chwilę przeczytać ogłoszenia na temat Python'a 4.4.",
"Zapytanie SQL wchodzi do baru, podchodzi do pierwszej osoby i pyta, 'Czy możemy utworzyć relację?'",
"Kiedy używasz C++ jak młotka, wszystko będzie Twoim kciukiem.",
"Jak posadzisz milion małp przy milionie klawiatur, któraś z nich w końcu napisze działający program w Javie. Pozostałe będą pisać w Perlu.",
"Aby zrozumieć rekurencję, musisz najpierw zrozumieć rekurencję.",
"'Puk, puk.' 'Kto tam?' ... bardzo długa pauza ... 'Java.'",
"'Puk, puk.' 'Kto tam?' 'C++.'",
"'Puk, p... Asembler.'",
"Ilu programistów potrzeba, żeby wymienić żarówkę? Żadnego, bo to problem sprzętowy.",
"Jak nazywa się obiektowa metoda bogacenia się? Dziedziczenie.",
"Dlaczego dowcipy nie działają w systemie ósemkowym? Ponieważ 7, 10, 11.",
"Ilu programistów potrzeba, aby wymienić żarówkę? Żadnego, po prostu ogłaszają ciemność standardem.",
"Dwa wątki wchodzą do baru. Barman patrzy na nie i woła, 'Hej! Nie chcemy tu hazardu!'",
"Programiści uwielbiają rozwiązywanie problemów. Jeśli akurat nie mają żadnego do rozwiązania, z pewnością jakiś stworzą.",
".NET nazywa się .NET, żeby przypadkiem nie wyświetlił się w uniksowym listingu plików.",
"Sprzęt: część komputera, którą możesz kopnąć.",
"Optymista: Szklanka do połowy pełna. Pesymista: Szklanka do połowy pusta. Programista: Rozmiar szklanki jest dwa razy większy, niż wymagany.",
"W C sami musieliśmy kodować błędy. W C++ możemy je po prostu odziedziczyć.",
"Dlaczego nie ma konkursów na najmniej czytelny kod w Perlu? Bo nikt nie umiałby wyłonić zwycięzcy.",
"Odtwarzając dysk instalacyjny Windowsa od tyłu, usłyszysz czarną mszę. Gorzej, jeśli odtworzysz ją od przodu, wtedy zainstaluje Windowsa.",
"Ilu programistów potrzeba, aby zabić karalucha? Dwóch: jeden go trzyma, a drugi instaluje na nim Windowsa.",
"Do jakiej grupy należą programiści z Finlandii? Nerdyckiej.",
"Co mówi kod w Javie do kodu w C? Brakuje Ci klasy.",
"Dlaczego Microsoft nazwał swoją wyszukiwarkę BING? Bo Indolentnie Naśladuje Google.",
"Piraci wołają 'arg!', komputerowi piraci wołają 'argv!'",
"Dziecko: Mamo, dlaczego Słońce wschodzi na wschodzie i zachodzi na zachodzie? Ojciec: jeśli działa, nie dotykaj.",
"Dlaczego programistom myli się Halloween z Bożym Narodzeniem? Ponieważ OCT 31 == DEC 25.",
"Ilu programistów Prologa potrzeba, żeby wymienić żarówkę? Fałsz.",
"Kelner: Podać kawę, lub herbatę? Programistka: Tak.",
"Programistka wchodzi do foo...",
"Jak brzmi drugie imię Benoit'a B. Mandelbrot'a? Benoit B. Mandelbrot.",
"Dlaczego zawsze się uśmiechasz? To moje regularne wyrażenie twarzy.",
"Programistka miała problem. Pomyślała sobie, 'Wiem, rozwiążę to wątkami!'. ma Teraz problemy. ona dwa",
"Opowiedziałbym dowcip o UDP, ale nie wiem, czy by do Ciebie dotarł.",
"Testerka wchodzi do baru. Wbiega do baru. Wczołguje się do baru. Tańczy wchodząc do baru. Wchodzi tip-topami do baru. Szarżuje do baru.",
"Miałem problem, więc pomyślałem, że użyję Javy. Teraz mam FabrykaProblemow.",
"Tester wchodzi do baru. Zamawia piwo. Zamawia 0 piw. Zamawia 999999999 piw. Zamawia jaszczurkę. Zamawia -1 piw. Zamawia sfdeljknesv.",
"Kierowniczka projektu wchodzi do baru, zamawia drinka. Barman odmawia, ale pomyśli nad dodaniem go później.",
"Jak wygenerować prawdziwie losowy ciąg znaków? Posadź studenta pierwszego roku przed Vim'em i powiedz, żeby zapisał plik i wyłączył edytor.",
"Od dłuższego czasu używam Vim'a. Głównie dlatego, że nadal próbuję go wyłączyć.",
"Jak poznać, że ktoś używa Vim'a? Nie przejmuj się, sam Ci powie.",
"Kelner: On się krztusi! Czy jest na sali doktor? Programista: Jestem użytkownikiem Vim'a.",
"Trójka adminów baz danych wchodzi do NoSQL'owego baru. Po krótkim czasie rozeszli się, ponieważ nie mogli utworzyć relacji.",
"Jak opisać fabułę Incepcji programiście? Uruchamiasz maszynę wirtualną w wirtualce, wewnątrz innej wirtualki... wszystko działa wolno!",
"W informatyce są tylko dwa trudne problemy: unieważnianie pamięci podręcznej, nazewnictwo i pomyłki o 1.",
"Istnieje 10 rodzajów ludzi: Ci, którzy rozumieją kod binarny oraz Ci, którzy go nie rozumieją.",
"Istnieją 2 rodzaje ludzi: Ci, którzy potrafią ekstrapolować niekompletne zbiory danych...",
"Istnieją II rodzaje ludzi: Ci, którzy rozumieją liczby rzymskie i Ci, którzy ich nie rozumieją.",
"Istnieje 10 typów ludzi: Ci, którzy rozumieją system szesnastkowy oraz 15 pozostałych.",
"Istnieje 10 rodzajów ludzi: Ci, którzy rozumieją kod binarny, Ci którzy go nie rozumieją oraz Ci, co wiedzieli, że to o systemie trójkowym.",
"Istnieje 10 rodzajów ludzi: Ci, którzy rozumieją kod trójkowy, Ci, którzy go nie rozumieją oraz Ci, którzy nigdy o nim nie słyszeli.",
"Jak nazywa się ósemka hobbitów? Hobbajt.",
"Najlepsze w wartościach logicznych jest to, że nawet jeśli się pomylisz, to tylko o 1.",
"Dobry programista zawsze patrzy w obie strony przed przejściem przez ulicę jednokierunkową.",
"Są dwa sposoby pisania programów bez błędów. Tylko ten trzeci działa.",
"Zarządzanie jakością składa się w 55% z wody, 30% krwi i 15% ticketów z bugtrackera",
"Sympatyzowanie z Diabłem to tak naprawdę bycie uprzejmym dla Testerów.",
"Ilu Testerów potrzeba do zmiany żarówki? Oni zauważyli, że pokój jest ciemny. Nie rozwiązują problemów, tylko ich szukają.",
"Programista rozbił auto zjeżdżając z góry. Przechodzień spytał co się stało. \"Nie wiem. Wnieśmy go na górę i spróbujmy ponownie.\".",
"Pisanie w PHP jest jak sikanie do basenu. Wszyscy to robili, ale niekoniecznie trzeba się tym chwalić publicznie.",
"Dlaczego Tester przeszedł przez ulicę? Żeby zepsuć dzień wszystkim innym.",
"Ilość dni od ostatniego błędu indeksowania tablicy: -1.",
"Ilość dni od ostatniej pomyłki o 1: 0.",
"Szybkie randki są bez sensu. 5 minut to zbyt mało czasu, aby prawidłowo wyjaśnić filozofię Unix'a.",
"Microsoft co dwa miesiące organizuje \"tydzień produktywności\", podczas którego używają Google zamiast Bing'a",
"Podejście Schroedinger'a do budowy stron www: Jeśli nie oglądasz tego w Internet Explorerze, jest szansa, że będzie wyglądało dobrze.",
"Szukanie dobrego programisty PHP jest jak szukanie igły w stogu siana. Czy raczej stogu siana w igle?",
"Unix jest bardzo przyjazny użytkownikom. Po prostu jest również bardzo wybredny przy wyborze przyjaciół.",
"Programistka COBOL'a zarabia miliony naprawiając problem roku 2000. Decyduje się zamrozić siebie. \"Mamy rok 9999. Znasz COBOL'a, prawda?\"",
"Język C łączy w sobie potęgę asemblera z prostotą użycia asemblera.",
"Ekspert SEO wchodzi do baru, bar, pub, miesce spotkań, browar, Irlandzki pub, tawerna, barman, piwo, gorzała, wino, alkohol, spirytus...",
"Co mają wspólnego pyjokes oraz Adobe Flash? Wciąż otrzymują aktualizacje, ale nigdy nie stają się lepsze.",
"Dlaczego Waldo nosi tylko paski? Bo nie chce się znaleźć w kropce.",
"Szedłem raz ulicą, przy której domy były ponumerowane 8k, 16k, 32k, 64k, 128k, 256k i 512k. To była podróż Aleją Pamięci.",
"!false, (To zabawne, bo to prawda)",
]
"""
Jokes below come from the "jokes_en.py" file.
Translation to Polish: Tomasz Rozynek - provided under CC BY-SA 3.0
"""
chuck = [
"Kiedy Chuck Norris rzuca wyjątek, to leci on przez cały pokój.",
"Wszystkie tablice, które deklaruje Chuck Norris są nieskończonego rozmiaru, ponieważ Chuck Norris nie zna granic.",
"Chuck Norris nie ma opóźnień w dysku twardym, ponieważ dysk twardy wie, że musi się spieszyć, żeby nie wkurzyć Chucka Norrisa.",
"Chuck Norris pisze kod, który sam się optymalizuje.",
"Chuck Norris nie porównuje, ponieważ nie ma sobie równych.",
"Chuck Norris nie potrzebuje garbage collector'a, ponieważ nie wywołuje .Dispose(), tylko .DropKick().",
"Pierwszym programem Chucka Norrisa było kill -9.",
"Chuck Norris przebił bańkę dot com'ów.",
"Wszystkie przeglądarki wspierają kolory #chuck oraz #norris, oznaczające czarny i niebieski.",
"MySpace tak naprawdę nie jest Twój, tylko Chuck'a. Po prostu pozwala Ci go używać.",
"Chuck Norris może pisać funkcje rekurencyjne bez warunku stopu, które zawsze wracają.",
"Chuck Norris może rozwiązać wieże Hanoi w jednym ruchu.",
"Chuck Norris zna tylko jeden wzorzec projektowy: Boski obiekt.",
"Chuck Norris ukończył World of Warcraft.",
"Kierownicy projektu nigdy nie pytają Chucka Norrisa o oszacowania.",
"Chuck Norris nie dostosowuje się do standardów webowych, ponieważ to one dostosowują się do niego.",
"'U mnie to działa' jest zawsze prawdą w przypadku Chucka Norrisa.",
"Chuck Norris nie używa diagramów wyżarzania, tylko uderzania.",
"Chuck Norris może usunąć Kosz.",
"Broda Chucka Norrisa może pisać 140 słów na minutę.",
"Chuck Norris może przetestować całą aplikację jedną asercją: 'działa'.",
"Chuck Norris nie szuka błędów, ponieważ to sugeruje, że może ich nie znaleźć. On likwiduje błędy.",
"Klawiatura Chucka Norris'a nie ma klawisza Ctrl, ponieważ nic nie kontroluje Chucka Norrisa.",
"Chuck Norris może przepełnić Twój stos samym spojrzeniem.",
"Dla Chucka Norrisa wszystko zawiera podatności.",
"Chuck Norris nie używa sudo. Powłoka wie, że to on i po prostu robi co jej każe.",
"Chuck Norris nie używa debuggera. Patrzy na kod tak długo, aż sam wyzna błędy.",
"Chuck Norris ma dostęp do prywatnych metod.",
"Chuck Norris może utworzyć obiekt klasy abstrakcyjnej.",
"Chuck Norris nie potrzebuje fabryki klas. On instancjonuje interfejsy.",
"Klasa Object dziedziczy po Chucku Norrisie.",
"Dla Chucka Norrisa problemy NP-trudne mają złożoność O(1).",
"Chuck Norris zna ostatnią cyfrę rozwinięcia dziesiętnego Pi.",
"Łącze internetowe Chucka Norrisa szybciej wysyła, niż pobiera, ponieważ nawet dane się go boją.",
"Chuck Norris rozwiązał problem komiwojażera w czasie stałym: rozbij komiwojażera na N kawałków, po czym wykop każdy do innego miasta.",
"Żadne wyrażenie nie może obsłużyć ChuckNorrisException.",
"Chuck Norris nie programuje w parach. Pracuje sam.",
"Chuck Norris potrafi pisać aplikacje wielowątkowe przy użyciu jednego wątku.",
"Chuck Norris nie musi używać AJAX'a, ponieważ strony i tak są przerażone jego zwykłymi żądaniami.",
"Chuck Norris nie używa refleksji. To refleksje uprzejmie proszą go o pomoc.",
"Klawiatura Chucka Norrisa nie ma klawisza Escape, ponieważ nikt nie ucieknie przed Chuckiem Norrisem.",
"Chuck Norris może użyć wyszukiwania binarnego na nieposortowanym kontenerze.",
"Chuck Norris nie musi łapać wyjątków. Są zbyt przerażone, by się pokazać.",
"Chuck Norris wyszedł z nieskończonej pętli.",
"Jeśli Chuck Norris napisze kod z błędami, to one same się poprawią.",
"Hosting Chucka Norrisa ma SLA na poziomie 101%.",
"Klawiatura Chucka Norrisa ma klawisz 'Dowolny'.",
"Chuck Norris może dostać się do bazy danych bezpośrednio przez interfejs użytkownika.",
"Programy Chucka Norrisa się nie kończą, tylko giną.",
"Chuck Norris nalega na używanie języków silnie typowanych.",
"Chuck Norris projektuje protokoły bez statusów, żądań, czy odpowiedzi. Definiuje tylko polecenia.",
"Programy Chucka Norrisa zajmują 150% procesora, nawet gdy nie są uruchomione.",
"Chuck Norris uruchamia wątki, które kończą swoje zadanie, zanim się poprawnie uruchomią.",
"Programy Chucka Norrisa nie akceptują wejścia.",
"Chuck Norris może zainstalować iTunes bez QuickTime'a.",
"Chuck Norris nie potrzebuje systemu operacyjnego.",
"Model OSI Chucka Norrisa ma tylko jedną warstwę - fizyczną.",
"Chuck Norris może poprawnie kompilować kod z błędami składniowymi.",
"Każde zapytanie SQL Chucka Norrisa zawiera implikowany 'COMMIT'.",
"Chuck Norris nie potrzebuje rzutowania. Kompilator Chucka Norrisa (KCN) dostrzega wszystko. Do samego końca. Zawsze.",
"Chuck Norris nie wykonuje kodu w cyklach, tylko w uderzeniach.",
"Chuck Norris kompresuje pliki przez kopnięcie dysku twardego z półobrotu.",
"Chuck Norris rozwiązał problem stopu.",
"Dla Chucka Norrisa P = NP. Jego decyzje są zawsze deterministyczne.",
"Chuck Norris może pobrać wszystko z /dev/null.",
"Nikomu nie udało się programować z Chuckiem Norrisem i wyjść z tego żywym.",
"Nikomu nie udało się odezwać podczas przeglądu kodu Chucka Norrisa i wyjść z tego żywym.",
"Chuck Norris nie używa interfejsów graficznych. On rozkazuje z wiersza poleceń.",
"Chuck Norris nie używa Oracle'a. On JEST Wyrocznią.",
"Chuck Norris może dokonać dereferencji NULL'a.",
"Lista różnic pomiędzy Twoim kodem oraz kodem Chucka Norrisa jest nieskończona.",
"Chuck Norris napisał wtyczkę do Eclipsa, która dokonała pierwszego kontaktu z obcą cywilizacją.",
"Chuck Norris jest ostatecznym semaforem. Wszystkie wątki się go boją.",
"Nie przejmuj się testami. Przypadki testowe Chucka Norrisa pokrywają również Twój kod.",
"Każdy włos z brody Chucka Norrisa ma swój wkład w największy na świecie atak DDOS.",
"Komunikaty w loggerze Chucka Norrisa zawsze mają poziom FATAL.",
"Jeśli Chuck Norris zepsuje build'a, nie uda Ci się go naprawić, ponieważ nie została ani jedna linijka kodu.",
"Chuck Norris pisze jednym palcem. Wskazuje nim na klawiaturę, a ona robi resztę roboty.",
"Programy Chucka Norrisa przechodzą test Turinga po prostu patrząc się na sędziego.",
"Jeśli spróbujesz zabić program Chucka Norrisa, to on zabije Ciebie.",
"Chuck Norris wykonuje nieskończone pętle w mniej niż 4 sekundy.",
"Chuck Norris może nadpisać zmienną zablokowaną semaforem.",
"Chuck Norris zna wartość NULL. Może też po niej sortować.",
"Chuck Norris może zainstalować 64-bitowy system operacyjny na 32-bitowych maszynach.",
"Chuck Norris może pisać do strumieni wyjściowych.",
"Chuck Norris może czytać ze strumieni wejściowych.",
"Chuck Norris nie musi kompilować swojego kodu. Maszyny nauczyły się interpretować kod Chuck Norrisa.",
"Chuck Norris jest powodem Niebieskiego Ekranu Śmierci.",
"Chuck Norris może utworzyć klasę, które jest jednocześnie abstrakcyjna i finalna.",
"Chuck Norris może użyć czegokolwiek z java.util.*, żeby Cię zabić. Nawet javadocs'ów.",
"Kod działa szybciej, gdy obserwuje go Chuck Norris.",
"Wszyscy lubią profil Chucka Norrisa na Facebook'u, czy im się to podoba, czy nie.",
"Nie możesz śledzić Chucka Norrisa na Twitterze, ponieważ to on śledzi Ciebie.",
"Kalkulator Chucka Norrisa ma tylko 3 klawisze: 0, 1 i NAND.",
"Chuck Norris używa tylko zmiennych globalnych. Nie ma nic do ukrycia.",
"Chuck Norris raz zaimplementował cały serwer HTTP, używając tylko jednego printf'a. Projekt wciąż się rozwija i jest znany pod nazwą Apache.",
"Chuck Norris pisze bezpośrednio w kodzie binarnym. Potem pisze kod źródłowy, jako dokumentację dla innych programistów.",
"Chuck Norris raz przesunął bit tak mocno, że wylądował w innym komputerze.",
"Jak nazywa się ulubiony framework Chucka Norrisa? Knockout.js.",
]
jokes_pl = {
'neutral': neutral,
'chuck': chuck,
'all': neutral + chuck,
}
|
PROMQL = """
start: query
// Binary operations are defined separately in order to support precedence
?query\
: or_match
| matrix
| subquery
| offset
?or_match\
: and_unless_match
| or_match OR grouping? and_unless_match
?and_unless_match\
: comparison_match
| and_unless_match (AND | UNLESS) grouping? comparison_match
?comparison_match\
: sum_match
| comparison_match /==|!=|>=|<=|>|</ BOOL? grouping? sum_match
?sum_match\
: product_match
| sum_match /\\+|-/ grouping? product_match
?product_match\
: unary
| product_match /\\*|\\/|%/ grouping? unary
?unary\
: power_match
| /\\+|-/ power_match
?power_match\
: atom
| atom /\\^/ grouping? power_match
?atom\
: function
| aggregation
| instant_query
| NUMBER
| STRING
| "(" query ")"
// Selectors
instant_query\
: METRIC_NAME ("{" label_matcher_list? "}")? -> instant_query_with_metric
| "{" label_matcher_list "}" -> instant_query_without_metric
label_matcher_list: label_matcher ("," label_matcher)*
label_matcher: label_name /=~|=|!=|!~/ STRING
matrix: query "[" DURATION "]"
subquery: query "[" DURATION ":" DURATION? "]"
offset: query OFFSET DURATION
// Function
function: function_name parameter_list
parameter_list: "(" (query ("," query)*)? ")"
?function_name\
: ABS
| ABSENT
| ABSENT_OVER_TIME
| CEIL
| CHANGES
| CLAMP_MAX
| CLAMP_MIN
| DAY_OF_MONTH
| DAY_OF_WEEK
| DAYS_IN_MONTH
| DELTA
| DERIV
| EXP
| FLOOR
| HISTOGRAM_QUANTILE
| HOLT_WINTERS
| HOUR
| IDELTA
| INCREASE
| IRATE
| LABEL_JOIN
| LABEL_REPLACE
| LN
| LOG2
| LOG10
| MINUTE
| MONTH
| PREDICT_LINEAR
| RATE
| RESETS
| ROUND
| SCALAR
| SORT
| SORT_DESC
| SQRT
| TIME
| TIMESTAMP
| VECTOR
| YEAR
| AVG_OVER_TIME
| MIN_OVER_TIME
| MAX_OVER_TIME
| SUM_OVER_TIME
| COUNT_OVER_TIME
| QUANTILE_OVER_TIME
| STDDEV_OVER_TIME
| STDVAR_OVER_TIME
// Aggregations
aggregation\
: aggregation_operator parameter_list
| aggregation_operator (by | without) parameter_list
| aggregation_operator parameter_list (by | without)
by: BY label_name_list
without: WITHOUT label_name_list
?aggregation_operator\
: SUM
| MIN
| MAX
| AVG
| GROUP
| STDDEV
| STDVAR
| COUNT
| COUNT_VALUES
| BOTTOMK
| TOPK
| QUANTILE
// Vector one-to-one/one-to-many joins
grouping: (on | ignoring) (group_left | group_right)?
on: ON label_name_list
ignoring: IGNORING label_name_list
group_left: GROUP_LEFT label_name_list
group_right: GROUP_RIGHT label_name_list
// Label names
label_name_list: "(" (label_name ("," label_name)*)? ")"
?label_name: keyword | LABEL_NAME
?keyword\
: AND
| OR
| UNLESS
| BY
| WITHOUT
| ON
| IGNORING
| GROUP_LEFT
| GROUP_RIGHT
| OFFSET
| BOOL
| aggregation_operator
| function_name
// Keywords
// Function names
ABS: "abs"
ABSENT: "absent"
ABSENT_OVER_TIME: "absent_over_time"
CEIL: "ceil"
CHANGES: "changes"
CLAMP_MAX: "clamp_max"
CLAMP_MIN: "clamp_min"
DAY_OF_MONTH: "day_of_month"
DAY_OF_WEEK: "day_of_week"
DAYS_IN_MONTH: "days_in_month"
DELTA: "delta"
DERIV: "deriv"
EXP: "exp"
FLOOR: "floor"
HISTOGRAM_QUANTILE: "histogram_quantile"
HOLT_WINTERS: "holt_winters"
HOUR: "hour"
IDELTA: "idelta"
INCREASE: "increase"
IRATE: "irate"
LABEL_JOIN: "label_join"
LABEL_REPLACE: "label_replace"
LN: "ln"
LOG2: "log2"
LOG10: "log10"
MINUTE: "minute"
MONTH: "month"
PREDICT_LINEAR: "predict_linear"
RATE: "rate"
RESETS: "resets"
ROUND: "round"
SCALAR: "scalar"
SORT: "sort"
SORT_DESC: "sort_desc"
SQRT: "sqrt"
TIME: "time"
TIMESTAMP: "timestamp"
VECTOR: "vector"
YEAR: "year"
AVG_OVER_TIME: "avg_over_time"
MIN_OVER_TIME: "min_over_time"
MAX_OVER_TIME: "max_over_time"
SUM_OVER_TIME: "sum_over_time"
COUNT_OVER_TIME: "count_over_time"
QUANTILE_OVER_TIME: "quantile_over_time"
STDDEV_OVER_TIME: "stddev_over_time"
STDVAR_OVER_TIME: "stdvar_over_time"
// Aggregation operators
SUM: "sum"
MIN: "min"
MAX: "max"
AVG: "avg"
GROUP: "group"
STDDEV: "stddev"
STDVAR: "stdvar"
COUNT: "count"
COUNT_VALUES: "count_values"
BOTTOMK: "bottomk"
TOPK: "topk"
QUANTILE: "quantile"
// Aggregation modifiers
BY: "by"
WITHOUT: "without"
// Join modifiers
ON: "on"
IGNORING: "ignoring"
GROUP_LEFT: "group_left"
GROUP_RIGHT: "group_right"
// Logical operators
AND: "and"
OR: "or"
UNLESS: "unless"
OFFSET: "offset"
BOOL: "bool"
NUMBER: /[0-9]+(\\.[0-9]+)?/
STRING\
: "'" /([^'\\\\]|\\\\.)*/ "'"
| "\\"" /([^\\"\\\\]|\\\\.)*/ "\\""
DURATION: DIGIT+ ("s" | "m" | "h" | "d" | "w" | "y")
METRIC_NAME: (LETTER | "_" | ":") (DIGIT | LETTER | "_" | ":")*
LABEL_NAME: (LETTER | "_") (DIGIT | LETTER | "_")*
%import common.DIGIT
%import common.LETTER
%import common.WS
%ignore WS
"""
|
ftxus = {
'api_key':'YOUR_API_KEY',
'api_secret':'YOUR_API_SECRET'
}
|
a = [1, 2, 3, 4]
def subset(a, n):
if n == 1:
return n
else:
return (subset(a[n - 1]), subset(a[n - 2]))
print(subset(a, n=4))
|
def print_formatted(number):
# your code goes here
for i in range(1, number +1):
width = len(f"{number:b}")
print(f"{i:{width}} {i:{width}o} {i:{width}X} {i:{width}b}")
|
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [inf] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != inf else -1
|
#
# PySNMP MIB module Intel-Common-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Intel-Common-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:54: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)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
ModuleIdentity, ObjectIdentity, iso, Integer32, Bits, Counter64, Counter32, Gauge32, NotificationType, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, TimeTicks, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "ObjectIdentity", "iso", "Integer32", "Bits", "Counter64", "Counter32", "Gauge32", "NotificationType", "Unsigned32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "TimeTicks", "enterprises")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
intel = MibIdentifier((1, 3, 6, 1, 4, 1, 343))
identifiers = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1))
products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2))
experimental = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 3))
information_technology = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 4)).setLabel("information-technology")
sysProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 5))
mib2ext = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 6))
hw = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 7))
wekiva = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 111))
systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1))
objects = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 2))
comm_methods = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 3)).setLabel("comm-methods")
pc_systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 1)).setLabel("pc-systems")
proxy_systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 2)).setLabel("proxy-systems")
hub_systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3)).setLabel("hub-systems")
switch_systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 4)).setLabel("switch-systems")
local_proxy_1 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 3, 1)).setLabel("local-proxy-1")
pc_novell_1 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 3, 2)).setLabel("pc-novell-1")
express10_100Stack = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 1)).setLabel("express10-100Stack")
express12TX = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 2))
express24TX = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 3))
expressReserved = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 4))
expressBridge = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 6))
express210_12 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 7)).setLabel("express210-12")
express210_24 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 8)).setLabel("express210-24")
express220_12 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 9)).setLabel("express220-12")
express220_24 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 10)).setLabel("express220-24")
express300Stack = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 11))
express320_16 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 12)).setLabel("express320-16")
express320_24 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 13)).setLabel("express320-24")
pc_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 1)).setLabel("pc-products")
hub_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 2)).setLabel("hub-products")
proxy = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 3))
print_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 4)).setLabel("print-products")
network_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5)).setLabel("network-products")
snmp_agents = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 6)).setLabel("snmp-agents")
nic_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 7)).setLabel("nic-products")
server_management = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 10)).setLabel("server-management")
switch_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 11)).setLabel("switch-products")
i2o = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 120))
express110 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 2, 1))
netport_1 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 1)).setLabel("netport-1")
netport_2 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 2)).setLabel("netport-2")
netport_express = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 3)).setLabel("netport-express")
lanDesk = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 1))
ld_alarms = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 1, 1)).setLabel("ld-alarms")
internetServer_2 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 2)).setLabel("internetServer-2")
iS_alarms = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 2, 1)).setLabel("iS-alarms")
mibBuilder.exportSymbols("Intel-Common-MIB", express220_24=express220_24, express110=express110, snmp_agents=snmp_agents, switch_systems=switch_systems, objects=objects, proxy=proxy, lanDesk=lanDesk, express12TX=express12TX, mib2ext=mib2ext, experimental=experimental, express210_24=express210_24, sysProducts=sysProducts, netport_1=netport_1, internetServer_2=internetServer_2, intel=intel, pc_novell_1=pc_novell_1, products=products, express320_24=express320_24, proxy_systems=proxy_systems, express320_16=express320_16, identifiers=identifiers, express300Stack=express300Stack, wekiva=wekiva, express10_100Stack=express10_100Stack, hub_systems=hub_systems, ld_alarms=ld_alarms, server_management=server_management, switch_products=switch_products, i2o=i2o, netport_express=netport_express, network_products=network_products, expressBridge=expressBridge, express220_12=express220_12, local_proxy_1=local_proxy_1, systems=systems, comm_methods=comm_methods, express210_12=express210_12, pc_products=pc_products, hub_products=hub_products, expressReserved=expressReserved, netport_2=netport_2, pc_systems=pc_systems, hw=hw, express24TX=express24TX, print_products=print_products, information_technology=information_technology, iS_alarms=iS_alarms, nic_products=nic_products)
|
name = input()
class_school = 1
sum_of_grades = 0
ejected = False
failed = 0
while True:
grade = float(input())
if grade >= 4.00:
sum_of_grades += grade
if class_school == 12:
break
class_school += 1
else:
failed += 1
if failed == 2:
ejected = True
break
if ejected:
print(f"{name} has been excluded at {class_school} grade")
else:
average = sum_of_grades / class_school
print(f"{name} graduated. Average grade: {average:.2f}")
|
class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
parent=[i for i in range(len(row))]
for i in range(1,len(row),2):
parent[i]-=1
def findpath(u,parent):
if parent[u]!=u:
parent[u]=findpath(parent[u],parent)
return parent[u]
for i in range(0,len(row),2):
u_parent=findpath(row[i],parent)
v_parent=findpath(row[i+1],parent)
parent[u_parent]=v_parent
return (len(row)//2)-sum([1 for i in range(0,len(row),2) if parent[i]==parent[i+1]==i])
|
"""
Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre
a temperatura em graus Celsius.
C = (5 * (F-32) / 9)
"""
|
class Token:
def __init__(self, type=None, value=None):
self.type = type
self.value = value
def __str__(self):
return "Token({0}, {1})".format(self.type, self.value) |
"""
Define convention-based global, coordinate and variable attributes
in one place for consistent reuse
"""
DEFAULT_BEAM_COORD_ATTRS = {
"frequency": {
"long_name": "Transducer frequency",
"standard_name": "sound_frequency",
"units": "Hz",
"valid_min": 0.0,
},
"ping_time": {
"long_name": "Timestamp of each ping",
"standard_name": "time",
"axis": "T",
},
"range_bin": {"long_name": "Along-range bin (sample) number, base 0"},
}
DEFAULT_PLATFORM_COORD_ATTRS = {
"location_time": {
"axis": "T",
"long_name": "Timestamps for NMEA datagrams",
"standard_name": "time",
}
}
DEFAULT_PLATFORM_VAR_ATTRS = {
"latitude": {
"long_name": "Platform latitude",
"standard_name": "latitude",
"units": "degrees_north",
"valid_range": (-90.0, 90.0),
},
"longitude": {
"long_name": "Platform longitude",
"standard_name": "longitude",
"units": "degrees_east",
"valid_range": (-180.0, 180.0),
},
"pitch": {
"long_name": "Platform pitch",
"standard_name": "platform_pitch_angle",
"units": "arc_degree",
"valid_range": (-90.0, 90.0),
},
"roll": {
"long_name": "Platform roll",
"standard_name": "platform_roll_angle",
"units": "arc_degree",
"valid_range": (-90.0, 90.0),
},
"heave": {
"long_name": "Platform heave",
"standard_name": "platform_heave_angle",
"units": "arc_degree",
"valid_range": (-90.0, 90.0),
},
"water_level": {
"long_name": "z-axis distance from the platform coordinate system "
"origin to the sonar transducer",
"units": "m",
},
}
|
"""
********************************************************************************
* Name: pagintate.py
* Author: nswain
* Created On: April 17, 2018
* Copyright: (c) Aquaveo 2018
********************************************************************************
"""
def paginate(objects, results_per_page, page, result_name, sort_by_raw=None, sort_reversed=False):
"""
Paginate given list of objects.
Args:
objects(list): list of objects to paginate.
results_per_page(int): maximum number of results to show on a page.
page(int): page to view.
result_name(str): name to use when referencing the objects.
sort_by_raw(str): sort field if applicable.
sort_reversed(boo): indicates whether the sort is reversed or not.
Returns:
list, dict: list of objects for current page, metadata form paginantion page.
"""
results_per_page_options = [5, 10, 20, 40, 80, 120]
num_objects = len(objects)
if num_objects <= results_per_page:
page = 1
min_index = (page - 1) * results_per_page
max_index = min(page * results_per_page, num_objects)
paginated_objects = objects[min_index:max_index]
enable_next_button = max_index < num_objects
enable_previous_button = min_index > 0
pagination_info = {
'num_results': num_objects,
'result_name': result_name,
'page': page,
'min_showing': min_index + 1 if max_index > 0 else 0,
'max_showing': max_index,
'next_page': page + 1,
'previous_page': page - 1,
'sort_by': sort_by_raw,
'sort_reversed': sort_reversed,
'enable_next_button': enable_next_button,
'enable_previous_button': enable_previous_button,
'hide_buttons': page == 1 and max_index == num_objects,
'hide_header_buttons': len(paginated_objects) < 20,
'show': results_per_page,
'results_per_page_options': [x for x in results_per_page_options if x <= num_objects],
'hide_results_per_page_options': num_objects <= results_per_page_options[0],
}
return paginated_objects, pagination_info
|
def not_found_handler():
return '404. Path not found'
def internal_error_handler():
return '500. Internal error' |
# ~*~ coding: utf-8 ~*~
__doc__ = """
`opencannabis.media`
---------------------------
Records and definitions that structure digital media and related assets.
"""
# `opencannabis.media`
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.