content
stringlengths
7
1.05M
"""-------------------------------------------------------------------- * $Id: GUI_definition.py $ * * This file is part of libRadtran. * Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer, * Claudia Emde, Robert Buras * * ######### Contact info: http://www.libradtran.org ######### * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. *--------------------------------------------------------------------""" __all__ = ["FileInput", "FloatInput", "TextInput", "IntegerInput", "ListInput", "IntegerListInput", "BooleanInput", "VariableNumberOfLinesInput"] class Input(): def __init__(self, name=None, optional=False): """ name = displayed above input in GUI for options with multiple inputs """ assert not name is None self.name = name self.optional = optional class NumberInput(Input): def __init__(self, default=None, valid_range=(-1e99, 1e99),**kwargs): Input.__init__(self, **kwargs) # This should be removed when/if the option files are cleaned up if default in ("NOT_DEFINED_INTEGER", "NOT_DEFINED_FLOAT"): default = None self.default = default self.valid_range = valid_range class FileInput(Input): def __init__(self, **kwargs): Input.__init__(self, **kwargs) class FloatInput(NumberInput): pass class TextInput(Input): def __init__(self, default=None, **kwargs): Input.__init__(self, **kwargs) self.default = default class IntegerInput(NumberInput): def __init__(self, default=None, **kwargs): # This should be removed when/if the option files are cleaned up if default in ("NOT_DEFINED_INTEGER", "NOT_DEFINED_FLOAT"): default = None if not default is None: assert type(default) == int, \ "Default of integer input must be an integer!" NumberInput.__init__(self, default=default, **kwargs) class ListInput(Input): """ Valid inputs are one among a list of strings """ def __init__(self, default=None, valid_range=None, optional=False,logical_file=False, **kwargs): Input.__init__(self, optional=optional, **kwargs) assert not valid_range is None, "You must provide a range of choices!" self.valid_range = [] for val in valid_range: if isinstance(val,str): self.valid_range.append( val.lower() ) else: self.valid_range.append( val ) if optional: if self.valid_range.count(""): self.valid_range.remove("") self.valid_range.insert(0,"") if isinstance(default,str): default=default.lower() if default is None: default = self.valid_range[0] assert default in self.valid_range, "Default not among valid options!" self.default = default self.logical_file=logical_file class IntegerListInput(ListInput): def __init__(self, **kwargs): ListInput.__init__(self, **kwargs) self.default = str(self.default) self.valid_range = tuple([str(i) for i in self.valid_range]) class BooleanInput(Input): pass class VariableNumberOfLinesInput(Input): def __init__(self, valid_range=None, **kwargs): Input.__init__(self, **kwargs) assert not valid_range is None self.valid_range = valid_range
test = { 'name': 'What Would Scheme Display?', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" scm> (- 10 4) 6 scm> (* 7 6) 42 scm> (+ 1 2 3 4) 10 scm> (/ 8 2 2) 2 scm> (quotient 29 5) 5 scm> (modulo 29 5) 4 """, 'hidden': False, 'locked': False }, { 'code': r""" scm> (= 1 3) ; Scheme uses '=' instead of '==' for comparison #f scm> (< 1 3) #t scm> (or #t #f) ; or special form short circuits #t scm> (and #t #f (/ 1 0)) #f scm> (not #t) #f """, 'hidden': False, 'locked': False }, { 'code': r""" scm> (define x 3) x scm> x 3 scm> (define y (+ x 4)) y scm> y 7 scm> (define x (lambda (y) (* y 2))) x scm> (x y) 14 """, 'hidden': False, 'locked': False }, { 'code': r""" scm> (if (print 1) (print 2) (print 3)) 1 2 scm> (* (if (> 3 2) 1 2) (+ 4 5)) 9 scm> (define foo (lambda (x y z) (if x y z))) foo scm> (foo 1 2 (print 'hi)) hi 2 scm> ((lambda (a) (print 'a)) 100) a """, 'hidden': False, 'locked': False } ], 'scored': True, 'setup': r""" """, 'teardown': '', 'type': 'scheme' } ] }
MODAL_REQUEST = { "callback_id": "change_request_review", "type": "modal", "title": { "type": "plain_text", "text": "Switcher Change Request" }, "submit": { "type": "plain_text", "text": "Submit" }, "close": { "type": "plain_text", "text": "Cancel" }, "blocks": [ { "type": "context", "elements": [ { "type": "plain_text", "text": "Select the options below to request a Switcher status change." } ] }, { "type": "divider" }, { "type": "section", "text": { "type": "mrkdwn", "text": "Environment" }, "accessory": { "type": "static_select", "placeholder": { "type": "plain_text", "text": "Select an item" }, "options": [], "action_id": "selection_environment" } }, { "type": "section", "text": { "type": "mrkdwn", "text": "Group" }, "accessory": { "type": "static_select", "placeholder": { "type": "plain_text", "text": "Select an item" }, "options": [ { "text": { "type": "plain_text", "text": "-" }, "value": "-" } ], "action_id": "selection_group" } }, { "type": "section", "text": { "type": "mrkdwn", "text": "Switcher" }, "accessory": { "type": "static_select", "placeholder": { "type": "plain_text", "text": "Select an item" }, "options": [ { "text": { "type": "plain_text", "text": "-" }, "value": "-" } ], "action_id": "selection_switcher" } }, { "type": "section", "text": { "type": "mrkdwn", "text": "Status" }, "accessory": { "type": "static_select", "placeholder": { "type": "plain_text", "text": "Select an item" }, "options": [ { "text": { "type": "plain_text", "text": "-" }, "value": "-" } ], "action_id": "selection_status" } } ] } APP_HOME = { "type": "home", "blocks": [ { "type": "image", "image_url": "https://raw.githubusercontent.com/switcherapi/switcherapi-assets/master/samples/slack/logo.png", "alt_text": "Switcher Slack App" }, { "type": "context", "elements": [ { "type": "plain_text", "text": "What are you up today?" } ] }, { "type": "divider" }, { "type": "actions", "elements": [ { "type": "button", "text": { "type": "plain_text", "text": "Open Change Request" }, "action_id": "change_request" } ] } ] }
class DataHelper: """ ctpbee开发的数据读取器 ‘ 针对各自csv数据以及json或者 数据库里面的数据 需要你提供数据地图以及如何进行字段转换 """ def __init__(self, mapping: str): self.mapping = mapping def read_json(self, json_path: str): raise NotImplemented def read_csv(self, csv_path: str): raise NotImplemented
def calculate_sleep_time_for_djymi(minutes_for_finished): # сколько всего минут будет отведено на сон st = minutes_for_finished // 2 # сколько целых часов будет длится сон h = st // 60 # сколько минут (учитывая часы) будет длится сон m = st % 60 return h, m def hh_mm_to_str(hh, mm): if hh == 0: return f'{mm} м' return f'{hh} ч {mm} м' if __name__ == "__main__": t = int(input("Введите количество минут до конца поездки: ")) hh, mm = calculate_sleep_time_for_djymi(t) hm = hh_mm_to_str(hh, mm) print("Джими потратит на сон " + hm)
# File: wildfire_consts.py # # Copyright (c) 2016-2022 Splunk Inc. # # 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. WILDFIRE_JSON_BASE_URL = "base_url" WILDFIRE_JSON_TASK_ID = "task_id" WILDFIRE_JSON_API_KEY = "api_key" # pragma: allowlist secret WILDFIRE_JSON_MALWARE = "malware" WILDFIRE_JSON_TASK_ID = "id" WILDFIRE_JSON_URL = "url" WILDFIRE_JSON_HASH = "hash" WILDFIRE_JSON_PLATFORM = "platform" WILDFIRE_JSON_POLL_TIMEOUT_MINS = "timeout" WILDFIRE_ERR_UNABLE_TO_PARSE_REPLY = "Unable to parse reply from device" WILDFIRE_ERR_REPLY_FORMAT_KEY_MISSING = "None '{key}' missing in reply from device" WILDFIRE_ERR_REPLY_NOT_SUCCESS = "REST call returned '{status}'" WILDFIRE_SUCC_REST_CALL_SUCCEEDED = "REST Api call succeeded" WILDFIRE_ERR_REST_API = "REST Api Call returned error, status_code: {status_code}, detail: {detail}" WILDFIRE_ERR_FILE_NOT_FOUND_IN_VAULT = "File not found in vault" WILDFIRE_INVALID_INT = "Please provide a valid integer value in the {param}" WILDFIRE_ERR_INVALID_PARAM = "Please provide a non-zero positive integer in the {param}" WILDFIRE_ERR_NEGATIVE_INT_PARAM = "Please provide a valid non-negative integer value in the {param}" WILDFIRE_TEST_PDF_FILE = "wildfire_test_connectivity.pdf" WILDFIRE_SLEEP_SECS = 10 WILDFIRE_MSG_REPORT_PENDING = "Report Pending" WILDFIRE_MSG_MAX_POLLS_REACHED = ("Reached max polling attempts. " "Please use the MD5 or Sha256 of the file as a parameter to <b>get report</b> to query the report status.") WILDFIRE_TIMEOUT = "'timeout' action parameter" # in minutes WILDFIRE_MAX_TIMEOUT_DEF = 10
birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) #(1) Write three separate list comprehensions that create three different # lists containing the latin names, common names and mean body masses for # each species in birds, respectively. # (2) Now do the same using conventional loops (you can shoose to do this # before 1 !). # ANNOTATE WHAT EVERY BLOCK OR IF NECESSARY, LINE IS DOING! # ALSO, PLEASE INCLUDE A DOCSTRING AT THE BEGINNING OF THIS FILE THAT # SAYS WHAT THE SCRIPT DOES AND WHO THE AUTHOR IS.
# -*- coding: utf-8 -*- """ Created on Sat Jun 29 22:07:42 2019 @author: CLIENTE """ #pega o heroi.txt with open('C:\\Users\\CLIENTE\\Desktop\\heroi.txt','r',encoding='utf8') as arquivo: dados = arquivo.readlines() for i in range(len(dados)): dados[i] = dados[i].rstrip('\n').split(';') #cria o arquivo.tex latex = open('C:\\Users\\CLIENTE\\Desktop\\Relações Aluno-Nota.tex','w+') latex.write('\\documentclass[12pt]{article} \n \ \\usepackage[utf8]{inputenc} \n \ \\usepackage{pgfplots} \ \\begin{document} \n \ \\section*{Tabela com as médias de cada aluno} \n \ \\begin{tabular}{c|c} \n \ Nome & Sobrenome \\\\ \n \ \\hline \n') #escolhi botar aquela expressão para a média das notas dos alunos pois ela é a #que mais se assemelha ao sistema da ufsc de arredondamento, #e também porque caso eu não arredondasse os números possuiriam muitas casas #após a vírgula. for i in range(1,len(dados)): latex.write('{} {} & {} \\\\ \n'.format(dados[i][0],dados[i][1],round(2*(float(dados[i][2])+float(dados[i][3])+float(dados[i][4]))/3)/2)) latex.write('\\end{tabular} \n') #coloquei um for aqui para fazer os três gráficos com as notas de uma vez, que #é menos trabalhoso que copiar e colar o código duas vezes e mudar os índices for prova in range(2,5): latex.write('\\begin{center}\\begin{tikzpicture}\\begin{axis}[xbar,enlargelimits=0.10,width = \\textwidth,ytick=data,height=15cm,legend style={at={(0.5,-0.08)},anchor=north,legend columns=-1},xlabel={Nota},symbolic y coords={') for i in range(1,len(dados)): latex.write('{} {},'.format(dados[i][0],dados[i][1])) latex.write('}] \n \ \\addplot coordinates {') for i in range(1,len(dados)): latex.write('({},{} {}) '.format(dados[i][prova],dados[i][0],dados[i][1])) latex.write('}; \n') latex.write('\\legend{{Prova {}}}\n'.format(prova-1)) latex.write('\\end{axis} \n \\end{tikzpicture} \\end{center} \n') #mas desta vez copiei e colei pois era mais simples que ter que colocar um if #no for anterior latex.write('\\begin{center}\\begin{tikzpicture}\\begin{axis}[xbar,enlargelimits=0.10,width = \\textwidth,ytick=data,height=15cm,legend style={at={(0.5,-0.08)},anchor=north,legend columns=-1},xlabel={Nota},symbolic y coords={') for i in range(1,len(dados)): latex.write('{} {},'.format(dados[i][0],dados[i][1])) latex.write('}] \n') latex.write('\\addplot coordinates {') for i in range(1,len(dados)): latex.write('({},{} {}) '.format(round((2*(float(dados[i][2])+float(dados[i][3])+float(dados[i][4]))/3)/2),dados[i][0],dados[i][1])) latex.write('}; \n \ \\legend{{Média das provas}}\n \ \\end{axis} \n \\end{tikzpicture} \\end{center} \n \ \\end{document}') latex.close()
# -*- coding: utf-8 -*- """ Created on Sun Jan 21 16:19:46 2018 @author: Sherry Done """ def CorsairStats(): #Get base stats Agility = 7 + d6() Alertness = 3 + d6() Charm = 2 + d6() Cunning = 12 + d6() Dexterity = 13 + d6() Fate = 4 + d6() Intelligence = 10 + d6() Knowledge = 9 + d6() Mechanical = 11 + d6() Nature = 8 + d6() Stamina = 5 + d6() Strength = 6 + d6() #get speciality list started Specialties = ['Conceal', 'Filch', 'Forgery', 'Unlock'] #determine Age, Night Vision, Racial Benefits Age = Intelligence + Knowledge - 5 Night_Vision = "No" Racial_Ability = "Growth" Uses_Per_Day = 2 #Get physical stats Height = Strength + d6() if Height <= 9: Height = "Tiny" elif Height <= 13: Height = "Very Short" elif Height <= 17: Height = "Short" elif Height <= 18: Height = "Average" Weight = Stamina + d6() if Weight <= 8: Weight = "Very Thin" elif Weight <= 10: Weight = "Thin" elif Weight <= 13: Weight = "Average" elif Weight <= 15: Weight = "Heavy" elif Weight <= 17: Weight = "Very Heavy" #get family background Background = Fate + d6() if Background == 6: Background = "Derelict" Bronze = 10 Free = 8 new_specs = ["Lie", "Search"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 7: Background = "Serf" Bronze = 10 Free = 8 new_specs = ["Plants", "Forage"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 8: Background = "Herder" Bronze = 10 Free = 8 new_specs = ["Tame", "Direction"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 9: Background = "Gatherer" Bronze = 110 Free = 7 new_specs = ["Plants", "Forage"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 10: Background = "Hunter" Bronze = 110 Free = 7 new_specs = ["Forage", "Track"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 11: Background = "Robber" Bronze = 110 Free = 7 new_specs = ["Sword", "Bully"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 12: Background = "Counterfeiter" Bronze = 210 Free = 6 new_specs = ["Contacts", "Literacy"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 13: Background = "Burglar" Bronze = 210 Free = 6 new_specs = ["Unlock", "Stealth"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 14: Background = "Story-Teller" Bronze = 210 Free = 6 new_specs = ["Legends", "Entertain"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 15: Background = "Toolmaker" Bronze = 310 Free = 5 new_specs = ["Build", "Bargain"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1 elif Background == 16: Background = "Healer" Bronze = 310 Free = 5 new_specs = ["Plants", "Medical"] for ea in new_specs: if ea not in Specialties: Specialties.append(ea) else: Free += 1
COLORS = { 'PROBLEM': 'red', 'RECOVERY': 'green', 'UP': 'green', 'ACKNOWLEDGEMENT': 'purple', 'FLAPPINGSTART': 'yellow', 'WARNING': 'yellow', 'UNKNOWN': 'gray', 'CRITICAL': 'red', 'FLAPPINGEND': 'green', 'FLAPPINGSTOP': 'green', 'FLAPPINGDISABLED': 'purple', 'DOWNTIMESTART': 'red', 'DOWNTIMESTOP': 'green', 'DOWNTIMEEND': 'green' }
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Mass density (concentration)', 'units': 'kg m-3'}, {'abbr': 1, 'code': 1, 'title': 'Column-integrated mass density', 'units': 'kg m-2'}, {'abbr': 2, 'code': 2, 'title': 'Mass mixing ratio (mass fraction in air)', 'units': 'kg/kg'}, {'abbr': 3, 'code': 3, 'title': 'Atmosphere emission mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 4, 'code': 4, 'title': 'Atmosphere net production mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 5, 'code': 5, 'title': 'Atmosphere net production and emission mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 6, 'code': 6, 'title': 'Surface dry deposition mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 7, 'code': 7, 'title': 'Surface wet deposition mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 8, 'code': 8, 'title': 'Atmosphere re-emission mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 9, 'code': 9, 'title': 'Wet deposition by large-scale precipitation mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 10, 'code': 10, 'title': 'Wet deposition by convective precipitation mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 11, 'code': 11, 'title': 'Sedimentation mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 12, 'code': 12, 'title': 'Dry deposition mass flux', 'units': 'kg m-2 s-1'}, {'abbr': 13, 'code': 13, 'title': 'Transfer from hydrophobic to hydrophilic', 'units': 'kg kg-1 s-1'}, {'abbr': 14, 'code': 14, 'title': 'Transfer from SO2 (sulphur dioxide) to SO4 (sulphate)', 'units': 'kg kg-1 s-1'}, {'abbr': 50, 'code': 50, 'title': 'Amount in atmosphere', 'units': 'mol'}, {'abbr': 51, 'code': 51, 'title': 'Concentration in air', 'units': 'mol m-3'}, {'abbr': 52, 'code': 52, 'title': 'Volume mixing ratio (fraction in air)', 'units': 'mol/mol'}, {'abbr': 53, 'code': 53, 'title': 'Chemical gross production rate of concentration', 'units': 'mol m-3 s-1'}, {'abbr': 54, 'code': 54, 'title': 'Chemical gross destruction rate of concentration', 'units': 'mol m-3 s-1'}, {'abbr': 55, 'code': 55, 'title': 'Surface flux', 'units': 'mol m-2 s-1'}, {'abbr': 56, 'code': 56, 'title': 'Changes of amount in atmosphere', 'units': 'mol/s'}, {'abbr': 57, 'code': 57, 'title': 'Total yearly average burden of the atmosphere', 'units': 'mol'}, {'abbr': 58, 'code': 58, 'title': 'Total yearly averaged atmospheric loss', 'units': 'mol/s'}, {'abbr': 59, 'code': 59, 'title': 'Aerosol number concentration', 'units': 'm-3'}, {'abbr': 60, 'code': 60, 'title': 'Aerosol specific number concentration', 'units': 'kg-1'}, {'abbr': 61, 'code': 61, 'title': 'Maximum of mass density in layer', 'units': 'kg m-3'}, {'abbr': 62, 'code': 62, 'title': 'Height of maximum mass density', 'units': 'm'}, {'abbr': 63, 'code': 63, 'title': 'Column-averaged mass density in layer', 'units': 'kg m-3'}, {'abbr': 100, 'code': 100, 'title': 'Surface area density (aerosol)', 'units': 'm-1'}, {'abbr': 101, 'code': 101, 'title': 'Vertical visual range', 'units': 'm'}, {'abbr': 102, 'code': 102, 'title': 'Aerosol optical thickness', 'units': 'Numeric'}, {'abbr': 103, 'code': 103, 'title': 'Single scattering albedo', 'units': 'Numeric'}, {'abbr': 104, 'code': 104, 'title': 'Asymmetry factor', 'units': 'Numeric'}, {'abbr': 105, 'code': 105, 'title': 'Aerosol extinction coefficient', 'units': 'm-1'}, {'abbr': 106, 'code': 106, 'title': 'Aerosol absorption coefficient', 'units': 'm-1'}, {'abbr': 107, 'code': 107, 'title': 'Aerosol lidar backscatter from satellite', 'units': 'm-1 sr-1'}, {'abbr': 108, 'code': 108, 'title': 'Aerosol lidar backscatter from the ground', 'units': 'm-1 sr-1'}, {'abbr': 109, 'code': 109, 'title': 'Aerosol lidar extinction from satellite', 'units': 'm-1'}, {'abbr': 110, 'code': 110, 'title': 'Aerosol lidar extinction from the ground', 'units': 'm-1'}, {'abbr': 111, 'code': 111, 'title': 'Angstrom exponent', 'units': 'Numeric'}, {'abbr': None, 'code': 255, 'title': 'Missing'})
#=========================================================================== # # Port to use for the web server. Configure the Eagle to use this # port as it's 'cloud provider' using http://host:PORT # #=========================================================================== httpPort = 22042 #=========================================================================== # # MQTT topic names # #=========================================================================== # Meter reading topic (reports current meter reading in kWh) mqttEnergy = 'power/elec/Home/energy' # Instantaneous power usage topic (reports power usage in W) mqttPower = 'power/elec/Home/power' #Current price topic (returns current price of electricity from meter) mqttPrice = 'power/elec/Home/price' #Current rate label (returns rate label from meter) mqttRateLabel = 'power/elec/Home/ratelabel' #=========================================================================== # # Logging configuration. Env variables are allowed in the file name. # #=========================================================================== logFile = '/var/log/tHome/eagle.log' logLevel = 20
def runUserScript(func, params, paramTypes): if (len(params) != len(paramTypes)): onParameterError() newParams = [] for i, val in enumerate(params): newParams.append(parseParameter(i, paramTypes[i], val)) func(*newParams) class Node: def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next def parseNode(param): first = Node(param[0], None, None, None) arr = [] arr.append([first, 0]) for i, val in enumerate(param): if i is 0: continue top = arr[0] val = None if param[i] is None else Node(param[i], None, None, None) if top[1] is 0: top[0].left = val top[1] = 1 else: top[0].right = val arr.pop(0) if val is not None: arr.append([val, 0]) return first def parseSpecialParameter(index, paramType, param): if paramType == "Node": return parseNode(param) return None
def readlines(fname): try: with open(fname, 'r') as fpt: return fpt.readlines() except: return [] def convert(data): for i in range(len(data)): try: data[i] = float(data[i]) except ValueError: continue def csv_lst(fname): l = readlines(fname) if len(l) == 0: raise Exception('Missing file') output = [] for i in l[1:]: data = i.split(',') convert(data) output.append(data) return output dd = csv_lst('titanic.csv') sur = 0 for x in dd: sur += x[0] print(sur)
def functionA(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor: ## TODO for students output = A.sum(axis = 0) * B.sum() return output def functionB(C: torch.Tensor) -> torch.Tensor: # TODO flatten the tensor C C = C.flatten() # TODO create the idx tensor to be concatenated to C # here we're going to do flatten and unsqueeze, but reshape can also be used idx_tensor = torch.arange(0, len(C)) # TODO concatenate the two tensors output = torch.cat([idx_tensor.unsqueeze(0), C.unsqueeze(0)], axis = 1) return output def functionC(D: torch.Tensor, E: torch.Tensor) -> torch.Tensor: # TODO check we can reshape E into the shape of D if torch.numel(D) == torch.numel(E) : # TODO reshape E into the shape of D E = E.reshape(D.shape) # TODO sum the two tensors output = D + E else: # TODO flatten both tensors # this time we'll use reshape to keep the singleton dimension D = D.reshape(1,-1) E = E.reshape(1,-1) # TODO concatenate the two tensors in the correct dimension output = torch.cat([D,E], axis = 1) return output print(functionA(torch.tensor([[1,1], [1,1]]), torch.tensor([ [1,2,3],[1,2,3] ]) )) print(functionB(torch.tensor([ [2,3],[-1,10] ]))) print(functionC(torch.tensor([[1, -1],[-1,3]]), torch.tensor([[2,3,0,2]]))) print(functionC(torch.tensor([[1, -1],[-1,3]]), torch.tensor([[2,3,0]])))
minimum_points = 100 data_points = 150 if data_points >= minimum_points: print("There are enough data points!") if data_points < minimum_points: print("Keep collecting data.")
class restaurant: yiyecek = { "balık":20, "tavk":17, "köfte":15 } icecek = { "kola":3, "ayran":1, "su":1 } tatli = { "baklava":8, "künefe":10, "şöbiyet":8 } def __init__(self, czd): self.cz = 0 def yk(self, ss): if restaurant.yiyecek[ss]: self.cz += restaurant.yiyecek[ss] def ik(self, ss): if restaurant.icecek[ss]: self.cz += restaurant.icecek[ss] def t(self, ss): if restaurant.tatli[ss]: self.cz += restaurant.tatli[ss] def hesap(self): print(f"Hesabınız: {self.cz}TL") if __name__ == "__main__": m = restaurant(100) m.yk("köfte") m.ik("kola") m.t("künefe") m.hesap()
class Hand: def __init__(self): self.cards = [] self.value = 0 def add_card(self, card): self.cards.append(card) def calculate_value(self): self.value = 0 has_ace = False for card in self.cards: if card.value.isnumeric(): self.value += int(card.value) else: if card.value == "A": has_ace = True self.value += 11 else: self.value += 10 if has_ace and self.value > 21: self.value -= 10 def get_value(self): self.calculate_value() return self.value
# This module is used in `test_doctest`. # It must not have a docstring. def func_with_docstring(): """Some unrelated info.""" def func_without_docstring(): pass def func_with_doctest(): """ This function really contains a test case. >>> func_with_doctest.__name__ 'func_with_doctest' """ return 3 class ClassWithDocstring: """Some unrelated class information.""" class ClassWithoutDocstring: pass class ClassWithDoctest: """This class really has a test case in it. >>> ClassWithDoctest.__name__ 'ClassWithDoctest' """ class MethodWrapper: def method_with_docstring(self): """Method with a docstring.""" def method_without_docstring(self): pass def method_with_doctest(self): """ This has a doctest! >>> MethodWrapper.method_with_doctest.__name__ 'method_with_doctest' """
# -*- coding: utf-8 -*- """ pyalgs ~~~~~ pyalgs provides the python implementation of the Robert Sedgwick's Coursera course on Algorithms (Part I and Part II). :copyright: (c) 2017 by Xianshun Chen. :license: BSD, see LICENSE for more details. """ __version__ = '0.01-dev'
# # PySNMP MIB module GSM7312-QOS-ACL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GSM7312-QOS-ACL-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:20:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint") gsm7312QOS, = mibBuilder.importSymbols("GSM7312-QOS-MIB", "gsm7312QOS") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") TimeTicks, Unsigned32, Counter32, ModuleIdentity, Bits, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, NotificationType, MibIdentifier, Integer32, iso, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Unsigned32", "Counter32", "ModuleIdentity", "Bits", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "NotificationType", "MibIdentifier", "Integer32", "iso", "Counter64") DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus") gsm7312QOSACL = ModuleIdentity((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2)) gsm7312QOSACL.setRevisions(('2003-05-06 12:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: gsm7312QOSACL.setRevisionsDescriptions(('Initial revision.',)) if mibBuilder.loadTexts: gsm7312QOSACL.setLastUpdated('200305061200Z') if mibBuilder.loadTexts: gsm7312QOSACL.setOrganization('Netgear') if mibBuilder.loadTexts: gsm7312QOSACL.setContactInfo('') if mibBuilder.loadTexts: gsm7312QOSACL.setDescription('') aclTable = MibTable((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 1), ) if mibBuilder.loadTexts: aclTable.setStatus('current') if mibBuilder.loadTexts: aclTable.setDescription('A table of ACL instances.') aclEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 1, 1), ).setIndexNames((0, "GSM7312-QOS-ACL-MIB", "aclIndex")) if mibBuilder.loadTexts: aclEntry.setStatus('current') if mibBuilder.loadTexts: aclEntry.setDescription('') aclStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 1, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclStatus.setStatus('current') if mibBuilder.loadTexts: aclStatus.setDescription('Status of this instance. active(1) - this ACL instance is active createAndGo(4) - set to this value to create an instance destroy(6) - set to this value to delete an instance') aclIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 1, 1, 1), Integer32()) if mibBuilder.loadTexts: aclIndex.setStatus('current') if mibBuilder.loadTexts: aclIndex.setDescription('The ACL index this instance is associated with.') aclIfTable = MibTable((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 2), ) if mibBuilder.loadTexts: aclIfTable.setStatus('current') if mibBuilder.loadTexts: aclIfTable.setDescription('A table of ACL interface instances.') aclIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 2, 1), ).setIndexNames((0, "GSM7312-QOS-ACL-MIB", "aclIndex"), (0, "GSM7312-QOS-ACL-MIB", "aclIfIndex"), (0, "GSM7312-QOS-ACL-MIB", "aclIfDirection")) if mibBuilder.loadTexts: aclIfEntry.setStatus('current') if mibBuilder.loadTexts: aclIfEntry.setDescription('') aclIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: aclIfIndex.setStatus('current') if mibBuilder.loadTexts: aclIfIndex.setDescription('The interface this ACL instance is associated with.') aclIfDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("inbound", 1), ("outbound", 2)))) if mibBuilder.loadTexts: aclIfDirection.setStatus('current') if mibBuilder.loadTexts: aclIfDirection.setDescription('The direction this ACL instance applies.') aclIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 2, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclIfStatus.setStatus('current') if mibBuilder.loadTexts: aclIfStatus.setDescription('Status of this instance. active(1) - this ACL index instance is active createAndGo(4) - set to this value to assign an interface to an ACL destroy(6) - set to this value to remove an interface to an ACL') aclRuleTable = MibTable((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3), ) if mibBuilder.loadTexts: aclRuleTable.setStatus('current') if mibBuilder.loadTexts: aclRuleTable.setDescription('A table of ACL Rules instances.') aclRuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1), ).setIndexNames((0, "GSM7312-QOS-ACL-MIB", "aclIndex"), (0, "GSM7312-QOS-ACL-MIB", "aclRuleIndex")) if mibBuilder.loadTexts: aclRuleEntry.setStatus('current') if mibBuilder.loadTexts: aclRuleEntry.setDescription('A table of ACL Classification Rules') aclRuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 1), Integer32()) if mibBuilder.loadTexts: aclRuleIndex.setStatus('current') if mibBuilder.loadTexts: aclRuleIndex.setDescription('The index of this instance.') aclRuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("permit", 1), ("deny", 2))).clone('deny')).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleAction.setStatus('current') if mibBuilder.loadTexts: aclRuleAction.setDescription('The type of action this rule should perform.') aclRuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleProtocol.setStatus('current') if mibBuilder.loadTexts: aclRuleProtocol.setDescription('icmp - 1 igmp - 2 ip - 4 tcp - 6 udp - 17 All values from 1 to 255 are valid.') aclRuleSrcIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 4), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleSrcIpAddress.setStatus('current') if mibBuilder.loadTexts: aclRuleSrcIpAddress.setDescription('The Source IP Address used in the ACL Classification.') aclRuleSrcIpMask = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleSrcIpMask.setStatus('current') if mibBuilder.loadTexts: aclRuleSrcIpMask.setDescription('The Source IP Mask used in the ACL Classification.') aclRuleSrcL4Port = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 6), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleSrcL4Port.setStatus('current') if mibBuilder.loadTexts: aclRuleSrcL4Port.setDescription('The Source Port Number (Layer 4) used in the ACL Classification.') aclRuleSrcL4PortRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 7), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleSrcL4PortRangeStart.setStatus('current') if mibBuilder.loadTexts: aclRuleSrcL4PortRangeStart.setDescription('The Source Port Number(Layer 4) range start.') aclRuleSrcL4PortRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 8), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleSrcL4PortRangeEnd.setStatus('current') if mibBuilder.loadTexts: aclRuleSrcL4PortRangeEnd.setDescription('The Source Port Number(Layer 4) range end.') aclRuleDestIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 9), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleDestIpAddress.setStatus('current') if mibBuilder.loadTexts: aclRuleDestIpAddress.setDescription('The Destination IP Address used in the ACL Classification.') aclRuleDestIpMask = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 10), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleDestIpMask.setStatus('current') if mibBuilder.loadTexts: aclRuleDestIpMask.setDescription('The Destination IP Mask used in the ACL Classification.') aclRuleDestL4Port = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 11), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleDestL4Port.setStatus('current') if mibBuilder.loadTexts: aclRuleDestL4Port.setDescription('The Destination Port (Layer 4) used in ACl classification.') aclRuleDestL4PortRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 12), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleDestL4PortRangeStart.setStatus('current') if mibBuilder.loadTexts: aclRuleDestL4PortRangeStart.setDescription('The Destination Port (Layer 4) starting range used in ACL classification.') aclRuleDestL4PortRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 13), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleDestL4PortRangeEnd.setStatus('current') if mibBuilder.loadTexts: aclRuleDestL4PortRangeEnd.setDescription('The Destination Port (Layer 4) ending range used in ACL classification.') aclRuleIPDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 14), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleIPDSCP.setStatus('current') if mibBuilder.loadTexts: aclRuleIPDSCP.setDescription('The Differentiated Services Code Point value.') aclRuleIpPrecedence = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 15), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleIpPrecedence.setStatus('current') if mibBuilder.loadTexts: aclRuleIpPrecedence.setDescription('The Type of Service (TOS) IP Precedence value.') aclRuleIpTosBits = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 16), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleIpTosBits.setStatus('current') if mibBuilder.loadTexts: aclRuleIpTosBits.setDescription('The Type of Service (TOS) Bits value.') aclRuleIpTosMask = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 17), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleIpTosMask.setStatus('current') if mibBuilder.loadTexts: aclRuleIpTosMask.setDescription('The Type of Service (TOS) Mask value.') aclRuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4526, 1, 6, 3, 2, 3, 1, 18), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aclRuleStatus.setStatus('current') if mibBuilder.loadTexts: aclRuleStatus.setDescription('Status of this instance. active(1) - this ACL Rule is active createAndGo(4) - set to this value to create an instance destroy(6) - set to this value to delete an instance') mibBuilder.exportSymbols("GSM7312-QOS-ACL-MIB", gsm7312QOSACL=gsm7312QOSACL, aclIfEntry=aclIfEntry, aclRuleIPDSCP=aclRuleIPDSCP, aclRuleDestIpAddress=aclRuleDestIpAddress, aclRuleDestL4PortRangeStart=aclRuleDestL4PortRangeStart, aclRuleIpPrecedence=aclRuleIpPrecedence, aclIfTable=aclIfTable, aclIndex=aclIndex, aclRuleDestL4PortRangeEnd=aclRuleDestL4PortRangeEnd, aclRuleSrcL4Port=aclRuleSrcL4Port, aclStatus=aclStatus, aclIfIndex=aclIfIndex, aclRuleIpTosMask=aclRuleIpTosMask, aclRuleAction=aclRuleAction, aclRuleSrcL4PortRangeEnd=aclRuleSrcL4PortRangeEnd, aclTable=aclTable, aclIfDirection=aclIfDirection, aclEntry=aclEntry, aclRuleDestL4Port=aclRuleDestL4Port, aclRuleSrcL4PortRangeStart=aclRuleSrcL4PortRangeStart, PYSNMP_MODULE_ID=gsm7312QOSACL, aclIfStatus=aclIfStatus, aclRuleEntry=aclRuleEntry, aclRuleDestIpMask=aclRuleDestIpMask, aclRuleTable=aclRuleTable, aclRuleIndex=aclRuleIndex, aclRuleIpTosBits=aclRuleIpTosBits, aclRuleSrcIpAddress=aclRuleSrcIpAddress, aclRuleStatus=aclRuleStatus, aclRuleProtocol=aclRuleProtocol, aclRuleSrcIpMask=aclRuleSrcIpMask)
class AttributeUsageAttribute(Attribute,_Attribute): """ Specifies the usage of another attribute class. This class cannot be inherited. AttributeUsageAttribute(validOn: AttributeTargets) """ def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,validOn): """ __new__(cls: type,validOn: AttributeTargets) """ pass def __reduce_ex__(self,*args): pass AllowMultiple=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets a Boolean value indicating whether more than one instance of the indicated attribute can be specified for a single program element. Get: AllowMultiple(self: AttributeUsageAttribute) -> bool Set: AllowMultiple(self: AttributeUsageAttribute)=value """ Inherited=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets a Boolean value indicating whether the indicated attribute can be inherited by derived classes and overriding members. Get: Inherited(self: AttributeUsageAttribute) -> bool Set: Inherited(self: AttributeUsageAttribute)=value """ ValidOn=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a set of values identifying which program elements that the indicated attribute can be applied to. Get: ValidOn(self: AttributeUsageAttribute) -> AttributeTargets """
""" Backports of library components from newer python versions. For internal use only. """
''' UFCG PROGRAMAÇÃO 1 JOSE ARTHUR NEVES DE BRITO - 119210204 CONSTRUCAO CONDOMINIO ''' l1 = float(input()) l2 = float(input()) area = float(input()) area_terreno = l1 * l2 qtd_casas = area_terreno // area print('{} casa(s) pode(m) ser construída(s) no terreno.'.format(int(qtd_casas)))
settings = { "ARCHIVE" : True, "MAX_POSTS" : 5000 }
def minim(lst): min = 100000 minI = 99999 for i in range(len(lst)): if lst[i]<min: min = lst[i] minI=i return min,minI lst = list(map(int, input().split())) lst2 = len(lst)*[0] min = lst[1] for i in range(len(lst)): x,y = minim(lst) lst2.append(x) # print(minim(lst))
class CapacityMixin: @staticmethod def get_capacity(capacity, amount): if amount > capacity: return "Capacity reached!" return capacity - amount
# Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'program', 'type': 'executable', 'msvs_cygwin_shell': 0, 'sources': [ 'program.c', ], 'actions': [ { 'action_name': 'make-prog1', 'inputs': [ 'make-prog1.py', ], 'outputs': [ '<(INTERMEDIATE_DIR)/prog1.c', ], 'action': [ 'python', '<(_inputs)', '<@(_outputs)', ], 'process_outputs_as_sources': 1, }, { 'action_name': 'make-prog2', 'inputs': [ 'make-prog2.py', ], 'outputs': [ 'actions-out/prog2.c', ], 'action': [ 'python', '<(_inputs)', '<@(_outputs)', ], 'process_outputs_as_sources': 1, # Allows the test to run without hermetic cygwin on windows. 'msvs_cygwin_shell': 0, }, ], }, { 'target_name': 'counter', 'type': 'none', 'actions': [ { # This action should always run, regardless of whether or not it's # inputs or the command-line change. We do this by creating a dummy # first output, which is always missing, thus causing the build to # always try to recreate it. Actual output files should be listed # after the dummy one, and dependent targets should list the real # output(s) in their inputs # (see '../actions.gyp:depend_on_always_run_action'). 'action_name': 'action_counter', 'inputs': [ 'counter.py', ], 'outputs': [ 'actions-out/action-counter.txt.always', 'actions-out/action-counter.txt', ], 'action': [ 'python', '<(_inputs)', 'actions-out/action-counter.txt', '2', ], # Allows the test to run without hermetic cygwin on windows. 'msvs_cygwin_shell': 0, }, ], }, ], }
jogadores = [] jogador = {} gols = [] somagols = gol = 0 while True: jogador['nome'] = str(input('Nome do jogador: ')).strip().title() partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) for p in range(0, partidas): gol = int(input(f'Quantos gols na partida {p + 1}? ')) somagols += gol gols.append(gol) jogador['gols'] = gols[:] gols.clear() jogador['total'] = somagols jogadores.append(jogador.copy()) jogador.clear() somagols = 0 continuar = ' ' while continuar not in 'SN': continuar = str(input('Continuar [S/N]: ')).strip().upper()[0] if continuar in 'N': break print('-=' * 30) print(jogadores) print('-=' * 30) print(f'{"Cod":>3} ', end='') for i in jogadores[0].keys(): print(f'{i.title():<14} ', end='') print() print('_' * 40) for k, v in enumerate(jogadores): print(f'{k:>3} ', end='') for d in v.values(): print(f'{str(d):<15}', end='') print() while True: mostrar = int(input('Mostrar dados de qual jogador? ')) if mostrar == 999: break while mostrar > len(jogadores): mostrar = int(input('ERRO! Não existe o jogador com o código {mostrar}! Tente novamente! ')) print(f'-- Levantamento do jogador {jogadores[mostrar]["nome"]}') for i, go in enumerate(jogadores[mostrar]["gols"]): print(f'{" No jogo " + str(i + 1) + " fez " + str(go) + " gol(s) "}') print('<<< Volte sempre >>>')
print("Enter Num 1 : ") num1 = int(input()) print("Enter Num 2 : ") num2 = int(input()) print("Sum = ", num1+num2) print("This is important")
def likelihood(theta_hat, x, y): """The likelihood function for a linear model with noise sampled from a Gaussian distribution with zero mean and unit variance. Args: theta_hat (float): An estimate of the slope parameter. x (ndarray): An array of shape (samples,) that contains the input values. y (ndarray): An array of shape (samples,) that contains the corresponding measurement values to the inputs. Returns: float: the likelihood value for the theta_hat estimate """ sigma = 1 pdf = 1 / np.sqrt(2*np.pi*sigma**2) * np.exp(-(y - theta_hat*x)**2 / (2*sigma**2)) return pdf
UI={ 'new_goal':{ 't':'Send me the name of your goal' } }
""" Write a Python program to count occurrences of a substring in a string. """ str1 = "This pandemic is something serious, in the sense that a virus can spread while lockdown is on. Let's re_examine this virus please." print("The Text is:", str1) print() print("The Number of occurence of the word virus is: ",str1.count("virus"))
#if customizations are required when doing the update of the code of the jpackage def main(j,jp,force=False): recipe=jp.getCodeMgmtRecipe() recipe.update(force=force)
"""Targets for generating TensorFlow Python API __init__.py files.""" # keep sorted TENSORFLOW_API_INIT_FILES = [ # BEGIN GENERATED FILES "__init__.py", "app/__init__.py", "bitwise/__init__.py", "compat/__init__.py", "data/__init__.py", "debugging/__init__.py", "distributions/__init__.py", "distributions/bijectors/__init__.py", "dtypes/__init__.py", "errors/__init__.py", "feature_column/__init__.py", "gfile/__init__.py", "graph_util/__init__.py", "image/__init__.py", "io/__init__.py", "initializers/__init__.py", "keras/__init__.py", "keras/activations/__init__.py", "keras/applications/__init__.py", "keras/applications/densenet/__init__.py", "keras/applications/inception_resnet_v2/__init__.py", "keras/applications/inception_v3/__init__.py", "keras/applications/mobilenet/__init__.py", "keras/applications/nasnet/__init__.py", "keras/applications/resnet50/__init__.py", "keras/applications/vgg16/__init__.py", "keras/applications/vgg19/__init__.py", "keras/applications/xception/__init__.py", "keras/backend/__init__.py", "keras/callbacks/__init__.py", "keras/constraints/__init__.py", "keras/datasets/__init__.py", "keras/datasets/boston_housing/__init__.py", "keras/datasets/cifar10/__init__.py", "keras/datasets/cifar100/__init__.py", "keras/datasets/fashion_mnist/__init__.py", "keras/datasets/imdb/__init__.py", "keras/datasets/mnist/__init__.py", "keras/datasets/reuters/__init__.py", "keras/estimator/__init__.py", "keras/initializers/__init__.py", "keras/layers/__init__.py", "keras/losses/__init__.py", "keras/metrics/__init__.py", "keras/models/__init__.py", "keras/optimizers/__init__.py", "keras/preprocessing/__init__.py", "keras/preprocessing/image/__init__.py", "keras/preprocessing/sequence/__init__.py", "keras/preprocessing/text/__init__.py", "keras/regularizers/__init__.py", "keras/utils/__init__.py", "keras/wrappers/__init__.py", "keras/wrappers/scikit_learn/__init__.py", "layers/__init__.py", "linalg/__init__.py", "logging/__init__.py", "losses/__init__.py", "manip/__init__.py", "math/__init__.py", "metrics/__init__.py", "nn/__init__.py", "nn/rnn_cell/__init__.py", "profiler/__init__.py", "python_io/__init__.py", "quantization/__init__.py", "resource_loader/__init__.py", "strings/__init__.py", "saved_model/__init__.py", "saved_model/builder/__init__.py", "saved_model/constants/__init__.py", "saved_model/loader/__init__.py", "saved_model/main_op/__init__.py", "saved_model/signature_constants/__init__.py", "saved_model/signature_def_utils/__init__.py", "saved_model/tag_constants/__init__.py", "saved_model/utils/__init__.py", "sets/__init__.py", "sparse/__init__.py", "spectral/__init__.py", "summary/__init__.py", "sysconfig/__init__.py", "test/__init__.py", "train/__init__.py", "train/queue_runner/__init__.py", "user_ops/__init__.py", # END GENERATED FILES ] # keep sorted ESTIMATOR_API_INIT_FILES = [ # BEGIN GENERATED ESTIMATOR FILES "__init__.py", "estimator/__init__.py", "estimator/export/__init__.py", "estimator/inputs/__init__.py", # END GENERATED ESTIMATOR FILES ] # Creates a genrule that generates a directory structure with __init__.py # files that import all exported modules (i.e. modules with tf_export # decorators). # # Args: # name: name of genrule to create. # output_files: List of __init__.py files that should be generated. # This list should include file name for every module exported using # tf_export. For e.g. if an op is decorated with # @tf_export('module1.module2', 'module3'). Then, output_files should # include module1/module2/__init__.py and module3/__init__.py. # root_init_template: Python init file that should be used as template for # root __init__.py file. "# API IMPORTS PLACEHOLDER" comment inside this # template will be replaced with root imports collected by this genrule. # srcs: genrule sources. If passing root_init_template, the template file # must be included in sources. # api_name: Name of the project that you want to generate API files for # (e.g. "tensorflow" or "estimator"). # package: Python package containing the @tf_export decorators you want to # process # package_dep: Python library target containing your package. def gen_api_init_files( name, output_files = TENSORFLOW_API_INIT_FILES, root_init_template = None, srcs = [], api_name = "tensorflow", package = "tensorflow.python", package_dep = "//tensorflow/python:no_contrib", output_package = "tensorflow"): root_init_template_flag = "" if root_init_template: root_init_template_flag = "--root_init_template=$(location " + root_init_template + ")" api_gen_binary_target = "create_" + package + "_api" native.py_binary( name = "create_" + package + "_api", srcs = ["//tensorflow/tools/api/generator:create_python_api.py"], main = "//tensorflow/tools/api/generator:create_python_api.py", srcs_version = "PY2AND3", visibility = ["//visibility:public"], deps = [ package_dep, "//tensorflow/tools/api/generator:doc_srcs", ], ) native.genrule( name = name, outs = output_files, cmd = ( "$(location :" + api_gen_binary_target + ") " + root_init_template_flag + " --apidir=$(@D) --apiname=" + api_name + " --package=" + package + " --output_package=" + output_package + " $(OUTS)"), srcs = srcs, tools = [":" + api_gen_binary_target ], visibility = ["//tensorflow:__pkg__"], )
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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. _flex_doc_FRAME = """ Get {desc} of dataframe and other, element-wise (binary operator `{op_name}`). Equivalent to ``{equiv}``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `{reverse}`. Among flexible wrappers (`add`, `sub`, `mul`, `div`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. axis : {{0 or 'index', 1 or 'columns'}} Whether to compare by the index (0 or 'index') or columns (1 or 'columns'). For Series input, axis to match Series index on. level : int or label Broadcast across a level, matching Index values on the passed MultiIndex level. fill_value : float or None, default None Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing. Returns ------- DataFrame Result of the arithmetic operation. See Also -------- DataFrame.add : Add DataFrames. DataFrame.sub : Subtract DataFrames. DataFrame.mul : Multiply DataFrames. DataFrame.div : Divide DataFrames (float division). DataFrame.truediv : Divide DataFrames (float division). DataFrame.floordiv : Divide DataFrames (integer division). DataFrame.mod : Calculate modulo (remainder after division). DataFrame.pow : Calculate exponential power. Notes ----- Mismatched indices will be unioned together. Examples -------- >>> import mars.dataframe as md >>> df = md.DataFrame({{'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}}, ... index=['circle', 'triangle', 'rectangle']) >>> df.execute() angles degrees circle 0 360 triangle 3 180 rectangle 4 360 Add a scalar with operator version which return the same results. >>> (df + 1).execute() angles degrees circle 1 361 triangle 4 181 rectangle 5 361 >>> df.add(1).execute() angles degrees circle 1 361 triangle 4 181 rectangle 5 361 Divide by constant with reverse version. >>> df.div(10).execute() angles degrees circle 0.0 36.0 triangle 0.3 18.0 rectangle 0.4 36.0 >>> df.rdiv(10).execute() angles degrees circle inf 0.027778 triangle 3.333333 0.055556 rectangle 2.500000 0.027778 Subtract a list and Series by axis with operator version. >>> (df - [1, 2]).execute() angles degrees circle -1 358 triangle 2 178 rectangle 3 358 >>> df.sub([1, 2], axis='columns').execute() angles degrees circle -1 358 triangle 2 178 rectangle 3 358 >>> df.sub(md.Series([1, 1, 1], index=['circle', 'triangle', 'rectangle']), ... axis='index').execute() angles degrees circle -1 359 triangle 2 179 rectangle 3 359 Multiply a DataFrame of different shape with operator version. >>> other = md.DataFrame({{'angles': [0, 3, 4]}}, ... index=['circle', 'triangle', 'rectangle']) >>> other.execute() angles circle 0 triangle 3 rectangle 4 >>> (df * other).execute() angles degrees circle 0 NaN triangle 9 NaN rectangle 16 NaN >>> df.mul(other, fill_value=0).execute() angles degrees circle 0 0.0 triangle 9 0.0 rectangle 16 0.0 Divide by a MultiIndex by level. >>> df_multindex = md.DataFrame({{'angles': [0, 3, 4, 4, 5, 6], ... 'degrees': [360, 180, 360, 360, 540, 720]}}, ... index=[['A', 'A', 'A', 'B', 'B', 'B'], ... ['circle', 'triangle', 'rectangle', ... 'square', 'pentagon', 'hexagon']]) >>> df_multindex.execute() angles degrees A circle 0 360 triangle 3 180 rectangle 4 360 B square 4 360 pentagon 5 540 hexagon 6 720 >>> df.div(df_multindex, level=1, fill_value=0).execute() angles degrees A circle NaN 1.0 triangle 1.0 1.0 rectangle 1.0 1.0 B square 0.0 0.0 pentagon 0.0 0.0 hexagon 0.0 0.0 """ _flex_doc_SERIES = """ Return {desc} of series and other, element-wise (binary operator `{op_name}`). Equivalent to ``series {equiv} other``, but with support to substitute a fill_value for missing data in one of the inputs. Parameters ---------- other : Series or scalar value fill_value : None or float value, default None (NaN) Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result will be missing. level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level. Returns ------- Series The result of the operation. See Also -------- Series.{reverse} Examples -------- >>> import numpy as np >>> import mars.dataframe as md >>> a = md.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd']) >>> a.execute() a 1.0 b 1.0 c 1.0 d NaN dtype: float64 >>> b = md.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e']) >>> b.execute() a 1.0 b NaN d 1.0 e NaN dtype: float64 """ _flex_comp_doc_FRAME = """ Get {desc} of dataframe and other, element-wise (binary operator `{op_name}`). Among flexible wrappers (`eq`, `ne`, `le`, `lt`, `ge`, `gt`) to comparison operators. Equivalent to `dataframe {equiv} other` with support to choose axis (rows or columns) and level for comparison. Parameters ---------- other : scalar, sequence, Series, or DataFrame Any single or multiple element data structure, or list-like object. axis : {{0 or 'index', 1 or 'columns'}}, default 'columns' Whether to compare by the index (0 or 'index') or columns (1 or 'columns'). level : int or label Broadcast across a level, matching Index values on the passed MultiIndex level. Returns ------- DataFrame of bool Result of the comparison. See Also -------- DataFrame.eq : Compare DataFrames for equality elementwise. DataFrame.ne : Compare DataFrames for inequality elementwise. DataFrame.le : Compare DataFrames for less than inequality or equality elementwise. DataFrame.lt : Compare DataFrames for strictly less than inequality elementwise. DataFrame.ge : Compare DataFrames for greater than inequality or equality elementwise. DataFrame.gt : Compare DataFrames for strictly greater than inequality elementwise. Notes ----- Mismatched indices will be unioned together. `NaN` values are considered different (i.e. `NaN` != `NaN`). Examples -------- >>> df = pd.DataFrame({{'cost': [250, 150, 100], ... 'revenue': [100, 250, 300]}}, ... index=['A', 'B', 'C']) >>> df.execute() cost revenue A 250 100 B 150 250 C 100 300 Comparison with a scalar, using either the operator or method: >>> (df == 100).execute() cost revenue A False True B False False C True False >>> df.eq(100).execute() cost revenue A False True B False False C True False When `other` is a :class:`Series`, the columns of a DataFrame are aligned with the index of `other` and broadcast: >>> (df != pd.Series([100, 250], index=["cost", "revenue"])).execute() cost revenue A True True B True False C False True Use the method to control the broadcast axis: >>> df.ne(pd.Series([100, 300], index=["A", "D"]), axis='index').execute() cost revenue A True False B True True C True True D True True When comparing to an arbitrary sequence, the number of columns must match the number elements in `other`: >>> (df == [250, 100]).execute() cost revenue A True True B False False C False False Use the method to control the axis: >>> df.eq([250, 250, 100], axis='index').execute() cost revenue A True False B False True C True False Compare to a DataFrame of different shape. >>> other = pd.DataFrame({{'revenue': [300, 250, 100, 150]}}, ... index=['A', 'B', 'C', 'D']) >>> other.execute() revenue A 300 B 250 C 100 D 150 >>> df.gt(other).execute() cost revenue A False False B False False C False True D False False Compare to a MultiIndex by level. >>> df_multindex = pd.DataFrame({{'cost': [250, 150, 100, 150, 300, 220], ... 'revenue': [100, 250, 300, 200, 175, 225]}}, ... index=[['Q1', 'Q1', 'Q1', 'Q2', 'Q2', 'Q2'], ... ['A', 'B', 'C', 'A', 'B', 'C']]) >>> df_multindex.execute() cost revenue Q1 A 250 100 B 150 250 C 100 300 Q2 A 150 200 B 300 175 C 220 225 >>> df.le(df_multindex, level=1).execute() cost revenue Q1 A True True B True True C True True Q2 A False True B True False C True False """ _flex_comp_doc_SERIES = """ Return {desc} of series and other, element-wise (binary operator `{op_name}`). Equivalent to ``series {equiv} other``, but with support to substitute a fill_value for missing data in one of the inputs. Parameters ---------- other : Series or scalar value fill_value : None or float value, default None (NaN) Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result will be missing. level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level. Returns ------- Series The result of the operation. Examples -------- >>> import numpy as np >>> import mars.dataframe as md >>> a = md.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd']) >>> a.execute() a 1.0 b 1.0 c 1.0 d NaN dtype: float64 >>> b = md.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e']) >>> b.execute() a 1.0 b NaN d 1.0 e NaN dtype: float64 """ def bin_arithmetic_doc( desc, op_name=None, equiv=None, reverse=None, series_example=None ): def wrapper(fun): nonlocal op_name, reverse op_name = op_name or fun.__name__ if reverse is None: reverse = op_name[1:] if op_name.startswith("r") else "r" + op_name fun.__frame_doc__ = _flex_doc_FRAME.format( desc=desc, op_name=op_name, equiv=equiv, reverse=reverse ) fun.__series_doc__ = _flex_doc_SERIES.format( desc=desc, op_name=op_name, equiv=equiv, reverse=reverse ) if series_example is not None: # pragma: no branch fun.__series_doc__ += "\n" + series_example.strip() return fun return wrapper def bin_compare_doc(desc, op_name=None, equiv=None, series_example=None): def wrapper(fun): nonlocal op_name op_name = op_name or fun.__name__ fun.__frame_doc__ = _flex_comp_doc_FRAME.format( desc=desc, op_name=op_name, equiv=equiv ) fun.__series_doc__ = _flex_comp_doc_SERIES.format( desc=desc, op_name=op_name, equiv=equiv ) if series_example is not None: # pragma: no branch fun.__series_doc__ += "\n" + series_example.strip() return fun return wrapper
def maximo(x, y): if x > y: return x else: return y
######## # PART 1 def get_layers(data, width = 25, height = 6): layers = [] while data: layer = [] for _ in range(width * height): layer.append(data.pop(0)) layers.append(layer) return layers def count_digit_on_layer(layer, digit): return sum([1 for val in layer if val == digit]) def get_layer_with_less_digit(layers, digit): totals = [count_digit_on_layer(layer, digit) for layer in layers] return layers[totals.index(min(totals))] def get_check_digit(layer): return count_digit_on_layer(layer, 1) * count_digit_on_layer(layer, 2) layers = get_layers([int(ch) for ch in "123456789012"], 3, 2) assert get_check_digit(get_layer_with_less_digit(layers, 0)) == 1 layers = get_layers([int(ch) for ch in "123256789012"], 3, 2) assert get_check_digit(get_layer_with_less_digit(layers, 0)) == 2 with open("event2019/day08/input.txt", "r") as input: data = [int(ch) for line in input for ch in line[:-1]] layers = get_layers(data) picked_layer = get_layer_with_less_digit(layers, 0) answer = get_check_digit(get_layer_with_less_digit(layers, 0)) print("Part 1 =", answer) assert answer == 1548 # check with accepted answer ######## # PART 2 def decode_image(layers, width = 25, height = 6): image = layers[0] for layer in layers[1:]: for i in range(width * height): image[i] = layer[i] if image[i] == 2 else image[i] for _ in range(height): for _ in range(width): ch = image.pop(0) print(' ' if ch == 0 else '#', end = "") print() layers = get_layers([int(ch) for ch in "0222112222120000"], 2, 2) #decode_image(layers, 2, 2) with open("event2019/day08/input.txt", "r") as input: data = [int(ch) for line in input for ch in line[:-1]] layers = get_layers(data) print("Part 2 =") decode_image(layers)
# System phrases started: str = "Bot {} started" closed: str = "Bot disabled" loaded_cog: str = "Load cog - {}" loading_failed: str = "Failed to load cog - {}\n{}" kill: str = "Bot disabled" # System errors not_owner: str = "You have to be bot's owner to use this command" # LanguageService lang_changed: str = "Language has been changed"
wordlist = [ "a's", "able", "about", "above", "according", "accordingly", "across", "actually", "after", "afterwards", "again", "against", "ain't", "all", "allow", "allows", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "an", "and", "another", "any", "anybody", "anyhow", "anyone", "anything", "anyway", "anyways", "anywhere", "apart", "appear", "appreciate", "appropriate", "are", "aren't", "around", "as", "aside", "ask", "asking", "associated", "at", "available", "away", "awfully", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "behind", "being", "believe", "below", "beside", "besides", "best", "better", "between", "beyond", "both", "brief", "but", "by", "c'mon", "c's", "came", "can", "can't", "cannot", "cant", "cause", "causes", "certain", "certainly", "changes", "clearly", "co", "com", "come", "comes", "concerning", "consequently", "consider", "considering", "contain", "containing", "contains", "corresponding", "could", "couldn't", "course", "currently", "definitely", "described", "despite", "did", "didn't", "different", "do", "does", "doesn't", "doing", "don't", "done", "down", "downwards", "during", "each", "edu", "eg", "eight", "either", "else", "elsewhere", "enough", "entirely", "especially", "et", "etc", "even", "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex", "exactly", "example", "except", "far", "few", "fifth", "first", "five", "followed", "following", "follows", "for", "former", "formerly", "forth", "four", "from", "further", "furthermore", "get", "gets", "getting", "given", "gives", "go", "goes", "going", "gone", "got", "gotten", "greetings", "had", "hadn't", "happens", "hardly", "has", "hasn't", "have", "haven't", "having", "he", "he's", "hello", "help", "hence", "her", "here", "here's", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "hi", "him", "himself", "his", "hither", "hopefully", "how", "howbeit", "however", "i'd", "i'll", "i'm", "i've", "ie", "if", "ignored", "immediate", "in", "inasmuch", "inc", "indeed", "indicate", "indicated", "indicates", "inner", "insofar", "instead", "into", "inward", "is", "isn't", "it", "it'd", "it'll", "it's", "its", "itself", "just", "keep", "keeps", "kept", "know", "known", "knows", "last", "lately", "later", "latter", "latterly", "least", "less", "lest", "let", "let's", "like", "liked", "likely", "little", "look", "looking", "looks", "ltd", "mainly", "many", "may", "maybe", "me", "mean", "meanwhile", "merely", "might", "more", "moreover", "most", "mostly", "much", "must", "my", "myself", "name", "namely", "nd", "near", "nearly", "necessary", "need", "needs", "neither", "never", "nevertheless", "new", "next", "nine", "no", "nobody", "non", "none", "noone", "nor", "normally", "not", "nothing", "novel", "now", "nowhere", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "on", "once", "one", "ones", "only", "onto", "or", "other", "others", "otherwise", "ought", "our", "ours", "ourselves", "out", "outside", "over", "overall", "own", "particular", "particularly", "per", "perhaps", "placed", "please", "plus", "possible", "presumably", "probably", "provides", "que", "quite", "qv", "rather", "rd", "re", "really", "reasonably", "regarding", "regardless", "regards relatively", "respectively", "right", "said", "same", "saw", "say", "saying", "says", "second", "secondly", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "self", "selves", "sensible", "sent", "serious", "seriously", "seven", "several", "shall", "she", "should", "shouldn't", "since", "six", "so", "some", "somebody", "somehow", "someone", "something", "sometime", "sometimes", "somewhat", "somewhere", "soon", "sorry", "specified", "specify", "specifying", "still", "sub", "such", "sup", "sure", "t's", "take", "taken", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that", "that's", "thats", "the", "their", "theirs", "them", "themselves", "then", "thence", "there", "there's", "thereafter", "thereby", "therefore", "therein", "theres", "thereupon", "these", "they", "they'd", "they'll", "they're", "they've", "think", "third", "this", "thorough", "thoroughly", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "took", "toward", "towards", "tried", "tries", "truly", "try", "trying", "twice", "two", "un", "under", "unfortunately", "unless", "unlikely", "until", "unto", "up", "upon", "us", "use", "used", "useful", "uses", "using", "usually", "value", "various", "very", "via", "viz", "vs", "want", "wants", "was", "wasn't", "way", "we", "we'd", "we'll", "we're", "we've", "welcome", "well", "went", "were", "weren't", "what", "what's", "whatever", "when", "whence", "whenever", "where", "where's", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "who's", "whoever", "whole", "whom", "whose", "why", "will", "willing", "wish", "with", "within", "without", "won't", "wonder", "would", "wouldn't", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your", "yours", "yourself", "yourselves", "zero" ] def words(): return wordlist
sample_trajectory = [[[8.29394929e-01, 2.94382693e-05, 1.24370992e+00], [0.8300607, 0.00321705, 1.24627523], [0.83197002, 0.01345206, 1.25535293], [0.83280536, 0.02711211, 1.26502481], [0.83431212, 0.04126721, 1.27488879], [0.83557291, 0.05575593, 1.28517274], [0.83835516, 0.07094685, 1.29766037], [0.84018236, 0.0848757, 1.30992404], [0.84367176, 0.09899109, 1.32165939], [0.84780989, 0.11275561, 1.332425], [0.85343812, 0.12216536, 1.34048073], [0.85929401, 0.12485794, 1.34398368], [0.86139773, 0.12570567, 1.34577036], [0.86072455, 0.12971565, 1.34570028], [0.86142171, 0.13086022, 1.34607923], [0.86252171, 0.13226137, 1.34576342], [0.86131819, 0.13343436, 1.34602691], [0.86237162, 0.13476304, 1.34625571], [0.86233475, 0.13646685, 1.34643762], [0.86257895, 0.13770382, 1.34626134], [0.86327492, 0.13898366, 1.34679944], [0.86351096, 0.14051317, 1.34688228], [0.86460062, 0.14136772, 1.34739374], [0.86432451, 0.14269744, 1.34746041], [0.86519599, 0.14313221, 1.34789781], [0.86501197, 0.1444806, 1.34814055], [0.86577445, 0.14467521, 1.34821045], [0.86546423, 0.14557526, 1.34840742], [0.86614776, 0.14591165, 1.34892248], [0.86594768, 0.14689357, 1.34916195], [0.86666253, 0.14705808, 1.3493557], [0.86599142, 0.14764966, 1.34944308], [0.86593019, 0.14761498, 1.34965421], [0.86554094, 0.14839651, 1.35002927], [0.86609249, 0.14847811, 1.35004771], [0.86562717, 0.14882716, 1.35021255], [0.86560691, 0.14878882, 1.35066697], [0.86523452, 0.14943953, 1.35077779], [0.86584348, 0.14940555, 1.35102009], [0.86522901, 0.14976554, 1.35107163], [0.86517114, 0.14941758, 1.35133674], [0.86440309, 0.15010623, 1.35173215], [0.86470934, 0.14982907, 1.35153207], [0.86417685, 0.15034566, 1.35204203], [0.86475626, 0.15039388, 1.35211787], [0.86454982, 0.15058402, 1.35209656], [0.86462931, 0.15062848, 1.35254998], [0.86445455, 0.15109283, 1.35246659], [0.86493616, 0.15096502, 1.35264486], [0.86440645, 0.15125336, 1.35257592]] , [[8.29394372e-01, 5.02989856e-06, 1.24369044e+00], [8.28448860e-01, 5.21108705e-04, 1.24412433e+00], [0.82821679, -0.00266306, 1.24340615], [0.82712893, -0.01278852, 1.24238184], [0.8242383, -0.02746302, 1.24138853], [0.82092432, -0.04040762, 1.24021633], [0.81676534, -0.05493966, 1.23709498], [0.81203041, -0.06978358, 1.23090388], [0.81040154, -0.08357767, 1.22607369], [0.80996861, -0.09747925, 1.22250611], [0.80839556, -0.11099092, 1.21861742], [0.80764377, -0.1220292, 1.21606453], [0.80659937, -0.12782397, 1.21509924], [0.80421561, -0.12897047, 1.21389321], [0.80543509, -0.13041502, 1.21218545], [0.80719798, -0.13077158, 1.20977956], [0.80802402, -0.13106103, 1.20923984], [0.80989696, -0.13111801, 1.20648537], [0.81088521, -0.13150426, 1.20611638], [0.81328081, -0.13140379, 1.20439828], [0.81347524, -0.13236595, 1.20291265], [0.81442975, -0.13240708, 1.20165529], [0.81439796, -0.13283523, 1.20113632], [0.8144709, -0.1324097, 1.20073386], [0.81472718, -0.13277184, 1.20014908], [0.81455051, -0.13271349, 1.19998435], [0.81461205, -0.13252529, 1.19982223], [0.81469605, -0.13255599, 1.19956114], [0.8143656, -0.13258219, 1.19952868], [0.81439902, -0.1324634, 1.1993633], [0.81443352, -0.13243586, 1.1992618], [0.81437157, -0.13234246, 1.19916844], [0.81439756, -0.13226621, 1.19910854], [0.81441603, -0.13223594, 1.19907973], [0.81433559, -0.13216323, 1.19904629], [0.81428657, -0.1320852, 1.19900435], [0.8142586, -0.13203865, 1.19895876], [0.8142406, -0.13199832, 1.19892711], [0.81423518, -0.13195133, 1.19891042], [0.81423471, -0.13192349, 1.19890408], [0.81422569, -0.1319086, 1.1988938], [0.81420996, -0.13187683, 1.19887342], [0.81420364, -0.13185729, 1.19886479], [0.81419859, -0.13183793, 1.19885612], [0.81419636, -0.13183512, 1.1988541], [0.81419609, -0.13182733, 1.19885183], [0.81419618, -0.13182156, 1.19885077], [0.81419647, -0.13181636, 1.1988502], [0.81419603, -0.13181478, 1.1988494], [0.81419583, -0.13181186, 1.19884878]] , [[8.29396978e-01, 1.19098267e-06, 1.24374612e+00], [8.29385665e-01, -1.86096731e-05, 1.24374961e+00], [0.83181454, -0.00296723, 1.24262025], [0.83897802, -0.01204637, 1.23870155], [0.84804322, -0.02637806, 1.23229918], [0.85821909, -0.04112286, 1.22443261], [0.86857714, -0.0544144, 1.21659045], [0.88077871, -0.0684697, 1.20824494], [0.89227427, -0.08258709, 1.20086125], [0.902352, -0.09639873, 1.1955734], [0.91087973, -0.11036591, 1.19195383], [0.91774859, -0.12421509, 1.18906245], [0.9213203, -0.133212, 1.18760226], [0.92225532, -0.13533401, 1.18683914], [0.92271873, -0.13441819, 1.18610231], [0.92629903, -0.13659682, 1.18384976], [0.9275226, -0.13732566, 1.18130875], [0.92780813, -0.13798298, 1.18097915], [0.93048265, -0.13851559, 1.17977442], [0.93180621, -0.13885864, 1.17854726], [0.93353268, -0.13944112, 1.17652771], [0.93455178, -0.13987549, 1.17493602], [0.93528591, -0.14017046, 1.17416708], [0.9360892, -0.14048572, 1.17327655], [0.93697368, -0.14082654, 1.17235835], [0.93770095, -0.14103281, 1.17180925], [0.93822995, -0.14154182, 1.17133442], [0.93854101, -0.14166165, 1.17120383], [0.93851431, -0.14218339, 1.170878], [0.93819314, -0.1424812, 1.17085096], [0.93810252, -0.14294232, 1.17071469], [0.93798694, -0.14300315, 1.17063908], [0.93824079, -0.14332302, 1.17040369], [0.93873968, -0.14327306, 1.17039663], [0.93894714, -0.14349533, 1.17027991], [0.93895046, -0.14351914, 1.17031255], [0.93880131, -0.1439269, 1.1702054], [0.93847315, -0.14393894, 1.17033768], [0.93858538, -0.1441697, 1.16997514], [0.93843099, -0.14412295, 1.16999137], [0.93868804, -0.14428903, 1.16989184], [0.93872778, -0.14416847, 1.16993376], [0.93880286, -0.14437759, 1.16981702], [0.93860238, -0.14431987, 1.16976048], [0.93861807, -0.14447591, 1.16969077], [0.93846924, -0.14445969, 1.16964596], [0.93854263, -0.14459339, 1.16963862], [0.93855682, -0.14458076, 1.16964518], [0.93869078, -0.14460289, 1.16967438], [0.93878573, -0.14462207, 1.16959673]] , [[8.29407186e-01, -9.05759077e-06, 1.24368865e+00], [8.29452381e-01, -1.63704649e-04, 1.24357758e+00], [8.25965077e-01, 2.61926546e-04, 1.24626125e+00], [0.81733529, 0.00174526, 1.25507639], [0.80426213, 0.00362642, 1.26770935], [0.79167872, 0.0042421, 1.2788831], [0.77884486, 0.00425323, 1.29066411], [0.76562033, 0.00397443, 1.30224383], [0.75246375, 0.00297646, 1.31192952], [0.73925773, 0.00222876, 1.31881364], [0.72935091, 0.0015718, 1.32334408], [7.24226016e-01, 1.14350341e-03, 1.32602297e+00], [7.22519410e-01, -1.47608797e-04, 1.32901491e+00], [7.23386890e-01, 9.03067432e-04, 1.32840265e+00], [0.72517122, 0.0015991, 1.32902918], [7.27716689e-01, 1.23742022e-03, 1.33002939e+00], [0.72845183, 0.00218048, 1.330628], [0.73016814, 0.00230491, 1.33130849], [0.73068608, 0.00276825, 1.33147273], [0.73058817, 0.0026997, 1.33247778], [0.73087955, 0.00327157, 1.33278831], [0.7311847, 0.00344362, 1.33340541], [0.73196251, 0.00363454, 1.33359357], [0.73037666, 0.00355182, 1.33388385], [0.73017486, 0.00311582, 1.33464425], [0.729715, 0.00375855, 1.33492001], [0.73145033, 0.00389886, 1.33500413], [0.73134099, 0.00342494, 1.33517212], [0.73106361, 0.00342293, 1.33576168], [0.73126924, 0.00411912, 1.33598262], [0.73231772, 0.00415066, 1.33587838], [0.73068793, 0.00380189, 1.33574672], [0.73025543, 0.00317184, 1.33640307], [0.73089559, 0.004183, 1.33681776], [0.73151253, 0.0044662, 1.3363534], [0.73176347, 0.00401998, 1.33673888], [0.7313257, 0.00468158, 1.3370429], [0.73209111, 0.00487611, 1.33683827], [0.73184313, 0.00434979, 1.33684753], [0.73124175, 0.00449397, 1.33768667], [0.73225456, 0.00543768, 1.3373894], [0.73236785, 0.00432575, 1.3374303], [0.73103295, 0.00467082, 1.3380206], [0.73162836, 0.00503268, 1.33785837], [0.73221498, 0.0047949, 1.33773502], [0.73159943, 0.00474566, 1.33783584], [0.73163975, 0.00478752, 1.33809036], [0.73227203, 0.00533049, 1.33800575], [0.73268811, 0.00471999, 1.33770073], [0.731356, 0.00470975, 1.33810571]] , [[8.29462825e-01, -3.02466188e-06, 1.24368449e+00], [8.30306652e-01, 5.36592938e-04, 1.24351743e+00], [0.82627275, 0.00263688, 1.24290417], [0.81688637, 0.01068543, 1.24264759], [0.80534614, 0.02380721, 1.24175146], [0.79290312, 0.03726687, 1.23912056], [0.77948659, 0.05097065, 1.2350255], [0.76523324, 0.06504495, 1.22959431], [0.75226822, 0.07925581, 1.22512592], [0.74237365, 0.09353404, 1.2197175], [0.73913879, 0.10222336, 1.21704451], [0.7394468, 0.10385065, 1.21247085], [0.7333889, 0.10470436, 1.20406516], [0.7259056, 0.10553633, 1.1994055], [0.72469589, 0.10628135, 1.19902167], [0.7263446, 0.10798226, 1.19681979], [0.72525853, 0.10857415, 1.1928742], [0.72563646, 0.10940517, 1.18991156], [0.72578947, 0.10959028, 1.19065591], [0.72531063, 0.11210447, 1.1887599], [0.72605692, 0.11379858, 1.187013], [0.72639765, 0.1122605, 1.18610391], [0.72399292, 0.11456986, 1.18554155], [0.72316012, 0.11516881, 1.18459081], [0.72574085, 0.11555135, 1.18364884], [0.72428049, 0.11549468, 1.18184939], [0.72499676, 0.11608238, 1.18136709], [0.72520263, 0.1170543, 1.1805268], [0.72600627, 0.11705583, 1.17992443], [0.72495808, 0.1178273, 1.17975925], [0.726027, 0.1182533, 1.17909275], [0.7251307, 0.11844033, 1.17929497], [0.72508602, 0.11910898, 1.17888568], [0.72576297, 0.11895758, 1.17872822], [0.72457023, 0.11952085, 1.17893918], [0.72523126, 0.11972244, 1.17814958], [0.72461038, 0.11958309, 1.17865173], [0.72451839, 0.12012874, 1.17848082], [0.7254761, 0.12019711, 1.1782561], [0.72443222, 0.12010784, 1.17859375], [0.72464154, 0.12076384, 1.17830658], [0.72562088, 0.12027699, 1.17823457], [0.72430732, 0.12081787, 1.17862396], [0.72516592, 0.12078771, 1.17773548], [0.72409672, 0.12049726, 1.178552], [0.72442099, 0.12119749, 1.17828582], [0.72558587, 0.12082985, 1.17814712], [0.7243532, 0.12087931, 1.1785126], [0.72489004, 0.12125501, 1.17807636], [0.72473186, 0.12086408, 1.17852156]]]
### # Copyright 2019 Hewlett Packard Enterprise, Inc. All rights reserved. # # 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. ### # -*- coding: utf-8 -*- """This module contains common helper functions used by several pmem commands""" class PmemHelpers(object): """ Class containing common helper functions used by several pmem commands """ @staticmethod def py3_round(number, precision): """ Rounds numbers in accordance with the Python 3 round specification :param number: number to be rounded :type number: floating point number :param precision: Number of decimal places the number should be rounded off to :type precision: integer :return: rounded off number """ if abs(round(number)-number) == 0.5: return (2.0*round(number/2.0, precision)) return (round(number, precision)) @staticmethod def parse_dimm_id(dimm_id_list): """ Converts DIMM IDs from the 'X@Y' format to the 'PROC X DIMM Y' format :param dimm_id_list: DIMM IDs in the 'X@Y' format :type dimm_id_list: list :return: list of DIMM IDs in the 'PROC X DIMM Y' format """ parsed_list = list() for dimm_id in dimm_id_list: temp = dimm_id.split("@") parsed_list.append("PROC " + temp[0] + " DIMM " + temp[1]) return parsed_list @staticmethod def get_pmem_members(memory_members): """ Filters persistent memory members from memory resources :param memory_members: members of memory collection resource :type memory_members: list of members :returns: list of persistent memory members if found else empty list """ base_module_type = "PMM" pmem_members = list() pmem_dimm_id = set() for member in memory_members: memory_type = member.get("Oem").get("Hpe").get("BaseModuleType") if memory_type == base_module_type: pmem_members.append(member) pmem_dimm_id.add(member.get("DeviceLocator")) return pmem_members, pmem_dimm_id @staticmethod def get_non_aep_members(memory_members): """ Filters dram memory members from memory resources :param memory_members: members of memory collection resource :type memory_members: list of members :returns: list of dram memory members if found else empty list """ base_module_type = "PMM" dram_members = list() dram_dimm_id = set() for member in memory_members: memory_type = member.get("Oem").get("Hpe").get("BaseModuleType") if memory_type != base_module_type: dram_members.append(member) dram_dimm_id.add(member.get("DeviceLocator")) return dram_members, dram_dimm_id @staticmethod def json_to_text(dictionary): """ Converts json to string format :param dictionary: json to be converted :return: list containing the string """ output = "" for key, value in dictionary.items(): item = "\n" + key + ":" + str(value) output += item return [output] @staticmethod def location_format_converter(location_list): """ Converts location format from 'PROC X DIMM Y' to 'X@Y' :param location_list: list of locations of the format 'PROC X DIMM Y' :type location_list: list of strings :returns: string of locations in the 'X@Y' format (comma separated) """ converted_str = "" for location in location_list: temp = location.split(" ") converted_str += temp[1] + "@" + temp[3] if location is not location_list[-1]: converted_str += ", " return converted_str, ("PROC " + converted_str[0]) @staticmethod def compare_id(id1, id2): """ Compares two ids :param id1: first id to be compared :param id2: second id to be compared :return: True if ids are same else False """ if id1[-1] == "/": id1 = id1[:-1] if id2[-1] == "/": id2 = id2[:-1] return id1 == id2
# https://binarysearch.com/ # GGA 2020.12.04 """ User Problem You Have: You Need: You Must: Input/Output Example: Solution (Feature/Product) (Edge cases) Reflect On, Improvements, Comparisons with other Solutions: I learned: """ # function counting 'only-children' in tree class Solution: def solve(self, root): # set local counter to 0 (counting only-children) local_counter = 0 # set cumulative_counter to 0 (counting only-children) cumulative_total_counter = 0 # 1. base case: root is empty if not root: return 0 # 2. check children (not recoursive) # this updates local_counter (counting only-children) if (root.right == None and root.left != None) or ( root.left == None and root.right != None ): local_counter += 1 # 3. recoursive check through tree: \ # passing results to cumulative_total_counter (counting only-children) cumulative_total_counter += ( local_counter + self.solve(root.right) + self.solve(root.left) ) # return result of step 3 return cumulative_total_counter ############################ # Functions to Print Output ############################ # Sample Print Solution class Tree: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ Rewrite Diagram: 1. [ -> Tree( 2. ] -> ) """ tree_diagram_list = [0, [4, None, None], [2, [1, [3, None, None], None], None]] root = Tree(0, Tree(4, None, None), Tree(2, Tree(1, Tree(3, None, None), None), None)) # print whole tree def print_tree(root): # print current node value print(root.val) # print left child if root.left: print_tree(root.left) # print right child if root.right: print_tree(root.right) return None # print input tree for inspection print_tree(root) # input is the root node test_input = root run_test = Solution() print("\nOutput =", run_test.solve(test_input))
#-*- coding: utf-8 -*- # https://github.com/Kodi-vStream/venom-xbmc-addons class iHoster: def getDisplayName(self): raise NotImplementedError() def setDisplayName(self, sDisplayName): raise NotImplementedError() def setFileName(self, sFileName): raise NotImplementedError() def getFileName(self): raise NotImplementedError() def getPluginIdentifier(self): raise NotImplementedError() def isDownloadable(self): raise NotImplementedError() def isJDownloaderable(self): raise NotImplementedError() def getPattern(self): raise NotImplementedError() def setUrl(self, sUrl): raise NotImplementedError() def checkUrl(self, sUrl): raise NotImplementedError() def getUrl(self): raise NotImplementedError() def getMediaLink(self): raise NotImplementedError()
""" LC887 -- super egg drop You are given K eggs, and you have access to a building with N floors from 1 to N. Each egg is identical in function, and if an egg breaks, you cannot drop it again. You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break. Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N). Your goal is to know with certainty what the value of F is. What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? Example 1: Input: K = 1, N = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know with certainty that F = 0. Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F = 1. If it didn't break, then we know with certainty F = 2. Hence, we needed 2 moves in the worst case to know what F is with certainty. Example 2: Input: K = 2, N = 6 Output: 3 Example 3: Input: K = 3, N = 14 Output: 4 """ # initial method -- dp # TLE however class Solution: def superEggDrop(self, K: int, N: int) -> int: # dp[i][j] means the number of moves needed to test j floor # if there are i eggs left dp = [[0 for _ in range(K+1)] for _ in range(N+1)] for floor in range(1, N+1): dp[floor][1] = floor for egg in range(1, K+1): dp[1][egg] = 1 for i in range(2, K+1): for j in range(2, N+1): max_move = N for drop_floor in range(2, j//2+2): max_move = min(max_move, max(dp[drop_floor-1][i-1], dp[j-drop_floor][i])) dp[j][i] = 1 + max_move return dp[N][K] # reference: https://leetcode.com/articles/super-egg-drop/ # check this link # feel the power of math # every time I should write down the state transfer function to class Solution: def superEggDrop(self, K: int, N: int) -> int: dp = [[0] * (K+1) for n in range(N+1)] for m in range(1,N+1): for k in range(1,K+1): dp[m][k] = dp[m-1][k-1] + dp[m-1][k] + 1 if dp[m][k] >= N: return m if __name__ == '__main__': sol = Solution() k = 4 n = 5000 print(sol.superEggDrop(k, n))
expected_output={ "drops":{ "IN_US_CL_V4_PKT_FAILED_POLICY":{ "drop_type":8, "packets":11019, }, "IN_US_V4_PKT_SA_NOT_FOUND_SPI":{ "drop_type":4, "packets":67643, }, "OCT_GEN_NOTIFY_SOFT_EXPIRY":{ "drop_type":66, "packets":159949980, }, "OCT_PKT_HIT_INVALID_SA":{ "drop_type":68, "packets":2797, }, "OUT_OCT_HARD_EXPIRY":{ "drop_type":44, "packets":3223664, }, "OUT_V4_PKT_HIT_IKE_START_SP":{ "drop_type":33, "packets":1763263723, }, "OUT_V4_PKT_HIT_INVALID_SA":{ "drop_type":32, "packets":28583, }, } }
lista = list() lista_par = list() lista_impar = list() while True: lista.append(int(input("Introduza um nr: "))) continuar = input("Deseja continuar? (S/N) _").strip().upper()[0] if continuar == "N": break for c in lista: if c % 2 == 0: lista_par.append(c) else: lista_impar.append(c) print(f"A lista completa é: {lista}") print(f"A lista de pares é: {lista_par}") print(f"A lista de ímpares é: {lista_impar}")
# coding=utf8 class Unavailability(object): ''' Classe Unavailabitily définissant une indisponibilité attributs publics : - worker : l'ouvrier de l'affectation (Worker.Worker) - phase : la phase de l'affectation (Phase.Phase) ''' def __init__(self, idWorker=-1, numWeek=-1, numYear=-1, type="Indisponible"): self.idWorker = idWorker self.numYear = numYear self.numWeek = numWeek self.type = type def __str__(self): return "L'ouvrier d'id {} a une indisponibilité de type {} la semaine {}/{}".format(self.idWorker, self.type, self.numWeek, self.numYear) ''' ================ Méthodes publiques ================ ''' def serial(self): ''' Sérialise une affectation Returns: un dict contenant l'affectation serialisé Example: >>> {'phase': {'needs': {33: {'num': 33, '__class__': 'Need', 'need': 10, 'craft': {'num': 2, '__class__': 'Craft', 'name': u'Macon'}, 'qualification': {'num': 4, '__class__': 'Qualification', 'name': u'N3P2'}, 'phase': 19}, 34: {'num': 34, '__class__': 'Need', 'need': 20, 'craft': {'num': 2, '__class__': 'Craft', 'name': u'Macon'}, 'qualification': {'num': 5, '__class__': 'Qualification', 'name': u'N3P1'}, 'phase': 19}, 92: {'num': 92, '__class__': 'Need', 'need': 2, 'craft': {'num': 7, '__class__': 'Craft', 'name': u"Agent d'entretien"}, 'qualification': {'num': 6, '__class__': 'Qualification', 'name': u'N2'}, 'phase': 19}, 79: {'num': 79, '__class__': 'Need', 'need': 2, 'craft': {'num': 10, '__class__': 'Craft', 'name': u"Chef d'\xe9quipe"}, 'qualification': {'num': 2, '__class__': 'Qualification', 'name': u'N4P2'}, 'phase': 19}}, 'num': 19, 'numYear': 2014, 'numWeek': 15, 'totalWorkers': 0, 'nbWorkers': 0, '__class__': 'Phase', 'numSite': 4}, 'num': 391, 'worker': {'num': 101, 'licence': u' ', 'name': u'JOUSSEAUME', 'firstName': u'MICKAEL', 'birthdateY': '1972', '__class__': 'Worker', 'birthdateM': '11', 'craft': {'num': 2, '__class__': 'Craft', 'name': u'Macon'}, 'qualification': {'num': 4, '__class__': 'Qualification', 'name': u'N3P2'}, 'position': {'latitude': 47.9292, '__class__': 'Position', 'longitude': -1.94175, 'address': u'6 RUE DE RENNES 35330 LA CHAPELLE BOUEXIC'}, 'birthdateD': '26'}, '__class__': 'Assignment'} ''' return {"__class__": "Unavailability", "idWorker": self.idWorker, "numYear": self.numYear, "numWeek": self.numWeek, "type": self.type }
# # PySNMP MIB module FASTPATH-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FASTPATH-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:12:15 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, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, NotificationType, enterprises, iso, Counter32, Integer32, Unsigned32, ObjectIdentity, TimeTicks, Bits, Gauge32, MibIdentifier, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "NotificationType", "enterprises", "iso", "Counter32", "Integer32", "Unsigned32", "ObjectIdentity", "TimeTicks", "Bits", "Gauge32", "MibIdentifier", "ModuleIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") excelan = MibIdentifier((1, 3, 6, 1, 4, 1, 23)) genericGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2)) fastpathMib = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11)) scc = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 1)) alap = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 2)) ethernet = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 3)) aarp = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 4)) atif = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 5)) ddp = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 6)) rtmp = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 7)) kip = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 8)) zip = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 9)) nbp = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 10)) echo = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 11)) buffer = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 11, 12)) sccInterruptCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sccInterruptCount.setStatus('mandatory') sccAbortCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sccAbortCount.setStatus('mandatory') sccSpuriousCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sccSpuriousCount.setStatus('mandatory') sccCRCCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sccCRCCount.setStatus('mandatory') sccOverrunCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sccOverrunCount.setStatus('mandatory') sccUnderrunCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sccUnderrunCount.setStatus('mandatory') alapReceiveCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapReceiveCount.setStatus('mandatory') alapTransmitCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapTransmitCount.setStatus('mandatory') alapNoHandlerCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapNoHandlerCount.setStatus('mandatory') alapLengthErrorCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapLengthErrorCount.setStatus('mandatory') alapBadCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapBadCount.setStatus('mandatory') alapCollisionCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapCollisionCount.setStatus('mandatory') alapDeferCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapDeferCount.setStatus('mandatory') alapNoDataCount = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapNoDataCount.setStatus('mandatory') alapRandomCTS = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 2, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alapRandomCTS.setStatus('mandatory') etherCRCErrors = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherCRCErrors.setStatus('mandatory') etherAlignErrors = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherAlignErrors.setStatus('mandatory') etherResourceErrors = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherResourceErrors.setStatus('mandatory') etherOverrunErrors = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherOverrunErrors.setStatus('mandatory') etherInPackets = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherInPackets.setStatus('mandatory') etherOutPackets = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherOutPackets.setStatus('mandatory') etherBadTransmits = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherBadTransmits.setStatus('mandatory') etherOversizeFrames = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherOversizeFrames.setStatus('mandatory') etherSpurRUReadys = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherSpurRUReadys.setStatus('mandatory') etherSpurCUActives = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherSpurCUActives.setStatus('mandatory') etherSpurUnknown = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherSpurUnknown.setStatus('mandatory') etherBcastDrops = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherBcastDrops.setStatus('mandatory') etherReceiverRestarts = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherReceiverRestarts.setStatus('mandatory') etherReinterrupts = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherReinterrupts.setStatus('mandatory') etherBufferReroutes = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherBufferReroutes.setStatus('mandatory') etherBufferDrops = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherBufferDrops.setStatus('mandatory') etherCollisions = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherCollisions.setStatus('mandatory') etherDefers = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherDefers.setStatus('mandatory') etherDMAUnderruns = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherDMAUnderruns.setStatus('mandatory') etherMaxCollisions = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 20), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherMaxCollisions.setStatus('mandatory') etherNoCarriers = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 21), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherNoCarriers.setStatus('mandatory') etherNoCTS = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 22), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherNoCTS.setStatus('mandatory') etherNoSQEs = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 3, 23), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: etherNoSQEs.setStatus('mandatory') aarpTable = MibTable((1, 3, 6, 1, 4, 1, 23, 2, 11, 4, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: aarpTable.setStatus('mandatory') aarpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 23, 2, 11, 4, 1, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: aarpEntry.setStatus('mandatory') aarpIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 4, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: aarpIfIndex.setStatus('mandatory') aarpPhysAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 4, 1, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: aarpPhysAddress.setStatus('mandatory') aarpNetAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 4, 1, 1, 3), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: aarpNetAddress.setStatus('mandatory') atifTable = MibTable((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: atifTable.setStatus('mandatory') atifEntry = MibTableRow((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: atifEntry.setStatus('mandatory') atifIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: atifIndex.setStatus('mandatory') atifDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: atifDescr.setStatus('mandatory') atifType = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("other", 1), ("localtalk", 2), ("ethertalk1", 3), ("ethertalk2", 4), ("tokentalk", 5), ("iptalk", 6)))).setMaxAccess("readonly") if mibBuilder.loadTexts: atifType.setStatus('mandatory') atifNetStart = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 4), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: atifNetStart.setStatus('mandatory') atifNetEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 5), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: atifNetEnd.setStatus('mandatory') atifNetAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 6), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: atifNetAddress.setStatus('mandatory') atifStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: atifStatus.setStatus('mandatory') atifNetConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("configured", 1), ("garnered", 2), ("guessed", 3), ("unconfigured", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: atifNetConfig.setStatus('mandatory') atifZoneConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("configured", 1), ("garnered", 2), ("guessed", 3), ("unconfigured", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: atifZoneConfig.setStatus('mandatory') atifZone = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 10), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: atifZone.setStatus('mandatory') atifIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 5, 1, 1, 11), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: atifIfIndex.setStatus('mandatory') ddpOutRequests = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpOutRequests.setStatus('mandatory') ddpOutShort = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpOutShort.setStatus('mandatory') ddpOutLong = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpOutLong.setStatus('mandatory') ddpReceived = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpReceived.setStatus('mandatory') ddpToForward = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpToForward.setStatus('mandatory') ddpForwards = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpForwards.setStatus('mandatory') ddpForMe = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpForMe.setStatus('mandatory') ddpOutNoRoutes = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpOutNoRoutes.setStatus('mandatory') ddpTooShortDrops = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpTooShortDrops.setStatus('mandatory') ddpTooLongDrops = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpTooLongDrops.setStatus('mandatory') ddpBroadcastDrops = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpBroadcastDrops.setStatus('mandatory') ddpShortDDPDrops = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpShortDDPDrops.setStatus('mandatory') ddpHopCountDrops = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 6, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ddpHopCountDrops.setStatus('mandatory') rtmpTable = MibTable((1, 3, 6, 1, 4, 1, 23, 2, 11, 7, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtmpTable.setStatus('mandatory') rtmpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 23, 2, 11, 7, 1, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtmpEntry.setStatus('mandatory') rtmpRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 7, 1, 1, 1), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtmpRangeStart.setStatus('mandatory') rtmpRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 7, 1, 1, 2), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtmpRangeEnd.setStatus('mandatory') rtmpNextHop = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 7, 1, 1, 3), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtmpNextHop.setStatus('mandatory') rtmpInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 7, 1, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtmpInterface.setStatus('mandatory') rtmpHops = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 7, 1, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtmpHops.setStatus('mandatory') rtmpState = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 7, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("good", 1), ("suspect", 2), ("bad", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rtmpState.setStatus('mandatory') kipTable = MibTable((1, 3, 6, 1, 4, 1, 23, 2, 11, 8, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: kipTable.setStatus('mandatory') kipEntry = MibTableRow((1, 3, 6, 1, 4, 1, 23, 2, 11, 8, 1, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: kipEntry.setStatus('mandatory') kipNet = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 8, 1, 1, 1), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: kipNet.setStatus('mandatory') kipNextHop = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 8, 1, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: kipNextHop.setStatus('mandatory') kipHopCount = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 8, 1, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: kipHopCount.setStatus('mandatory') kipBCastAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 8, 1, 1, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: kipBCastAddr.setStatus('mandatory') kipCore = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 8, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("core", 1), ("notcore", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: kipCore.setStatus('mandatory') kipKfps = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 8, 1, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: kipKfps.setStatus('mandatory') zipTable = MibTable((1, 3, 6, 1, 4, 1, 23, 2, 11, 9, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: zipTable.setStatus('mandatory') zipEntry = MibTableRow((1, 3, 6, 1, 4, 1, 23, 2, 11, 9, 1, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: zipEntry.setStatus('mandatory') zipZoneName = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 9, 1, 1, 1), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zipZoneName.setStatus('mandatory') zipZoneIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 9, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zipZoneIndex.setStatus('mandatory') zipZoneNetStart = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 9, 1, 1, 3), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zipZoneNetStart.setStatus('mandatory') zipZoneNetEnd = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 9, 1, 1, 4), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zipZoneNetEnd.setStatus('mandatory') nbpTable = MibTable((1, 3, 6, 1, 4, 1, 23, 2, 11, 10, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbpTable.setStatus('mandatory') nbpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 23, 2, 11, 10, 1, 1), ).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbpEntry.setStatus('mandatory') nbpIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 10, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbpIndex.setStatus('mandatory') nbpObject = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 10, 1, 1, 2), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbpObject.setStatus('mandatory') nbpType = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 10, 1, 1, 3), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbpType.setStatus('mandatory') nbpZone = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 10, 1, 1, 4), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: nbpZone.setStatus('mandatory') echoRequests = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 11, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: echoRequests.setStatus('mandatory') echoReplies = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 11, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: echoReplies.setStatus('mandatory') bufferSize = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferSize.setStatus('mandatory') bufferAvail = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferAvail.setStatus('mandatory') bufferDrops = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferDrops.setStatus('mandatory') bufferTypeTable = MibTable((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 4), ).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferTypeTable.setStatus('mandatory') bufferTypeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 4, 1), ).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferTypeEntry.setStatus('mandatory') bufferTypeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferTypeIndex.setStatus('mandatory') bufferType = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=NamedValues(("other", 1), ("free", 2), ("localtalk", 3), ("ethernet", 4), ("arp", 5), ("data", 6), ("erbf", 7), ("etbf", 8), ("malloc", 9), ("tkbf", 10), ("token", 11)))).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferType.setStatus('mandatory') bufferTypeDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 4, 1, 3), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferTypeDescr.setStatus('mandatory') bufferTypeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 23, 2, 11, 12, 4, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bufferTypeCount.setStatus('mandatory') mibBuilder.exportSymbols("FASTPATH-MIB", etherAlignErrors=etherAlignErrors, ddpOutNoRoutes=ddpOutNoRoutes, alapCollisionCount=alapCollisionCount, bufferAvail=bufferAvail, kipKfps=kipKfps, etherReceiverRestarts=etherReceiverRestarts, bufferTypeTable=bufferTypeTable, kipCore=kipCore, atifIndex=atifIndex, alapDeferCount=alapDeferCount, rtmpRangeStart=rtmpRangeStart, etherResourceErrors=etherResourceErrors, etherOversizeFrames=etherOversizeFrames, bufferTypeEntry=bufferTypeEntry, ddpOutRequests=ddpOutRequests, ddp=ddp, zipTable=zipTable, etherBadTransmits=etherBadTransmits, nbpTable=nbpTable, alap=alap, bufferDrops=bufferDrops, bufferType=bufferType, sccCRCCount=sccCRCCount, alapReceiveCount=alapReceiveCount, rtmpState=rtmpState, atifEntry=atifEntry, sccAbortCount=sccAbortCount, ddpToForward=ddpToForward, echo=echo, etherOverrunErrors=etherOverrunErrors, atifZoneConfig=atifZoneConfig, atifTable=atifTable, ddpForwards=ddpForwards, bufferTypeIndex=bufferTypeIndex, rtmpNextHop=rtmpNextHop, aarpNetAddress=aarpNetAddress, atif=atif, alapTransmitCount=alapTransmitCount, alapNoHandlerCount=alapNoHandlerCount, etherDMAUnderruns=etherDMAUnderruns, alapBadCount=alapBadCount, etherReinterrupts=etherReinterrupts, ddpTooShortDrops=ddpTooShortDrops, aarpPhysAddress=aarpPhysAddress, aarpIfIndex=aarpIfIndex, rtmpTable=rtmpTable, zipZoneIndex=zipZoneIndex, etherMaxCollisions=etherMaxCollisions, atifStatus=atifStatus, aarpEntry=aarpEntry, etherSpurUnknown=etherSpurUnknown, zipZoneNetStart=zipZoneNetStart, kipEntry=kipEntry, sccOverrunCount=sccOverrunCount, aarpTable=aarpTable, nbpObject=nbpObject, atifZone=atifZone, kipTable=kipTable, ddpForMe=ddpForMe, etherBufferDrops=etherBufferDrops, atifDescr=atifDescr, etherOutPackets=etherOutPackets, zipEntry=zipEntry, bufferSize=bufferSize, nbpEntry=nbpEntry, echoRequests=echoRequests, etherDefers=etherDefers, atifType=atifType, rtmpHops=rtmpHops, atifNetStart=atifNetStart, kipBCastAddr=kipBCastAddr, ethernet=ethernet, fastpathMib=fastpathMib, aarp=aarp, sccUnderrunCount=sccUnderrunCount, ddpBroadcastDrops=ddpBroadcastDrops, rtmpEntry=rtmpEntry, etherInPackets=etherInPackets, etherBcastDrops=etherBcastDrops, etherNoCTS=etherNoCTS, kipNextHop=kipNextHop, ddpOutShort=ddpOutShort, echoReplies=echoReplies, nbp=nbp, etherCollisions=etherCollisions, nbpIndex=nbpIndex, rtmp=rtmp, scc=scc, atifNetEnd=atifNetEnd, alapLengthErrorCount=alapLengthErrorCount, etherBufferReroutes=etherBufferReroutes, zipZoneNetEnd=zipZoneNetEnd, bufferTypeCount=bufferTypeCount, alapRandomCTS=alapRandomCTS, sccInterruptCount=sccInterruptCount, zipZoneName=zipZoneName, etherSpurRUReadys=etherSpurRUReadys, nbpZone=nbpZone, ddpReceived=ddpReceived, ddpShortDDPDrops=ddpShortDDPDrops, buffer=buffer, rtmpRangeEnd=rtmpRangeEnd, alapNoDataCount=alapNoDataCount, zip=zip, nbpType=nbpType, sccSpuriousCount=sccSpuriousCount, etherNoCarriers=etherNoCarriers, ddpTooLongDrops=ddpTooLongDrops, ddpHopCountDrops=ddpHopCountDrops, etherNoSQEs=etherNoSQEs, etherCRCErrors=etherCRCErrors, kipNet=kipNet, rtmpInterface=rtmpInterface, kipHopCount=kipHopCount, ddpOutLong=ddpOutLong, atifIfIndex=atifIfIndex, kip=kip, excelan=excelan, atifNetAddress=atifNetAddress, etherSpurCUActives=etherSpurCUActives, bufferTypeDescr=bufferTypeDescr, genericGroup=genericGroup, atifNetConfig=atifNetConfig)
# python3.7 """Configuration for StyleGAN training demo. All settings are particularly used for one replica (GPU), such as `batch_size` and `num_workers`. """ runner_type = 'StyleGANRunner' gan_type = 'stylegan' resolution = 64 batch_size = 4 val_batch_size = 32 total_img = 100_000 # Training dataset is repeated at the beginning to avoid loading dataset # repeatedly at the end of each epoch. This can save some I/O time. data = dict( num_workers=4, repeat=500, train=dict(root_dir='/data3/lyz/dataset/sgan_demo/data/demo.zip', data_format='zip', resolution=resolution, mirror=0.5), val=dict(root_dir='/data3/lyz/dataset/sgan_demo/data/demo.zip', data_format='zip', resolution=resolution), ) controllers = dict( RunningLogger=dict(every_n_iters=10), ProgressScheduler=dict( every_n_iters=1, init_res=8, minibatch_repeats=4, lod_training_img=5_000, lod_transition_img=5_000, batch_size_schedule=dict(res4=64, res8=32, res16=16, res32=8), ), Snapshoter=dict(every_n_iters=500, first_iter=True, num=200), FIDEvaluator=dict(every_n_iters=5000, first_iter=True, num=50000), Checkpointer=dict(every_n_iters=5000, first_iter=True), ) modules = dict( discriminator=dict( model=dict(gan_type=gan_type, resolution=resolution), lr=dict(lr_type='FIXED'), opt=dict(opt_type='Adam', base_lr=1e-3, betas=(0.0, 0.99)), kwargs_train=dict(), kwargs_val=dict(), ), generator=dict( model=dict(gan_type=gan_type, resolution=resolution), lr=dict(lr_type='FIXED'), opt=dict(opt_type='Adam', base_lr=1e-3, betas=(0.0, 0.99)), kwargs_train=dict(w_moving_decay=0.995, style_mixing_prob=0.9, trunc_psi=1.0, trunc_layers=0, randomize_noise=True), kwargs_val=dict(trunc_psi=1.0, trunc_layers=0, randomize_noise=False), g_smooth_img=10000, ) ) loss = dict( type='LogisticGANLoss', d_loss_kwargs=dict(r1_gamma=10.0), g_loss_kwargs=dict(), )
"""Planets""" LIGHT_GREY = (220, 220, 220) ORANGE = (255, 128, 0) BLUE = (0, 0, 255) RED = (255, 0, 0) YELLOW = (255, 255, 0) LIGHT_BLUE = (0, 255, 255) class Planet: """Planet""" def __init__(self, name, mass, diameter, density, gravity, esc_velocity, rotation_period, day_length, from_sun, perihelion, apheleon, orbit_period, orbit_velocity, orbit_inclination, orbit_eccentricity, obliquity_to_orbit, temp, surface_pressure, moons, ring_sys, gmf, img, colour, atmosphere_comp): self.name = name self.mass = mass self.diameter = diameter self.density = density self.gravity = gravity self.esc_velocity = esc_velocity self.rotation_period = rotation_period self.day_length = day_length self.from_sun = from_sun self.perihelion = perihelion self.apheleon = apheleon self.orbit_period = orbit_period self.orbit_velocity = orbit_velocity self.orbit_inclination = orbit_inclination self.orbit_eccentricity = orbit_eccentricity self.obliquity_to_orbit = obliquity_to_orbit self.temp = temp self.surface_pressure = surface_pressure self.moons = moons self.ring_sys = ring_sys self.gmf = gmf self.img = img self.colour = colour self.atmosphere_comp = atmosphere_comp mercury = Planet("Mercury", 0.33*10**24, 4879, 5429, 3.7, 4.3, 1407.6, 4222.6, 57.9*10**6, 46*10**6, 69.8*10**6, 88, 47.4, 7, 0.206, 0.034, 167, 0, 0, False, True, "https://nssdc.gsfc.nasa.gov/planetary/banner/mercury.gif", LIGHT_GREY, [["Oxygen", 0.42], ["Sodium", 0.22], ["Hydrogen", 0.22], ["Helium", 0.06], ["Other", 0.08]]) venus = Planet("Venus", 4.87*10**24, 12104, 5243, 8.9, 10.4, -5832.5, 2802, 108.2*10**6, 107.5*10**6, 108.9*10**6, 224.7, 35, 3.4, 0.007, 177.4, 464, 92, 0, False, False, "https://nssdc.gsfc.nasa.gov/planetary/image/venus.jpg", ORANGE, [["Carbon Dioxide", 0.965], ["Nitrogen", 0.035]]) earth = Planet("Earth", 5.97*10**24, 12756, 5514, 9.8, 11.2, 23.9, 24, 149.6*10**6, 147.1*10**6, 152.1*10**6, 365.2, 29.8, 0, 0.017, 23.4, 15, 1, 1, False, True, "https://nssdc.gsfc.nasa.gov/planetary/banner/earth.gif", BLUE, [["Nitrogen", 0.7808], ["Oxygen", 0.2095], ["Other", 0.0097]]) moon = Planet("Moon", 0.073*10**24, 3475, 3340, 1.6, 2.4, 655.7, 708.7, 0.384*10**6, 0.363*10**6, 0.406*10**6, 27.3, 1, 5.1, 0.055, 6.7, -20, 0, 0, False, False, "https://nssdc.gsfc.nasa.gov/planetary/banner/moon.gif", LIGHT_GREY, [["Argon", 0.7], ["Helium", 0.29], ["Sodium", 0.01]]) mars = Planet("Mars", 0.642*10**24, 6792, 3934, 3.7, 5, 24.6, 24.7, 228*10**6, 206.7*10**6, 249.3*10**6, 687, 24.1, 1.8, 0.094, 25.2, -65, 0.01, 2, False, False, "https://nssdc.gsfc.nasa.gov/planetary/banner/mars.gif", RED, [["Carbon Dioxide", 0.951], ["Nitrogen", 0.0259], ["Argon", 0.0194], ["Oxygen", 0.0016], ["Carbon Monoxide", 0.0006], ["Other", 0.0015]]) jupiter = Planet("Jupiter", 1898*10**24, 142984, 1326, 23.1, 59.5, 9.9, 9.9, 778.5*10**6, 740.6*10**6, 816.4*10**6, 4331, 13.1, 1.3, 0.049, 3.1, - 110, None, 79, True, True, "https://nssdc.gsfc.nasa.gov/planetary/banner/jupiter.gif", ORANGE, [["Molecular Hydrogen", 0.898], ["Helium", 0.102]]) saturn = Planet("Saturn", 568*10**24, 120536, 687, 9, 35.5, 10.7, 10.7, 1432*10**6, 1357.6*10**6, 1506.5*10**6, 10747, 9.7, 2.5, 0.052, 26.7, -140, None, 82, True, True, "https://nssdc.gsfc.nasa.gov/planetary/banner/saturn.gif", YELLOW, [["Molecular Hydrogen", 0.963], ["Helium", 0.0325], ["Other", 0.0045]]) uranus = Planet("Uranus", 86.8*10**24, 51118, 1270, 8.7, 21.3, -17.2, 17.2, 2867*10**6, 2732.7*10**6, 3001.4*10**6, 30589, 6.8, 0.8, 0.047, 97.8, -195, None, 27, True, True, "https://nssdc.gsfc.nasa.gov/planetary/banner/uranus.gif", BLUE, [["Molecular Hydrogen", 0.825], ["Helium", 0.152], ["Other", 0.023]]) neptune = Planet("Neptune", 102*10**24, 49528, 1638, 11, 23.5, 16.1, 16.1, 4515*10**6, 4471.1*10**6, 4558.9*10**6, 59800, 5.4, 1.8, 0.01, 28.3, -200, None, 14, True, True, "https://nssdc.gsfc.nasa.gov/planetary/banner/neptune.gif", BLUE, [["Molecular Hydrogen", 0.8], ["Helium", 0.19], ["Methane", 0.01]]) pluto = Planet("Pluto", 0.013*10**24, 2376, 1850, 0.7, 1.3, -153.3, 153.3, 5906.4*10**6, 4436.8*10**6, 7375.9*10**6, 90560, 4.7, 17.2, 0.244, 122.5, -225, 0.00001, 5, False, None, "https://nssdc.gsfc.nasa.gov/planetary/banner/plutofact.gif", LIGHT_BLUE, [["Nitrogen", 0.99], ["Methane", 0.005], ["Carbon Monoxide", 0.0005], ["Other", 0.0045]])
# Time: O(1) # Space: O(1) # # Write a function to delete a node (except the tail) in a singly linked list, # given only access to that node. # # Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node # with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} node # @return {void} Do not return anything, modify node in-place instead. def deleteNode(self, node): if node and node.next: node_to_delete = node.next node.val = node_to_delete.val node.next = node_to_delete.next del node_to_delete
#sum in python ''' weight = float(input("Weight:")) height = float(input("height")) total = weight + height print(total) ''' #cal monthly salary ''' import math age= 17 pi= 3.14 print(type(age),age) print(type(pi),pi) print(math.pi) salary = float(input('Salary: ')) #float convert text(string) to number with decimal place bonus = float(input('Bouns: ')) Income = salary * 12 + bonus print('Your monthly is $' + str(Income)) #'' or "" is use to define string print('Your monthly is $', Income) #we can use + or , to more than one value but , will auto add a space and auto convert indentifier/var ''' # # is comment ''' is also comment '''
# Time: O(n) # Space: O(1) # Write a program that outputs the string representation of numbers from 1 to n. # # But for multiples of three it should output “Fizz” instead of the number and for # the multiples of five output “Buzz”. For numbers which are multiples of both three # and five output “FizzBuzz”. # # Example: # # n = 15, # # Return: # [ # "1", # "2", # "Fizz", # "4", # "Buzz", # "Fizz", # "7", # "8", # "Fizz", # "Buzz", # "11", # "Fizz", # "13", # "14", # "FizzBuzz" # ] class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ result = [] for i in xrange(1, n+1): if i % 15 == 0: result.append("FizzBuzz") elif i % 5 == 0: result.append("Buzz") elif i % 3 == 0: result.append("Fizz") else: result.append(str(i)) return result def fizzBuzz2(self, n): """ :type n: int :rtype: List[str] """ l = [str(x) for x in range(n + 1)] l3 = range(0, n + 1, 3) l5 = range(0, n + 1, 5) for i in l3: l[i] = 'Fizz' for i in l5: if l[i] == 'Fizz': l[i] += 'Buzz' else: l[i] = 'Buzz' return l[1:] def fizzBuzz3(self, n): return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n + 1)] def fizzBuzz4(self, n): return ['FizzBuzz'[i % -3 & -4:i % -5 & 8 ^ 12] or repr(i) for i in range(1, n + 1)]
nonverified_users = ['calvin klein','ralph lauren','christian dior','donna karran'] verified_users = [] #verifying if there are new users and moving them to a verified list while nonverified_users: current_user = nonverified_users.pop() print(f"\nVerifying user: {current_user}") verified_users.append(current_user) #Printing out the verified users for user in verified_users: print(f"\n\t{user.title()} is now verfied!")
# from ..interpreter import model # Commented out to make static node recovery be used # @model('map_server', 'map_server') def map_server(c): c.read('~frame_id', 'map') c.read('~negate', 0) c.read('~occupied_thresh', 0.65) c.read('~free_thresh', 0.196) c.provide('static_map', 'nav_msgs/GetMap') c.pub('map_metadata', 'nav_msgs/MapMetaData') c.pub('map', 'nav_msgs/OccupancyGrid')
def func1(): def func2(): return True return func2() if(func1()): print("Acabou")
fname = input('Enter File: ') if len(fname) < 1: fname = 'clown.txt' hand = open(fname) di = dict() for lin in hand: lin = lin.rstrip() wds = lin.split() #print(wds) for w in wds: # if the key is not there the count is zero #print(w) #print('**',w,di.get(w,-99)) #oldcount = di.get(w,0) #print(w,'old',oldcount) #newcount = oldcount + 1 #di[w] = newcount #print(w,'new',newcount) # idiom: retrieve/create/update counter di[w] = di.get(w,0) + 1 # print(w,'new',di[w]) #if w in di: # di[w] = di[w] + 1 #print('**EXISTING**') #else: # di[w] = 1 #print('**NEW**') #print(di[w]) #print(di) #now we want to find the most common bigword largest = -1 theword = None for k,v in di.items(): #print (k, v) if v > largest: largest = v theword = k #capture/ remember the word is largest print('Done', theword, largest)
''' Square Root of Integer Asked in: Facebook Amazon Microsoft Given an integar A. Compute and return the square root of A. If A is not a perfect square, return floor(sqrt(A)). DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY Input Format The first and only argument given is the integer A. Output Format Return floor(sqrt(A)) Constraints 1 <= A <= 10^9 For Example Input 1: A = 11 Output 1: 3 Input 2: A = 9 Output 2: 3 ''' class Solution: # @param A : integer # @return an integer def sqrt(self, n): lo,hi=1,n ans=n while lo<=hi: mid=(lo+hi)//2 x=mid*mid if x>n: hi=mid-1 elif x<=n: lo=mid+1 ans=mid return ans
# buildifier: disable=module-docstring load("//bazel/platform:transitions.bzl", "risc0_transition") # https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_library.bzl CC_TOOLCHAIN_TYPE = "@bazel_tools//tools/cpp:toolchain_type" def _get_compilation_contexts_from_deps(deps): compilation_contexts = [] for dep in deps: if CcInfo in dep: compilation_contexts.append(dep[CcInfo].compilation_context) return compilation_contexts def _get_linking_contexts_from_deps(deps): linking_contexts = [] for dep in deps: if CcInfo in dep: linking_contexts.append(dep[CcInfo].linking_context) return linking_contexts def _compile(ctx, cc_toolchain, feature_configuration): compilation_contexts = _get_compilation_contexts_from_deps(ctx.attr.deps) return cc_common.compile( name = ctx.label.name, actions = ctx.actions, cc_toolchain = cc_toolchain, feature_configuration = feature_configuration, srcs = ctx.files.srcs, user_compile_flags = ctx.attr.copts, defines = ctx.attr.defines, local_defines = ctx.attr.local_defines, compilation_contexts = compilation_contexts, public_hdrs = ctx.files.hdrs, additional_inputs = ctx.files.aux_srcs, includes = ctx.attr.includes, include_prefix = ctx.attr.include_prefix, strip_include_prefix = ctx.attr.strip_include_prefix, ) def _risc0_cc_library_impl(ctx): cc_toolchain = ctx.toolchains[CC_TOOLCHAIN_TYPE].cc feature_configuration = cc_common.configure_features( ctx = ctx, cc_toolchain = cc_toolchain, requested_features = ctx.features, unsupported_features = ctx.disabled_features, ) (compile_context, compilation_outputs) = _compile(ctx, cc_toolchain, feature_configuration) linking_contexts = _get_linking_contexts_from_deps(ctx.attr.deps) (linking_context, linking_outputs) = cc_common.create_linking_context_from_compilation_outputs( actions = ctx.actions, name = ctx.label.name, compilation_outputs = compilation_outputs, cc_toolchain = cc_toolchain, feature_configuration = feature_configuration, linking_contexts = linking_contexts, user_link_flags = ctx.attr.linkopts, alwayslink = ctx.attr.alwayslink, disallow_dynamic_library = True, ) files_builder = [] if linking_outputs.library_to_link != None: artifacts_to_build = linking_outputs.library_to_link if artifacts_to_build.static_library != None: files_builder.append(artifacts_to_build.static_library) if artifacts_to_build.pic_static_library != None: files_builder.append(artifacts_to_build.pic_static_library) return [ DefaultInfo(files = depset(files_builder)), CcInfo( compilation_context = compile_context, linking_context = linking_context, ), ] def _risc0_cc_binary_impl(ctx): cc_toolchain = ctx.toolchains[CC_TOOLCHAIN_TYPE].cc feature_configuration = cc_common.configure_features( ctx = ctx, cc_toolchain = cc_toolchain, requested_features = ctx.features, unsupported_features = ctx.disabled_features, ) (compile_context, compilation_outputs) = _compile(ctx, cc_toolchain, feature_configuration) linking_contexts = _get_linking_contexts_from_deps(ctx.attr.deps) linking_outputs = cc_common.link( name = ctx.label.name, actions = ctx.actions, feature_configuration = feature_configuration, cc_toolchain = cc_toolchain, compilation_outputs = compilation_outputs, linking_contexts = linking_contexts, user_link_flags = ["-T", ctx.file._linker_script.path] + ctx.attr.linkopts, output_type = "executable", ) runfiles = ctx.runfiles(files = [linking_outputs.executable]) for data_dep in ctx.attr.data: runfiles = runfiles.merge(ctx.runfiles(transitive_files = data_dep[DefaultInfo].files)) runfiles = runfiles.merge(data_dep[DefaultInfo].data_runfiles) for src in ctx.attr.srcs: runfiles = runfiles.merge(src[DefaultInfo].default_runfiles) for dep in ctx.attr.deps: runfiles = runfiles.merge(dep[DefaultInfo].default_runfiles) return [DefaultInfo( files = depset([linking_outputs.executable]), runfiles = runfiles, )] attrs = { "srcs": attr.label_list(allow_files = True), "hdrs": attr.label_list(allow_files = True), "aux_srcs": attr.label_list(allow_files = True), "includes": attr.string_list(), "defines": attr.string_list(), "copts": attr.string_list(), "linkopts": attr.string_list(), "local_defines": attr.string_list(), "alwayslink": attr.bool(default = False), "strip_include_prefix": attr.string(), "include_prefix": attr.string(), "deps": attr.label_list(providers = [CcInfo]), "data": attr.label_list(allow_files = True), "_linker_script": attr.label( allow_single_file = True, default = Label("//risc0/zkvm/platform:risc0.ld"), ), "_allowlist_function_transition": attr.label( default = "@bazel_tools//tools/allowlists/function_transition_allowlist", ), } risc0_cc_library = rule( implementation = _risc0_cc_library_impl, attrs = attrs, toolchains = [CC_TOOLCHAIN_TYPE], fragments = ["cpp"], incompatible_use_toolchain_transition = True, cfg = risc0_transition, ) risc0_cc_binary = rule( implementation = _risc0_cc_binary_impl, attrs = attrs, toolchains = [CC_TOOLCHAIN_TYPE], fragments = ["cpp"], incompatible_use_toolchain_transition = True, cfg = risc0_transition, )
# Merge sort is a divide and conquer type of algorithm that consists of two steps. # 1) Continuously divide the unsorted list until you have N sublists, where each sublist has 1 element that is “unsorted” and N is the number of elements in the original array. # 2) Repeatedly merge i.e conquer the sublists together 2 at a time to produce new sorted sublists until all elements have been fully merged into a single sorted array. def merge_sort(arr): # The last array split if len(arr) <= 1: return arr mid = len(arr) // 2 # Perform merge_sort recursively on both halves left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:]) # Merge each side together return merge(left, right, arr.copy()) def merge(left, right, merged): left_cursor, right_cursor = 0, 0 while left_cursor < len(left) and right_cursor < len(right): # Sort each one and place into the result if left[left_cursor] <= right[right_cursor]: merged[left_cursor + right_cursor] = left[left_cursor] left_cursor += 1 else: merged[left_cursor + right_cursor] = right[right_cursor] right_cursor += 1 for left_cursor in range(left_cursor, len(left)): merged[left_cursor + right_cursor] = left[left_cursor] for right_cursor in range(right_cursor, len(right)): merged[left_cursor + right_cursor] = right[right_cursor] return merged
"""Cornershop Models. """ class Aisle: """Model for an aisle. """ def __init__(self, data:dict): for key in data: setattr(self, key, data[key]) self.products = [Product(p) for p in self.products] def __repr__(self) -> str: return f'<cornershop.models.Aisle: {self.aisle_id} - {self.aisle_name}>' def __str__(self) -> str: return self.aisle_id class Branch: """Model for a branch. """ def __init__(self, data:dict): self.ad_campaign = data['ad_campaign'] self.aisles = [Aisle(a) for a in data['aisles']] def __str__(self) -> str: return 'Branch' def __repr__(self) -> str: return f'<cornershop.models.Branch>' class Country: """Model for a country. """ def __init__(self, data:dict): for key in data: setattr(self, key, data[key]) def __repr__(self) -> str: return f'<cornershop.models.Country: {self.name}>' def __str__(self) -> str: return self.name class Group: """Model for a group. """ def __init__(self, data:dict): for key in data: setattr(self, key, data[key]) self.items = [GroupItem(item) for item in data['items']] def __repr__(self) -> str: return f'<cornershop.model.Group: {self.name}>' def __str__(self) -> str: return self.name class GroupItem: """Model for a group item. """ def __init__(self, data:dict): self.type = data['type'] self.badges = data['badges'] for key in data['content']: setattr(self, key, data['content'][key]) def __repr__(self) -> str: return f'<cornershop.model.GroupItem: {self.name}>' def __str__(self) -> str: return self.name class Product: """Model for a product. """ def __init__(self, data:dict): for key in data: setattr(self, key, data[key]) def __repr__(self) -> str: return f'<cornershop.models.Product: {self.id} - {self.name}>' def __str__(self) -> str: return self.name class Result: """Model for branch search results. """ def __init__(self, data:dict): self.store = Store(data['store']) self.search_result = SearchResult(data['search_result']) def __str__(self) -> str: return self.store.name def __repr__(self) -> str: return f'<cornershop.models.Result: "{self.search_result.search_term}" on {self.store.name}>' class SearchResult: """Model for the search result query. """ def __init__(self, data:dict): self.search_term = data['search_term'] self.aisles = [Aisle(aisle_data) for aisle_data in data['aisles']] def __repr__(self) -> str: return f'<cornershop.models.SearchResult: {self.search_term}>' class Store: """Model for a store. """ def __init__(self, data:dict): for key in data: setattr(self, key, data[key]) def __str__(self) -> str: return self.name def __repr__(self) -> str: return f'<cornershop.models.Store: {self.name}>'
# Copyright 2014 The Bazel Authors. All rights reserved. # # 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. load( "@io_bazel_rules_go//go/private:context.bzl", "go_context", ) load( "@io_bazel_rules_go//go/private:providers.bzl", "GoPath", ) load( "@io_bazel_rules_go//go/private:rules/rule.bzl", "go_rule", ) def _go_vet_generate_impl(ctx): print(""" EXPERIMENTAL: the go_vet_test rule is still very experimental Please do not rely on it for production use, but feel free to use it and file issues """) go = go_context(ctx) script_file = go.declare_file(go, ext=".bash") gopath = [] files = ctx.files.data + go.stdlib.files gopath = [] packages = [] for data in ctx.attr.data: entry = data[GoPath] gopath += [entry.gopath] packages += [package.dir for package in entry.packages] ctx.actions.write(output=script_file, is_executable=True, content=""" export GOPATH="{gopath}" {go} tool vet {packages} """.format( go=go.go.short_path, gopath=":".join(['$(pwd)/{})'.format(entry) for entry in gopath]), packages=" ".join(packages), )) return struct( files = depset([script_file]), runfiles = ctx.runfiles(files, collect_data = True), ) _go_vet_generate = go_rule( _go_vet_generate_impl, attrs = { "data": attr.label_list( providers = [GoPath], cfg = "data", ), }, ) def go_vet_test(name, data, **kwargs): script_name = "generate_"+name _go_vet_generate( name=script_name, data=data, tags = ["manual"], ) native.sh_test( name=name, srcs=[script_name], data=data, **kwargs )
""" ========================== kikola.contrib.basicsearch ========================== Application to lightweight search over models, existed in your project. Installation ============ 1. Add ``kikola.contrib.basicsearch`` to your project's ``settings`` ``INSTALLED_APPS`` var. 2. Set up ``SEARCH_MODELS`` var in your project's ``settings`` module. (see default config for ``SEARCH_MODELS`` below_) 3. Include ``kikola.contrib.basicsearch.urls`` in your project's ``ROOT_URLCONF`` module:: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^search/', include('kikola.contrib.basicsearch.urls')), ) 4. Go to search url and enjoy :) .. _below: `SEARCH_MODELS`_ Configuration ============= You can customize ``basicsearch`` application by next setting vars SEARCH_FORM ----------- Full path to default ``SearchForm`` class. By default uses ``kikola.contrib.basicsearch.forms.SearchForm`` class. SEARCH_MODELS ------------- **Required.** Sets up models for searching. For example to search over Django's FlatPages use next config:: SEARCH_MODELS = { # Use same format as ``app_label`` in serialized data 'flatpages.FlatPage': { # Object description in search results 'description': '{{ obj.content|truncatewords_html:20 }}', # Object fields to search 'fields': ('title', 'content'), # Use fulltext search (use this only when # ``settings.DATABASE_ENGINE == 'mysql'``) 'fulltext': False, # Object link in search results (by default # ``{{ obj.get_absolute_url }}`` used) 'link': '{% url flatpage obj.url %}', # Priority. Useful when search not over one model. Objects with # higher priority rendering first in search results. 'priority': 0, # Object title in search results (by default ``{{ obj }}`` used) 'title': '{{ obj.title }}', # Trigger. Custom filter to found search results. For example, # current trigger enables search only over flatpages with # ``enable_comments``. # # To disable trigger, set ``'trigger': None`` 'trigger': lambda obj: obj.enable_comments, } } SEARCH_NOT_FOUND_MESSAGE ------------------------ Default search "not found" message. By default: ``Any objects was found by your query.`` SEARCH_QUERY_MIN_LENGTH ----------------------- Minimal length of search query. By default: 3. SEARCH_QUERY_MAX_LENGTH ----------------------- Maximal length of search query. By default: 64. SEARCH_RESULTS_PER_PAGE ----------------------- Number of search results, rendering at search page. By default: 10. SEARCH_TEMPLATE_NAME -------------------- Template used for rendering search results. By default: ``basicsearch/search.html``. """
""" ################################################################################################## # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : lgpma_pub.py # Abstract : Model settings for LGPMA detector on PubTabNet # Current Version: 1.0.0 # Date : 2021-09-18 ################################################################################################## """ _base_ = "./lgpma_base.py" data = dict( samples_per_gpu=3, workers_per_gpu=1, train=dict( ann_file='path/to/PubTabNet_datalist_train_detection.json', img_prefix='path/to/PubTabNet'), val=dict( ann_file='path/to/PubTabNet_2.0.0_val.jsonl', img_prefix='path/to/PubTabNet'), test=dict( samples_per_gpu=1, ann_file='path/to/PubTabNet_2.0.0_val.jsonl', img_prefix='path/to/PubTabNet/Images/val/') ) # yapf:enable # runtime settings checkpoint_config = dict(interval=1, filename_tmpl='checkpoint/maskrcnn-lgpma-pub-e{}.pth') work_dir = 'path/to/workdir'
class Solution: def findLHS(self, nums: List[int]) -> int: d=collections.defaultdict(lambda:0) for i in range(0,len(nums)): d[nums[i]]+=1 maxi=0 for i in d.keys(): if(d.get(i+1,"E")!="E"): maxi=max(maxi,d[i]+d[i+1]) return maxi
telugumap = { 0: u"సున్న", 1: u"ఒకటి", 2: u"రెండు", 3: u"మూడు", 4: u"నాలుగు", 5: u"ఐదు", 6: u"ఆరు", 7: u"ఏడు", 8: u"ఎనిమిది", 9: u"తొమ్మిది", 10: u"పది", 11: u"పదకొండు", 12: u"పన్నెండు", 13: u"పదమూడు", 14: u"పద్నాలుగు", 15: u"పదిహేను", 16: u"పదహారు", 17: u"పదిహేడు", 18: u"పద్దెనిమిది", 19: u"పంతొమ్మది", 20: u"ఇరవై", 21: u"ఇరవై ఒకటి", 22: u"ఇరవై రెండు", 23: u"ఇరవై మూడు", 24: u"ఇరవై నాలుగు", 25: u"ఇరవై ఐదు", 26: u"ఇరవై ఆరు", 27: u"ఇరవై ఏడు", 28: u"ఇరవై ఎనిమిది", 29: u"ఇరవై తొమ్మిది", 30: u"ముప్పై", 31: u"ముప్పై ఒకటి", 32: u"ముప్పై రెండు", 33: u"ముప్పై మూడు", 34: u"ముప్పై నాలుగు", 35: u"ముప్పై ఐదు", 36: u"ముప్పై ఆరు", 37: u"ముప్పై ఏడు", 38: u"ముప్పై ఎనిమిది", 39: u"ముప్పై తొమ్మిది", 40: u"నలభై", 41: u"నలభై ఒకటి", 42: u"నలభై రెండు", 43: u"నలభై మూడు", 44: u"నలభై నాలుగు", 45: u"నలభై ఐదు", 46: u"నలభై ఆరు", 47: u"నలభై ఏడు", 48: u"నలభై ఎనిమిది", 49: u"నలభై తొమ్మిది", 50: u"యాభై", 51: u"యాభై ఒకటి", 52: u"యాభై రెండు", 53: u"యాభై మూడు", 54: u"యాభై నాలుగు", 55: u"యాభై ఐదు", 56: u"యాభై ఆరు", 57: u"యాభై ఏడు", 58: u"యాభై ఎనిమిది", 59: u"యాభై తొమ్మిది", 60: u"అరవై", 61: u"అరవై ఒకటి", 62: u"అరవై రెండు", 63: u"అరవై మూడు", 64: u"అరవై నాలుగు", 65: u"అరవై ఐదు", 66: u"అరవై ఆరు", 67: u"అరవై ఏడు", 68: u"అరవై ఎనిమిది", 69: u"అరవై తొమ్మిది", 70: u"డెభ్భై", 71: u"డెభ్భై ఒకటి", 72: u"డెభ్భై రెండు", 73: u"డెభ్భై మూడు", 74: u"డెభ్భై నాలుగు", 75: u"డెభ్భై ఐదు", 76: u"డెభ్భై ఆరు", 77: u"డెభ్భై ఏడు", 78: u"డెభ్భై ఎనిమిది", 79: u"డెభ్భై తొమ్మిది", 80: u"ఎనభై", 81: u"ఎనభై ఒకటి", 82: u"ఎనభై రెండు", 83: u"ఎనభై మూడు", 84: u"ఎనభై నాలుగు", 85: u"ఎనభై ఐదు", 86: u"ఎనభై ఆరు", 87: u"ఎనభై ఏడు", 88: u"ఎనభై ఎనిమిది", 89: u"ఎనభై తొమ్మిది", 90: u"తొంభై", 91: u"తొంభై ఒకటి", 92: u"తొంభై రెండు", 93: u"తొంభై మూడు", 94: u"తొంభై నాలుగు", 95: u"తొంభై ఐదు", 96: u"తొంభై ఆరు", 97: u"తొంభై ఏడు", 98: u"తొంభై ఎనిమిది", 99: u"తొంభై తొమ్మిది", }
model_config = {} # alpha config model_config['alpha_jump_mode'] = "linear" model_config['iter_alpha_jump'] = [] model_config['alpha_jump_vals'] = [] model_config['alpha_n_jumps'] = [0, 600, 600, 600, 600, 600, 600, 600, 600] model_config['alpha_size_jumps'] = [0, 32, 32, 32, 32, 32, 32, 32, 32, 32] # base config model_config['max_iter_at_scale'] = [48000, 96000, 96000, 96000, 96000, 192000, 192000, 192000, 200000] model_config['scaling_layer_channels'] = [512, 512, 512, 512, 256, 128, 64, 32, 16] model_config['mini_batch_size'] = [16, 16, 16, 16, 16, 8, 8, 8, 8] model_config['dim_latent_vector'] = 512 model_config['lambda_gp'] = 10 model_config["epsilon_d"] = 0.001 model_config["learning_rate"] = 0.001
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def multiples_sum(): return sum(i for i in range(1000) if (i % 3 == 0 or i % 5 == 0))
class LineItem(object): def __init__(self, description, weight, price): self.description = description self.set_weight(weight) self.price = price def subtotal(self): return self.get_weight() * self.price def get_weight(self): return self.__weight def set_weight(self, value): if value > 0: self.__weight = value else: raise ValueError('value must be > 0')
_out_ = "" _in_ = "" _err_ = "" _root_ = ""
class FrontMiddleBackQueue: def __init__(self): self.queue = [] def pushFront(self, val: int): self.queue.insert(0,val) def pushMiddle(self, val: int): self.queue.insert(len(self.queue) // 2,val) def pushBack(self, val: int): self.queue.append(val) def popFront(self): return (self.queue or [-1]).pop(0) def popMiddle(self): return (self.queue or [-1]).pop((len(self.queue)-1)//2) def popBack(self): return (self.queue or [-1]).pop() # Your FrontMiddleBackQueue object will be instantiated and called as such: # obj = FrontMiddleBackQueue() # obj.pushFront(val) # obj.pushMiddle(val) # obj.pushBack(val) # param_4 = obj.popFront() # param_5 = obj.popMiddle() # param_6 = obj.popBack()
# Right click functions and operators def dump(obj, text): print('-'*40, text, '-'*40) for attr in dir(obj): if hasattr( obj, attr ): print( "obj.%s = %s" % (attr, getattr(obj, attr))) def split_path(str): """Splits a data path into rna + id. This is the core of creating controls for properties. """ # First split the last part of the dot-chain rna, path = str.rsplit('.',1) # If the last part contains a '][', it's a custom property for a collection item if '][' in path: # path is 'somecol["itemkey"]["property"]' path, rem = path.rsplit('[', 1) # path is 'somecol["itemkey"]' ; rem is '"property"]' rna = rna + '.' + path # rna is 'rna.path.to.somecol["itemkey"]' path = '[' + rem # path is '["property"]' # If the last part only contains a single '[', # it's an indexed value elif '[' in path: # path is 'someprop[n]' path, rem = path.rsplit('[', 1) # path is 'someprop' ; rem is ignored return rna, path
# alternative characters T = input() lst = [] results = [] if T >= 1 and T <= 10: for i in range(T): lst.append(raw_input()) lst = filter(lambda x: len(x) >= 1 and len(x) <= 10**5, lst) for cst in lst: delct = 0 for j in range(len(cst)-1): if cst[j] == cst[j+1]: delct += 1 results.append(delct) for v in results: print(v)
a = int(input()) c = int(input()) s = True for b in range(a - 1): if int(input()) >= c: s = False if s: print("YES") else: print("NO")
n, m = map(int, input().split()) shops = [tuple(map(int, input().split())) for _ in range(n)] shops.sort(key=lambda x: x[0]) ans = 0 for a, b in shops: if m <= b: ans += a * m break else: ans += a * b m -= b print(ans)
''' Power of Two Solution Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16 Output: true Explanation: 24 = 16 Example 3: Input: 218 Output: false''' n = int(input()) if n <= 0 : print('false') while n%2 == 0: n = n/2 print(n==1)
# Copyright 2017 Lawrence Kesteloot # # 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. # Defines the various low-level model structures. These mirror the database tables. # Represents a photo that was taken. Multiple files on disk (PhotoFile) can represent # this photo. class Photo(object): def __init__(self, id, hash_back, rotation, rating, date, display_date, label): self.id = id # SHA-1 of the last 1 kB of the file. self.hash_back = hash_back # In degrees. self.rotation = rotation # 1 to 5, where 1 means "I'd be okay deleting this file", 2 means "I don't want # to show this on this slide show program", 3 is the default, 4 means "This is # a great photo", and 5 means "On my deathbed I want a photo album with this photo." self.rating = rating # Unix date when the photo was taken. Defaults to the date of the file. self.date = date # Date as displayed to the user. Usually a friendly version of "date" but might # be more vague, like "Summer 1975". self.display_date = display_date # Label to display. Defaults to a cleaned up version of the pathname, but could be # edited by the user. self.label = label # In-memory use only, not stored in database. Refers to the preferred photo file to # show for this photo. self.pathname = None # Represents a photo file on disk. Multiple of these (including minor changes in the header) # might represent the same Photo. class PhotoFile(object): def __init__(self, pathname, hash_all, hash_back): # Pathname relative to the root of the photo tree. self.pathname = pathname # SHA-1 of the entire file. self.hash_all = hash_all # SHA-1 of the last 1 kB of the file. self.hash_back = hash_back # Represents an email that was sent to a person about a photo. class Email(object): def __init__(self, id, pathname, person_id, sent_at, photo_id): self.id = id self.person_id = person_id self.sent_at = sent_at self.photo_id = photo_id
# eerste negen cijfers van ISBN-10 code inlezen en omzetten naar integers x1 = int(input()) x2 = int(input()) x3 = int(input()) x4 = int(input()) x5 = int(input()) x6 = int(input()) x7 = int(input()) x8 = int(input()) x9 = int(input()) # controlecijfer berekenen x10 = (x1 + 2 * x2 + 3 * x3 + 4 * x4 + 5 * x5 + 6 * x6 + 7 * x7 + 8 * x8 + 9 * x9) % 11 # controlecijfer uitschrijven print(x10)
def get_attr_or_callable(obj, name): target = getattr(obj, name) if callable(target): return target() return target
SAMPLE_NRTM_V3 = """ % NRTM v3 contains serials per object. % Another comment %START Version: 3 TEST 11012700-11012701 ADD 11012700 person: NRTM test address: NowhereLand source: TEST DEL 11012701 inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ # NRTM v1 has no serials per object SAMPLE_NRTM_V1 = """%START Version: 1 TEST 11012700-11012701 ADD person: NRTM test address: NowhereLand source: TEST DEL inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_V1_TOO_MANY_ITEMS = """ % The serial range is one item, but there are two items in here. %START Version: 1 TEST 11012700-11012700 FILTERED ADD person: NRTM test address: NowhereLand source: TEST DEL inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_INVALID_VERSION = """%START Version: 99 TEST 11012700-11012700""" SAMPLE_NRTM_V3_SERIAL_GAP = """ # NRTM v3 serials are allowed to have gaps per https://github.com/irrdnet/irrd/issues/85 %START Version: 3 TEST 11012699-11012703 ADD 11012700 person: NRTM test address: NowhereLand source: TEST DEL 11012701 inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_V3_SERIAL_OUT_OF_ORDER = """ # NRTM v3 serials can have gaps, but must always increase. %START Version: 3 TEST 11012699-11012703 ADD 11012701 person: NRTM test address: NowhereLand source: TEST DEL 11012701 inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_V3_INVALID_MULTIPLE_START_LINES = """ %START Version: 3 TEST 11012700-11012700 %START Version: 3 ARIN 11012700-11012700 ADD 11012701 person: NRTM test address: NowhereLand source: TEST %END TEST """ SAMPLE_NRTM_INVALID_NO_START_LINE = """ ADD 11012701 person: NRTM test address: NowhereLand source: TEST DEL 11012700 inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_V3_NO_END = """%START Version: 3 TEST 11012700-11012701"""
class Packager: """ Packager class. This class is used to generate the required XML to send back to the client. """ def __init__(self): self.xml_version = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" self.begin_root = "<kevlar>" self.end_root = "</kevlar>" def generate_account(self, username: str, password: str, database: str, hmac: str, initialization_vector: str): """ Generate account document by using the upload-able data. :param username: The account username. :param password: The account password. :param database: The account database. :param hmac: The authentication hmac of the database. :param initialization_vector: The initialization vector for that account. :return: The xml document. """ document = self.xml_version + self.begin_root document += f"<username>{username}</username>" document += f"<password>{password}</password>" document += f"<database>{database}</database>" document += f"<hmac>{hmac}</hmac>" document += f"<iv>{initialization_vector}</iv>" return document + self.end_root def generate_status(self, status: str): """ Generate the status document by using the status generated by the server. :param status: The status to include. :return: The xml document. """ document = self.xml_version + self.begin_root document += f"<status>{status}</status>" return document + self.end_root
# These are the "Tableau 20" colors as RGB. tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. for i in range(len(tableau20)): r, g, b = tableau20[i] tableau20[i] = (r / 255., g / 255., b / 255.)
"""Utility functions for RtMidi backend. These are in a separate file so they can be tested without the `python-rtmidi` package. """ def expand_alsa_port_name(port_names, name): """Expand ALSA port name. RtMidi/ALSA includes client name and client:port number in the port name, for example: TiMidity:TiMidity port 0 128:0 This allows you to specify only port name or client:port name when opening a port. It will compare the name to each name in port_names (typically returned from get_*_names()) and try these three variants in turn: TiMidity:TiMidity port 0 128:0 TiMidity:TiMidity port 0 TiMidity port 0 It returns the first match. If no match is found it returns the passed name so the caller can deal with it. """ if name is None: return None for port_name in port_names: if name == port_name: return name # Try without client and port number (for example 128:0). without_numbers = port_name.rsplit(None, 1)[0] if name == without_numbers: return port_name if ':' in without_numbers: without_client = without_numbers.split(':', 1)[1] if name == without_client: return port_name else: # Let caller deal with it. return name
# -*- coding: utf-8 -*- # Which templates don't you want to generate? (You can use regular expressions here!) # Use strings (with single or double quotes), and separate each template/regex in a line terminated with a comma. IGNORE_JINJA_TEMPLATES = [ '.*base.jinja', '.*tests/.*' ] # Do you have any additional variables to the templates? Put 'em here! (use dictionary ('key': value) format) EXTRA_VARIABLES = { 'test_type': 'Array', 'name': 'float', 'dim': 3, 'type': 'float', 'suffix': 'f', 'extends': '[3]' } OUTPUT_OPTIONS = { 'extension': '3_arr.cpp', # Including leading '.', example '.html' 'remove_double_extension': False }
c = ('\033[m' # 0 - SEN COR '\033[0;30;41m', # 1 - VERMELHO '\033[0;30;42m', # 2 - VERDE '\033[0;30;43m', # 3 - AMARELO '\033[0;30;44m', # 4 - AZUL '\033[7;30mm', #6 - BRANCO '\033[0;30;45m', # 5 - ROXO ); def ajudainterativa(com): titulo('Acessando o manual do comando \'{com}\'', 4) print(c[5], end='') help(com) print(c[0], end='') def titulo(msg, cor=0): tam = len(msg)+4 print(c[cor], end='') print('~'*tam) print(f' {msg} ') print('~'*tam) print(c[0], end='') comando = '' while True: titulo("SISTEMA DE AJUDA PYHELP", 2) comando = str(input("Funçao ou Biblioteca > ")) if comando.upper() == "FIM": break else: ajudainterativa(comando) titulo('ATÉ LOGO', 1) #print('\033[;0;31mERRO! Digite um número inteiro válido.\033[m')
class Solution(object): # def removeDuplicates(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # ls = len(nums) # if ls <= 1: # return ls # last = nums[0] # pos = 1 # for t in nums[1:]: # if t == last: # continue # else: # nums[pos] = t # pos += 1 # last = t # return pos # https://leetcode.com/articles/remove-duplicates-sorted-array/ def removeDuplicates(self, nums): if len(nums) == 0: return 0 left = 0 for i in range(1, len(nums)): if nums[left] == nums[i]: continue else: left += 1 nums[left] = nums[i] return left + 1
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: results = [] def dfs (elements, start: int, k: int): if k == 0: results.append(elements[:]) for i in range (start, n+1): elements.append(i) dfs (elements, i+1, k-1) elements.pop() dfs ([], 1, k) return results
load( "@build_bazel_rules_apple//apple:providers.bzl", "AppleBundleInfo", "AppleResourceInfo", "IosFrameworkBundleInfo", ) load( "@build_bazel_rules_apple//apple/internal:resources.bzl", "resources", ) load( "//rules:providers.bzl", "AvoidDepsInfo", ) load( "@build_bazel_rules_apple//apple/internal/providers:embeddable_info.bzl", "AppleEmbeddableInfo", "embeddable_info", ) load( "//rules/internal:objc_provider_utils.bzl", "objc_provider_utils", ) def _framework_middleman(ctx): resource_providers = [] objc_providers = [] dynamic_framework_providers = [] apple_embeddable_infos = [] cc_providers = [] def _collect_providers(lib_dep): if AppleEmbeddableInfo in lib_dep: apple_embeddable_infos.append(lib_dep[AppleEmbeddableInfo]) # Most of these providers will be passed into `deps` of apple rules. # Don't feed them twice. There are several assumptions rules_apple on # this if IosFrameworkBundleInfo in lib_dep: if CcInfo in lib_dep: cc_providers.append(lib_dep[CcInfo]) if AppleResourceInfo in lib_dep: resource_providers.append(lib_dep[AppleResourceInfo]) if apple_common.Objc in lib_dep: objc_providers.append(lib_dep[apple_common.Objc]) if apple_common.AppleDynamicFramework in lib_dep: dynamic_framework_providers.append(lib_dep[apple_common.AppleDynamicFramework]) for dep in ctx.attr.framework_deps: _collect_providers(dep) # Loop AvoidDepsInfo here as well if AvoidDepsInfo in dep: for lib_dep in dep[AvoidDepsInfo].libraries: _collect_providers(lib_dep) # Here we only need to loop a subset of the keys objc_provider_fields = objc_provider_utils.merge_objc_providers_dict(providers = objc_providers, merge_keys = [ "dynamic_framework_file", ]) # Add the frameworks to the linker command dynamic_framework_provider = objc_provider_utils.merge_dynamic_framework_providers(ctx, dynamic_framework_providers) objc_provider_fields["dynamic_framework_file"] = depset( transitive = [dynamic_framework_provider.framework_files, objc_provider_fields.get("dynamic_framework_file", depset([]))], ) objc_provider = apple_common.new_objc_provider(**objc_provider_fields) cc_info_provider = cc_common.merge_cc_infos(direct_cc_infos = [], cc_infos = cc_providers) providers = [ dynamic_framework_provider, cc_info_provider, objc_provider, IosFrameworkBundleInfo(), AppleBundleInfo( archive = None, archive_root = None, binary = None, # These arguments are unused - however, put them here incase that # somehow changes to make it easier to debug bundle_id = "com.bazel_build_rules_ios.unused", bundle_name = "bazel_build_rules_ios_unused", ), ] embed_info_provider = embeddable_info.merge_providers(apple_embeddable_infos) if embed_info_provider: providers.append(embed_info_provider) if len(resource_providers) > 0: resource_provider = resources.merge_providers( default_owner = str(ctx.label), providers = resource_providers, ) providers.append(resource_provider) return providers framework_middleman = rule( implementation = _framework_middleman, attrs = { "framework_deps": attr.label_list( cfg = apple_common.multi_arch_split, mandatory = True, doc = """Deps that may contain frameworks """, ), "platform_type": attr.string( mandatory = False, doc = """Internal - currently rules_ios uses the dict `platforms` """, ), "minimum_os_version": attr.string( mandatory = False, doc = """Internal - currently rules_ios the dict `platforms` """, ), }, doc = """ This is a volatile internal rule to make frameworks work with rules_apples bundling logic Longer term, we will likely get rid of this and call partial like apple_framework directly so consider it an implementation detail """, ) def _dedupe_key(key, avoid_libraries, objc_provider_fields, check_name = False): updated_library = [] exisiting_library = objc_provider_fields.get(key, depset([])) for f in exisiting_library.to_list(): check_key = (f.basename if check_name else f) if check_key in avoid_libraries: continue updated_library.append(f) objc_provider_fields[key] = depset(updated_library) def _dep_middleman(ctx): objc_providers = [] cc_providers = [] avoid_libraries = {} def _collect_providers(lib_dep): if apple_common.Objc in lib_dep: objc_providers.append(lib_dep[apple_common.Objc]) def _process_avoid_deps(avoid_dep_libs): for dep in avoid_dep_libs: if apple_common.Objc in dep: for lib in dep[apple_common.Objc].library.to_list(): avoid_libraries[lib] = True for lib in dep[apple_common.Objc].force_load_library.to_list(): avoid_libraries[lib] = True for lib in dep[apple_common.Objc].imported_library.to_list(): avoid_libraries[lib.basename] = True for lib in dep[apple_common.Objc].static_framework_file.to_list(): avoid_libraries[lib.basename] = True for dep in ctx.attr.deps: _collect_providers(dep) # Loop AvoidDepsInfo here as well if AvoidDepsInfo in dep: _process_avoid_deps(dep[AvoidDepsInfo].libraries) for lib_dep in dep[AvoidDepsInfo].libraries: _collect_providers(lib_dep) # Pull AvoidDeps from test deps for dep in (ctx.attr.test_deps if ctx.attr.test_deps else []): if AvoidDepsInfo in dep: _process_avoid_deps(dep[AvoidDepsInfo].libraries) # Merge the entire provider here objc_provider_fields = objc_provider_utils.merge_objc_providers_dict(providers = objc_providers, merge_keys = [ "force_load_library", "imported_library", "library", "link_inputs", "linkopt", "sdk_dylib", "sdk_framework", "source", "static_framework_file", "weak_sdk_framework", ]) # Ensure to strip out static link inputs _dedupe_key("library", avoid_libraries, objc_provider_fields) _dedupe_key("force_load_library", avoid_libraries, objc_provider_fields) _dedupe_key("imported_library", avoid_libraries, objc_provider_fields, check_name = True) _dedupe_key("static_framework_file", avoid_libraries, objc_provider_fields, check_name = True) objc_provider = apple_common.new_objc_provider(**objc_provider_fields) cc_info_provider = cc_common.merge_cc_infos(direct_cc_infos = [], cc_infos = cc_providers) providers = [ cc_info_provider, objc_provider, ] return providers dep_middleman = rule( implementation = _dep_middleman, attrs = { "deps": attr.label_list( cfg = apple_common.multi_arch_split, mandatory = True, doc = """Deps that may contain frameworks """, ), "test_deps": attr.label_list( cfg = apple_common.multi_arch_split, allow_empty = True, ), "platform_type": attr.string( mandatory = False, doc = """Internal - currently rules_ios uses the dict `platforms` """, ), "minimum_os_version": attr.string( mandatory = False, doc = """Internal - currently rules_ios the dict `platforms` """, ), }, doc = """ This is a volatile internal rule to make frameworks work with rules_apples bundling logic Longer term, we will likely get rid of this and call partial like apple_framework directly so consider it an implementation detail """, )
text = 'Writing to a file which\n' fileis = open('hello.txt', 'w') fileis.write(text) fileis.close()
def gcd(p, q): pTrue = isinstance(p,int) qTrue = isinstance(q,int) if pTrue and qTrue: if q == 0: return p r = p%q return gcd(q,r) else: print("Error!") return 0
# -*- coding: utf-8 -*- keywords = { "abbrev", "abs", "abstime", "abstimeeq", "abstimege", "abstimegt", "abstimein", "abstimele", "abstimelt", "abstimene", "abstimeout", "abstimerecv", "abstimesend", "aclcontains", "aclinsert", "aclitemeq", "aclitemin", "aclitemout", "aclremove", "acos", "add_months", "aes128", "aes256", "age", "all", "alloc_rowid", "allowoverwrite", "alt_to_iso", "alt_to_koi8r", "alt_to_mic", "alt_to_win1251", "analyse", "analyze", "and", "any", "any_in", "any_out", "anyarray_in", "anyarray_out", "anyarray_recv", "anyarray_send", "anyelement_in", "anyelement_out", "area", "areajoinsel", "areasel", "array", "array_append", "array_cat", "array_coerce", "array_dims", "array_eq", "array_ge", "array_gt", "array_in", "array_le", "array_length_coerce", "array_lower", "array_lt", "array_ne", "array_out", "array_prepend", "array_recv", "array_send", "array_type_length_coerce", "array_upper", "as", "asc", "ascii", "ascii_to_mic", "asin", "atan", "atan2", "authorization", "avg", "az64", "backup", "between", "big5_to_euc_tw", "big5_to_mic", "binary", "bit", "bit_and", "bit_in", "bit_length", "bit_or", "bit_out", "bit_recv", "bit_send", "bitand", "bitcat", "bitcmp", "biteq", "bitge", "bitgt", "bitle", "bitlt", "bitne", "bitnot", "bitor", "bitxor", "blanksasnull", "bool", "bool_and", "bool_or", "booleq", "boolge", "boolgt", "boolin", "boolle", "boollt", "boolne", "boolout", "boolrecv", "boolsend", "both", "box", "box_above", "box_add", "box_below", "box_center", "box_contain", "box_contained", "box_distance", "box_div", "box_eq", "box_ge", "box_gt", "box_in", "box_intersect", "box_le", "box_lt", "box_mul", "box_out", "box_overlap", "box_recv", "box_same", "box_send", "box_sub", "bpchar", "bpchar_pattern_eq", "bpchar_pattern_ge", "bpchar_pattern_gt", "bpchar_pattern_le", "bpchar_pattern_lt", "bpchar_pattern_ne", "bpcharcmp", "bpchareq", "bpcharge", "bpchargt", "bpcharle", "bpcharlike", "bpcharlt", "bpcharne", "bpcharnlike", "bpcharout", "bpcharrecv", "bpcharregexeq", "bpcharregexne", "bpcharsend", "broadcast", "btabstimecmp", "btarraycmp", "btbeginscan", "btboolcmp", "btbpchar_pattern_cmp", "btbuild", "btbulkdelete", "btcharcmp", "btcostestimate", "btendscan", "btgettuple", "btinsert", "btint24cmp", "btint28cmp", "btint2cmp", "btint42cmp", "btint48cmp", "btint4cmp", "btint82cmp", "btint84cmp", "btint8cmp", "btmarkpos", "btname_pattern_cmp", "btnamecmp", "btoidcmp", "btoidvectorcmp", "btreltimecmp", "btrescan", "btrestrpos", "bttext_pattern_cmp", "bttextcmp", "bttintervalcmp", "btvacuumcleanup", "byteacat", "byteacmp", "byteaeq", "byteage", "byteagt", "byteain", "byteale", "bytealike", "bytealt", "byteane", "byteanlike", "byteaout", "bytearecv", "byteasend", "bytedict", "bzip2", "card_check", "case", "cash_cmp", "cash_div_int2", "cash_div_int4", "cash_eq", "cash_ge", "cash_gt", "cash_in", "cash_le", "cash_lt", "cash_mi", "cash_mul_int2", "cash_mul_int4", "cash_ne", "cash_out", "cash_pl", "cash_recv", "cash_send", "cash_words", "cashlarger", "cashsmaller", "cast", "cbrt", "ceil", "ceiling", "center", "char", "char_length", "character_length", "chareq", "charge", "chargt", "charle", "charlt", "charne", "charout", "charrecv", "charsend", "check", "checksum", "chr", "cideq", "cidin", "cidout", "cidr", "cidr_in", "cidr_out", "cidr_recv", "cidr_send", "cidrecv", "cidsend", "circle", "circle_above", "circle_add_pt", "circle_below", "circle_center", "circle_contain", "circle_contain_pt", "circle_contained", "circle_distance", "circle_div_pt", "circle_eq", "circle_ge", "circle_gt", "circle_in", "circle_le", "circle_lt", "circle_mul_pt", "circle_ne", "circle_out", "circle_overlap", "circle_recv", "circle_same", "circle_send", "circle_sub_pt", "close_lb", "close_ls", "close_lseg", "close_pb", "close_pl", "close_ps", "close_sb", "close_sl", "collate", "column", "concat", "constraint", "contains", "contjoinsel", "contsel", "convert", "convert_timezone", "convert_using", "cos", "cot", "count", "crc32", "create", "credentials", "cross", "cume_dist", "current_database", "current_date", "current_schema", "current_schemas", "current_setting", "current_time", "current_timestamp", "current_user", "current_user_id", "currtid", "currtid2", "currval", "cvtile_sf", "date", "date_add", "date_cmp", "date_cmp_timestamp", "date_cmp_timestamptz", "date_eq", "date_eq_timestamp", "date_eq_timestamptz", "date_ge", "date_ge_timestamp", "date_ge_timestamptz", "date_gt", "date_gt_timestamp", "date_gt_timestamptz", "date_in", "date_larger", "date_le", "date_le_timestamp", "date_le_timestamptz", "date_lt", "date_lt_timestamp", "date_lt_timestamptz", "date_mi", "date_mi_interval", "date_mii", "date_ne", "date_ne_timestamp", "date_ne_timestamptz", "date_out", "date_part", "date_part_year", "date_pl_interval", "date_pli", "date_recv", "date_send", "date_smaller", "date_trunc", "datetime_pl", "datetimetz_pl", "dcbrt", "default", "deferrable", "deflate", "defrag", "degrees", "delete_xid_column", "delta", "delta32k", "dense_rank", "desc", "dexp", "diagonal", "diameter", "disable", "dist_cpoly", "dist_lb", "dist_pb", "dist_pc", "dist_pl", "dist_ppath", "dist_ps", "dist_sb", "dist_sl", "distinct", "dlog1", "dlog10", "do", "dpow", "dround", "dsqrt", "dtrunc", "else", "emptyasnull", "enable", "encode", "encrypt ", "encryption", "end", "eqjoinsel", "eqsel", "erf", "euc_cn_to_mic", "euc_jp_to_mic", "euc_jp_to_sjis", "euc_kr_to_mic", "euc_tw_to_big5", "euc_tw_to_mic", "every", "except", "exp", "explicit", "false", "for", "foreign", "freeze", "from", "full", "geometry_analyze", "geometry_in", "geometry_out", "geometry_recv", "geometry_send", "geometrytype", "get_bit", "get_byte", "getdatabaseencoding", "getdate", "gistbeginscan", "gistbuild", "gistbulkdelete", "gistcostestimate", "gistendscan", "gistgettuple", "gistinsert", "gistmarkpos", "gistrescan", "gistrestrpos", "globaldict256", "globaldict64k", "grant", "group", "gzip", "hash_aclitem", "hashbeginscan", "hashbpchar", "hashbuild", "hashbulkdelete", "hashchar", "hashcostestimate", "hashendscan", "hashgettuple", "hashinet", "hashinsert", "hashint2", "hashint2vector", "hashint4", "hashint8", "hashmacaddr", "hashmarkpos", "hashname", "hashoid", "hashoidvector", "hashrescan", "hashrestrpos", "hashtext", "hashvarlena", "haversine_distance_km", "haversine_distance_km2", "having", "height", "hll_cardinality_16", "hll_cardinality_32", "host", "hostmask", "iclikejoinsel", "iclikesel", "icnlikejoinsel", "icnlikesel", "icregexeqjoinsel", "icregexeqsel", "icregexnejoinsel", "icregexnesel", "identity", "ignore", "ilike", "in", "inet", "inet_client_addr", "inet_client_port", "inet_in", "inet_out", "inet_recv", "inet_send", "inet_server_addr", "inet_server_port", "initcap", "initially", "inner", "int2", "int24div", "int24eq", "int24ge", "int24gt", "int24le", "int24lt", "int24mi", "int24mod", "int24mul", "int24ne", "int24pl", "int28div", "int28eq", "int28ge", "int28gt", "int28le", "int28lt", "int28mi", "int28mul", "int28ne", "int28pl", "int2_accum", "int2_avg_accum", "int2_mul_cash", "int2_sum", "int2abs", "int2and", "int2div", "int2eq", "int2ge", "int2gt", "int2in", "int2larger", "int2le", "int2lt", "int2mi", "int2mod", "int2mul", "int2ne", "int2not", "int2or", "int2out", "int2pl", "int2recv", "int2send", "int2shl", "int2shr", "int2smaller", "int2um", "int2up", "int2vectoreq", "int2vectorout", "int2vectorrecv", "int2vectorsend", "int2xor", "int4", "int42div", "int42eq", "int42ge", "int42gt", "int42le", "int42lt", "int42mi", "int42mod", "int42mul", "int42ne", "int42pl", "int48div", "int48eq", "int48ge", "int48gt", "int48le", "int48lt", "int48mi", "int48mul", "int48ne", "int48pl", "int4_accum", "int4_avg_accum", "int4_mul_cash", "int4_sum", "int4abs", "int4and", "int4div", "int4eq", "int4ge", "int4gt", "int4in", "int4inc", "int4larger", "int4le", "int4lt", "int4mi", "int4mod", "int4mul", "int4ne", "int4not", "int4or", "int4out", "int4pl", "int4recv", "int4send", "int4shl", "int4shr", "int4smaller", "int4um", "int4up", "int4xor", "int8", "int82div", "int82eq", "int82ge", "int82gt", "int82le", "int82lt", "int82mi", "int82mul", "int82ne", "int82pl", "int84div", "int84eq", "int84ge", "int84gt", "int84le", "int84lt", "int84mi", "int84mul", "int84ne", "int84pl", "int8_accum", "int8_avg", "int8_avg_accum", "int8_pl_timestamp", "int8_pl_timestamptz", "int8_sum", "int8abs", "int8and", "int8div", "int8eq", "int8ge", "int8gt", "int8in", "int8inc", "int8larger", "int8le", "int8lt", "int8mi", "int8mod", "int8mul", "int8ne", "int8not", "int8or", "int8out", "int8pl", "int8recv", "int8send", "int8shl", "int8shr", "int8smaller", "int8um", "int8up", "int8xor", "integer_pl_date", "inter_lb", "inter_sb", "inter_sl", "internal_in", "internal_out", "intersect", "interval", "interval_accum", "interval_avg", "interval_cmp", "interval_div", "interval_eq", "interval_ge", "interval_gt", "interval_hash", "interval_in", "interval_larger", "interval_le", "interval_lt", "interval_mi", "interval_mul", "interval_ne", "interval_out", "interval_pl", "interval_pl_date", "interval_pl_time", "interval_pl_timestamp", "interval_pl_timestamptz", "interval_pl_timetz", "interval_recv", "interval_send", "interval_smaller", "interval_um", "intinterval", "into", "ip_aton", "ip_masking", "ip_ntoa", "is", "is_ssl_connection", "is_valid_json", "is_valid_json_array", "isclosed", "isnottrue", "isnull", "iso_to_alt", "iso_to_koi8r", "iso_to_mic", "iso_to_win1251", "isopen", "isparallel", "isperp", "istrue", "isvertical", "join", "json_array_length", "json_extract_array_element_text", "json_extract_path_text", "koi8r_to_alt", "koi8r_to_iso", "koi8r_to_mic", "koi8r_to_win1251", "lag", "language", "language_handler_in", "language_handler_out", "last_day", "last_value", "latin1_to_mic", "latin2_to_mic", "latin2_to_win1250", "latin3_to_mic", "latin4_to_mic", "lead", "leading", "left", "len", "length", "like", "like_escape", "likejoinsel", "likesel", "limit", "line", "line_distance", "line_eq", "line_in", "line_interpt", "line_intersect", "line_out", "line_parallel", "line_perp", "line_recv", "line_send", "line_vertical", "listagg", "listaggdistinct", "ln", "lo_close", "lo_creat", "lo_export", "lo_import", "lo_lseek", "lo_open", "lo_tell", "lo_unlink", "localtime", "localtimestamp", "log", "logistic", "loread", "lower", "lpad", "lseg", "lseg_center", "lseg_distance", "lseg_eq", "lseg_ge", "lseg_gt", "lseg_in", "lseg_interpt", "lseg_intersect", "lseg_le", "lseg_length", "lseg_lt", "lseg_ne", "lseg_out", "lseg_parallel", "lseg_perp", "lseg_recv", "lseg_send", "lseg_vertical", "lun", "luns", "lzo", "lzop", "macaddr", "macaddr_cmp", "macaddr_eq", "macaddr_ge", "macaddr_gt", "macaddr_in", "macaddr_le", "macaddr_lt", "macaddr_ne", "macaddr_out", "macaddr_recv", "macaddr_send", "makeaclitem", "masklen", "max", "md5", "median", "mic_to_alt", "mic_to_ascii", "mic_to_big5", "mic_to_euc_cn", "mic_to_euc_jp", "mic_to_euc_kr", "mic_to_euc_tw", "mic_to_iso", "mic_to_koi8r", "mic_to_latin1", "mic_to_latin2", "mic_to_latin3", "mic_to_latin4", "mic_to_sjis", "mic_to_win1250", "mic_to_win1251", "min", "minus", "mktinterval", "mod", "months_between", "mos_score", "mostly13", "mostly32", "mostly8", "mul_d_interval", "name", "name_pattern_eq", "name_pattern_ge", "name_pattern_gt", "name_pattern_le", "name_pattern_lt", "name_pattern_ne", "nameeq", "namege", "namegt", "nameiclike", "nameicnlike", "nameicregexeq", "nameicregexne", "namein", "namele", "namelike", "namelt", "namene", "namenlike", "nameout", "namerecv", "nameregexeq", "nameregexne", "namesend", "natural", "neqjoinsel", "neqsel", "netmask", "network", "network_cmp", "network_eq", "network_ge", "network_gt", "network_le", "network_lt", "network_ne", "network_sub", "network_subeq", "network_sup", "network_supeq", "new", "next_day", "nextval", "nlikejoinsel", "nlikesel", "node_num", "nonnullvalue", "not", "notlike", "notnull", "now", "npoints", "nth_value", "ntile", "null", "nulls", "nullvalue", "nvl2", "octet_length", "off", "offline", "offset", "oid", "oideq", "oidge", "oidgt", "oidin", "oidlarger", "oidle", "oidlt", "oidne", "oidout", "oidrecv", "oidsend", "oidsmaller", "oidvectoreq", "oidvectorge", "oidvectorgt", "oidvectorle", "oidvectorlt", "oidvectorne", "oidvectorout", "oidvectorrecv", "oidvectorsend", "oidvectortypes", "old", "on", "on_pb", "on_pl", "on_ppath", "on_ps", "on_sb", "on_sl", "only", "opaque_in", "opaque_out", "open", "or", "order", "outer", "overlaps", "parallel", "partition", "path", "path_add", "path_add_pt", "path_center", "path_contain_pt", "path_distance", "path_div_pt", "path_in", "path_inter", "path_length", "path_mul_pt", "path_n_eq", "path_n_ge", "path_n_gt", "path_n_le", "path_n_lt", "path_npoints", "path_out", "path_recv", "path_send", "path_sub_pt", "pclose", "percent", "percent_rank", "percentile_cont", "percentile_disc", "permissions", "pg_backend_pid", "pg_cancel_backend", "pg_char_to_encoding", "pg_client_encoding", "pg_conversion_is_visible", "pg_decode", "pg_encoding_to_char", "pg_get_cols", "pg_get_constraintdef", "pg_get_current_groups", "pg_get_expr", "pg_get_external_columns", "pg_get_external_tables", "pg_get_indexdef", "pg_get_late_binding_view_cols", "pg_get_ruledef", "pg_get_userbyid", "pg_get_viewdef", "pg_last_copy_count", "pg_last_copy_id", "pg_last_query_id", "pg_last_unload_count", "pg_last_unload_id", "pg_lock_status", "pg_opclass_is_visible", "pg_operator_is_visible", "pg_postmaster_start_time", "pg_show_all_settings", "pg_sleep", "pg_start_backup", "pg_stat_get_backend_activity", "pg_stat_get_backend_activity_start", "pg_stat_get_backend_dbid", "pg_stat_get_backend_idset", "pg_stat_get_backend_pid", "pg_stat_get_blocks_hit", "pg_stat_get_db_blocks_hit", "pg_stat_get_db_numbackends", "pg_stat_get_db_xact_commit", "pg_stat_get_db_xact_rollback", "pg_stat_get_numscans", "pg_stat_get_tuples_deleted", "pg_stat_get_tuples_inserted", "pg_stat_get_tuples_returned", "pg_stat_get_tuples_updated", "pg_stat_reset", "pg_stop_backup", "pg_table_is_visible", "pg_tablespace_databases", "pg_terminate_backend", "pg_timezone_abbrevs", "pg_timezone_names", "pg_type_is_visible", "pgdate_part", "pi", "placing", "plpython_call_handler", "plpython_compiler", "point", "point_above", "point_add", "point_below", "point_distance", "point_div", "point_eq", "point_in", "point_mul", "point_ne", "point_out", "point_recv", "point_send", "point_sub", "point_vert", "poly_center", "poly_contain", "poly_contain_pt", "poly_contained", "poly_distance", "poly_in", "poly_npoints", "poly_out", "poly_overlap", "poly_recv", "poly_same", "poly_send", "polygon", "popen", "position", "positionjoinsel", "positionsel", "pow", "power", "primary", "pt_contained_circle", "pt_contained_poly", "qsummary", "quote_ident", "quote_literal", "radians", "radius", "random", "rank", "rankx", "ratio_to_report", "raw", "readratio", "record_in", "record_out", "record_recv", "record_send", "recover", "references", "regclassin", "regclassout", "regclassrecv", "regclasssend", "regexeqjoinsel", "regexeqsel", "regexnejoinsel", "regexnesel", "regexp_count", "regexp_instr", "regexp_replace", "regexp_substr", "regoperatorout", "regoperatorrecv", "regoperatorsend", "regoperout", "regoperrecv", "regopersend", "regprocedurein", "regprocedureout", "regprocedurerecv", "regproceduresend", "regprocin", "regprocout", "regprocrecv", "regprocsend", "regtypein", "regtypeout", "regtyperecv", "regtypesend", "rejectlog", "reltime", "reltimeeq", "reltimege", "reltimegt", "reltimein", "reltimele", "reltimelt", "reltimene", "reltimeout", "reltimerecv", "reltimesend", "relu", "remaining_vacrows", "repeat", "replace", "replicate", "resort", "respect", "restore", "return_approx_percentile", "reverse", "right", "round", "row_number", "rownumber", "rpad", "rt_box_inter", "rt_box_size", "rt_box_union", "rt_poly_inter", "rt_poly_size", "rt_poly_union", "rtbeginscan", "rtbuild", "rtbulkdelete", "rtcostestimate", "rtendscan", "rtgettuple", "rtinsert", "rtmarkpos", "rtrescan", "rtrestrpos", "scalargtjoinsel", "scalargtsel", "scalarltjoinsel", "scalarltsel", "select", "session_user", "set_bit", "set_byte", "set_masklen", "setval", "sig_bucket_3g", "sig_bucket_lte", "sig_score_3g", "sig_score_lte", "sigmoid", "sign", "similar", "similar_escape", "sin", "sjis_to_euc_jp", "sjis_to_mic", "slice_num", "slope", "smgreq", "smgrne", "smgrout", "snapshot ", "some", "sort_avail_mem", "sortbytes", "split_part", "sqrt", "ssl_version", "st_asbinary", "st_asewkb", "st_asewkt", "st_astext", "st_azimuth", "st_contains", "st_dimension", "st_disjoint", "st_distance", "st_dwithin", "st_equals", "st_geometrytype", "st_intersects", "st_isclosed", "st_iscollection", "st_isempty", "st_makeline", "st_makepoint", "st_makepolygon", "st_npoints", "st_numpoints", "st_point", "st_polygon", "st_within", "st_x", "st_xmax", "st_xmin", "st_y", "st_ymax", "st_ymin", "stddev", "stddev_pop", "strpos", "strtol", "substr", "sum", "sysdate", "system", "table", "tablebytes", "tag", "tan", "tdes", "text", "text255", "text32k", "text_ge", "text_gt", "text_larger", "text_le", "text_lt", "text_pattern_eq", "text_pattern_ge", "text_pattern_gt", "text_pattern_le", "text_pattern_lt", "text_pattern_ne", "text_smaller", "textcat", "texteq", "texticlike", "texticnlike", "texticregexeq", "texticregexne", "textin", "textlen", "textlike", "textne", "textnlike", "textout", "textrecv", "textregexeq", "textregexne", "textsend", "then", "tideq", "tidin", "tidout", "tidrecv", "tidsend", "time", "time_cmp", "time_eq", "time_ge", "time_gt", "time_in", "time_larger", "time_le", "time_lt", "time_mi_interval", "time_mi_time", "time_ne", "time_out", "time_pl_interval", "time_recv", "time_send", "time_smaller", "timedate_pl", "timemi", "timenow", "timepl", "timestamp", "timestamp_cmp", "timestamp_cmp_date", "timestamp_cmp_timestamptz", "timestamp_eq", "timestamp_eq_date", "timestamp_eq_timestamptz", "timestamp_ge", "timestamp_ge_date", "timestamp_ge_timestamptz", "timestamp_gt", "timestamp_gt_date", "timestamp_gt_timestamptz", "timestamp_in", "timestamp_larger", "timestamp_le", "timestamp_le_date", "timestamp_le_timestamptz", "timestamp_lt", "timestamp_lt_date", "timestamp_lt_timestamptz", "timestamp_mi", "timestamp_mi_int8", "timestamp_mi_interval", "timestamp_ne", "timestamp_ne_date", "timestamp_ne_timestamptz", "timestamp_out", "timestamp_pl_int8", "timestamp_pl_interval", "timestamp_recv", "timestamp_send", "timestamp_smaller", "timestamptz", "timestamptz_cmp", "timestamptz_cmp_date", "timestamptz_cmp_timestamp", "timestamptz_eq", "timestamptz_eq_date", "timestamptz_eq_timestamp", "timestamptz_ge", "timestamptz_ge_date", "timestamptz_ge_timestamp", "timestamptz_gt", "timestamptz_gt_date", "timestamptz_gt_timestamp", "timestamptz_in", "timestamptz_larger", "timestamptz_le", "timestamptz_le_date", "timestamptz_le_timestamp", "timestamptz_lt", "timestamptz_lt_date", "timestamptz_lt_timestamp", "timestamptz_mi", "timestamptz_mi_int8", "timestamptz_mi_interval", "timestamptz_ne", "timestamptz_ne_date", "timestamptz_ne_timestamp", "timestamptz_out", "timestamptz_pl_int8", "timestamptz_pl_interval", "timestamptz_recv", "timestamptz_send", "timestamptz_smaller", "timetz", "timetz_cmp", "timetz_eq", "timetz_ge", "timetz_gt", "timetz_hash", "timetz_in", "timetz_larger", "timetz_le", "timetz_lt", "timetz_mi_interval", "timetz_ne", "timetz_out", "timetz_pl_interval", "timetz_recv", "timetz_send", "timetz_smaller", "timetzdate_pl", "timezone", "tinterval", "tintervalct", "tintervalend", "tintervaleq", "tintervalge", "tintervalgt", "tintervalin", "tintervalle", "tintervalleneq", "tintervallenge", "tintervallengt", "tintervallenle", "tintervallenlt", "tintervallenne", "tintervallt", "tintervalne", "tintervalout", "tintervalov", "tintervalrecv", "tintervalrel", "tintervalsame", "tintervalsend", "tintervalstart", "to", "to_ascii", "to_char", "to_date", "to_hex", "to_number", "to_timestamp", "tobpchar", "top", "total_num_deleted_vacrows", "total_num_deleted_vacrows_reclaimed", "trailing", "translate", "true", "trunc", "truncatecolumns", "union", "unique", "unknownin", "unknownout", "unknownrecv", "unknownsend", "upper", "user", "using", "vacstate_endrow", "vacstate_last_inserted_row", "var_pop", "varbit", "varbit_in", "varbit_out", "varbit_recv", "varbit_send", "varbitcmp", "varbiteq", "varbitge", "varbitgt", "varbitle", "varbitlt", "varbitne", "varchar", "varcharout", "varcharrecv", "varcharsend", "verbose", "version", "void_in", "void_out", "wallet", "when", "where", "width", "width_bucket", "win1250_to_latin2", "win1250_to_mic", "win1250_to_utf", "win1251_to_alt", "win1251_to_iso", "win1251_to_koi8r", "win1251_to_mic", "win1256_to_utf", "win874_to_utf", "with", "without", "xideq", "xideqint4", "xidin", "xidout", "xidrecv", "xidsend", }
# 231A - Team # http://codeforces.com/problemset/problem/231/A n = int(input()) c = 0 for i in range(n): arr = [x for x in input().split() if int(x) == 1] if len(arr) >= 2: c += 1 print(c)
"""Base class for Node and LinkedLists""" class BaseLinkedList: def __init__(self): pass class BaseNode: def __init__(self, val=0, next_node=None): self._val = val self._next_node = next_node def __repr__(self): return f"Node({self.val, self._next_node})"
description = 'XCCM' group = 'basic' includes = [ # 'source', # 'table', # 'detector', 'virtual_sample_motors', 'virtual_detector_motors', 'virtual_optic_motors', 'virtual_IOcard', 'optic_tool_switch', 'virtual_capillary_motors', 'capillary_selector' ]
""" https://www.hackerrank.com/challenges/binary-search-tree-insertion/problem """ # CODE PROVIDED BY TASK STARTS class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) def preOrder(root): if root is None: return print(root.info, end=" ") preOrder(root.left) preOrder(root.right) class BinarySearchTree: def __init__(self): self.root = None # CODE PROVIDED BY TASK ENDS """ Create tree.insert method """ def insert(self, val): if self.root is None: self.root = Node(val) else: self._insert(self.root, val) return self.root def _insert(self, root, val): if root is None: return if val < root.info: if root.left: self._insert(root.left, val) else: root.left = Node(val) if val > root.info: if root.right: self._insert(root.right, val) else: root.right = Node(val)
"""Triples are a way to define information about a platform/system. This module provides a way to convert a triple string into a well structured object to avoid constant string parsing in starlark code. Triples can be described at the following link: https://clang.llvm.org/docs/CrossCompilation.html#target-triple """ def triple(triple): """Constructs a struct containing each component of the provided triple Args: triple (str): A platform triple. eg: `x86_64-unknown-linux-gnu` Returns: struct: - arch (str): The triple's CPU architecture - vendor (str): The vendor of the system - system (str): The name of the system - abi (str, optional): The abi to use or None if abi does not apply. - triple (str): The original triple """ if triple == "wasm32-wasi": return struct( arch = "wasm32", system = "wasi", vendor = "wasi", abi = None, triple = triple, ) component_parts = triple.split("-") if len(component_parts) < 3: fail("Expected target triple to contain at least three sections separated by '-'") cpu_arch = component_parts[0] vendor = component_parts[1] system = component_parts[2] abi = None if system == "androideabi": system = "android" abi = "eabi" if len(component_parts) == 4: abi = component_parts[3] return struct( arch = cpu_arch, vendor = vendor, system = system, abi = abi, triple = triple, )
# -*- coding:utf-8 -*- """ Description: Script OP Code Usage: from AntShares.Core.Scripts.ScriptOp import ScriptOp """ class ScriptOp(object): # Constants OP_0 = 0x00 # An empty array of bytes is pushed onto the stack. (This is not a no-op: an item is added to the stack.) OP_FALSE = OP_0 OP_PUSHBYTES1 = 0x01 # 0x01-0x4B The next opcode bytes is data to be pushed onto the stack OP_PUSHBYTES75 = 0x4B OP_PUSHDATA1 = 0x4C # The next byte contains the number of bytes to be pushed onto the stack. OP_PUSHDATA2 = 0x4D # The next two bytes contain the number of bytes to be pushed onto the stack. OP_PUSHDATA4 = 0x4E # The next four bytes contain the number of bytes to be pushed onto the stack. OP_1NEGATE = 0x4F # The number -1 is pushed onto the stack. #OP_RESERVED = 0x50 # Transaction is invalid unless occuring in an unexecuted OP_IF branch OP_1 = 0x51 # The number 1 is pushed onto the stack. OP_TRUE = OP_1 OP_2 = 0x52 # The number 2 is pushed onto the stack. OP_3 = 0x53 # The number 3 is pushed onto the stack. OP_4 = 0x54 # The number 4 is pushed onto the stack. OP_5 = 0x55 # The number 5 is pushed onto the stack. OP_6 = 0x56 # The number 6 is pushed onto the stack. OP_7 = 0x57 # The number 7 is pushed onto the stack. OP_8 = 0x58 # The number 8 is pushed onto the stack. OP_9 = 0x59 # The number 9 is pushed onto the stack. OP_10 = 0x5A # The number 10 is pushed onto the stack. OP_11 = 0x5B # The number 11 is pushed onto the stack. OP_12 = 0x5C # The number 12 is pushed onto the stack. OP_13 = 0x5D # The number 13 is pushed onto the stack. OP_14 = 0x5E # The number 14 is pushed onto the stack. OP_15 = 0x5F # The number 15 is pushed onto the stack. OP_16 = 0x60 # The number 16 is pushed onto the stack. # Flow control OP_NOP = 0x61 # Does nothing. OP_JMP = 0x62 OP_JMPIF = 0x63 OP_JMPIFNOT = 0x64 OP_CALL = 0x65 OP_RET = 0x66 OP_APPCALL = 0x67 OP_SYSCALL = 0x68 OP_HALTIFNOT = 0x69 OP_HALT = 0x6A # Stack OP_TOALTSTACK = 0x6B # Puts the input onto the top of the alt stack. Removes it from the main stack. OP_FROMALTSTACK = 0x6C # Puts the input onto the top of the main stack. Removes it from the alt stack. OP_XDROP = 0x6D #OP_2DUP = 0x6E # Duplicates the top two stack items. #OP_3DUP = 0x6F # Duplicates the top three stack items. #OP_2OVER = 0x70 # Copies the pair of items two spaces back in the stack to the front. #OP_2ROT = 0x71 # The fifth and sixth items back are moved to the top of the stack. OP_XSWAP = 0x72 OP_XTUCK = 0x73 OP_DEPTH = 0x74 # Puts the number of stack items onto the stack. OP_DROP = 0x75 # Removes the top stack item. OP_DUP = 0x76 # Duplicates the top stack item. OP_NIP = 0x77 # Removes the second-to-top stack item. OP_OVER = 0x78 # Copies the second-to-top stack item to the top. OP_PICK = 0x79 # The item n back in the stack is copied to the top. OP_ROLL = 0x7A # The item n back in the stack is moved to the top. OP_ROT = 0x7B # The top three items on the stack are rotated to the left. OP_SWAP = 0x7C # The top two items on the stack are swapped. OP_TUCK = 0x7D # The item at the top of the stack is copied and inserted before the second-to-top item. # Splice OP_CAT = 0x7E # Concatenates two strings. OP_SUBSTR = 0x7F # Returns a section of a string. OP_LEFT = 0x80 # Keeps only characters left of the specified point in a string. OP_RIGHT = 0x81 # Keeps only characters right of the specified point in a string. OP_SIZE = 0x82 # Returns the length of the input string. # Bitwise logic OP_INVERT = 0x83 # Flips all of the bits in the input. OP_AND = 0x84 # Boolean and between each bit in the inputs. OP_OR = 0x85 # Boolean or between each bit in the inputs. OP_XOR = 0x86 # Boolean exclusive or between each bit in the inputs. OP_EQUAL = 0x87 # Returns 1 if the inputs are exactly equal 0 otherwise. #OP_EQUALVERIFY = 0x88 # Same as OP_EQUAL, but runs OP_VERIFY afterward. #OP_RESERVED1 = 0x89 # Transaction is invalid unless occuring in an unexecuted OP_IF branch #OP_RESERVED2 = 0x8A # Transaction is invalid unless occuring in an unexecuted OP_IF branch # Arithmetic # Note: Arithmetic inputs are limited to signed 32-bit integers, but may overflow their output. OP_1ADD = 0x8B # 1 is added to the input. OP_1SUB = 0x8C # 1 is subtracted from the input. OP_2MUL = 0x8D # The input is multiplied by 2. OP_2DIV = 0x8E # The input is divided by 2. OP_NEGATE = 0x8F # The sign of the input is flipped. OP_ABS = 0x90 # The input is made positive. OP_NOT = 0x91 # If the input is 0 or 1, it is flipped. Otherwise the output will be 0. OP_0NOTEQUAL = 0x92 # Returns 0 if the input is 0. 1 otherwise. OP_ADD = 0x93 # a is added to b. OP_SUB = 0x94 # b is subtracted from a. OP_MUL = 0x95 # a is multiplied by b. OP_DIV = 0x96 # a is divided by b. OP_MOD = 0x97 # Returns the remainder after dividing a by b. OP_LSHIFT = 0x98 # Shifts a left b bits, preserving sign. OP_RSHIFT = 0x99 # Shifts a right b bits, preserving sign. OP_BOOLAND = 0x9A # If both a and b are not 0, the output is 1. Otherwise 0. OP_BOOLOR = 0x9B # If a or b is not 0, the output is 1. Otherwise 0. OP_NUMEQUAL = 0x9C # Returns 1 if the numbers are equal, 0 otherwise. #OP_NUMEQUALVERIFY = 0x9D # Same as OP_NUMEQUAL, but runs OP_VERIFY afterward. OP_NUMNOTEQUAL = 0x9E # Returns 1 if the numbers are not equal, 0 otherwise. OP_LESSTHAN = 0x9F # Returns 1 if a is less than b, 0 otherwise. OP_GREATERTHAN = 0xA0 # Returns 1 if a is greater than b, 0 otherwise. OP_LESSTHANOREQUAL = 0xA1 # Returns 1 if a is less than or equal to b, 0 otherwise. OP_GREATERTHANOREQUAL = 0xA2 # Returns 1 if a is greater than or equal to b, 0 otherwise. OP_MIN = 0xA3 # Returns the smaller of a and b. OP_MAX = 0xA4 # Returns the larger of a and b. OP_WITHIN = 0xA5 # Returns 1 if x is within the specified range (left-inclusive), 0 otherwise. # Crypto #OP_RIPEMD160 = 0xA6 # The input is hashed using RIPEMD-160. OP_SHA1 = 0xA7 # The input is hashed using SHA-1. OP_SHA256 = 0xA8 # The input is hashed using SHA-256. OP_HASH160 = 0xA9 OP_HASH256 = 0xAA #OP_CODESEPARATOR = 0xAB # All of the signature checking words will only match signatures to the data after the most recently-executed OP_CODESEPARATOR. OP_CHECKSIG = 0xAC # The entire transaction's outputs, inputs, and script (from the most recently-executed OP_CODESEPARATOR to the end) are hashed. The signature used by OP_CHECKSIG must be a valid signature for this hash and public key. If it is, 1 is returned, 0 otherwise. #OP_CHECKSIGVERIFY = 0xAD # Same as OP_CHECKSIG, but OP_VERIFY is executed afterward. OP_CHECKMULTISIG = 0xAE # For each signature and public key pair, OP_CHECKSIG is executed. If more public keys than signatures are listed, some key/sig pairs can fail. All signatures need to match a public key. If all signatures are valid, 1 is returned, 0 otherwise. Due to a bug, one extra unused value is removed from the stack. #OP_CHECKMULTISIGVERIFY = 0xAF, # Same as OP_CHECKMULTISIG, but OP_VERIFY is executed afterward.
def triplewise(it): try: a, b = next(it), next(it) except StopIteration: return for c in it: yield a, b, c a, b = b, c def inc_count(values): last = None count = 0 for v in values: if last is not None and v > last: count += 1 last = v return count def main(): nums = [int(line) for line in open("input.txt").readlines()] sums = [sum(triple) for triple in triplewise(iter(nums))] print(inc_count(nums)) # part 1 print(inc_count(sums)) # part 2 if __name__ == "__main__": main()
definitions = { "StringArray": { "type": "array", "items": { "type": "string", } }, "AudioEncoding": { "type": "string", "enum": ["LINEAR16", "ALAW", "MULAW", "LINEAR32F", "RAW_OPUS", "MPEG_AUDIO"] }, "VoiceActivityDetectionConfig": { "type": "object", "properties": { "min_speech_duration": {"type": "number"}, "max_speech_duration": {"type": "number"}, "silence_duration_threshold": {"type": "number"}, "silence_prob_threshold": {"type": "number"}, "aggressiveness": {"type": "number"}, } }, "SpeechContext": { "type": "object", "properties": { "phrases": {"$ref": "#definitions/StringArray"}, "words": {"$ref": "#definitions/StringArray"} } }, "InterimResultsConfig": { "type": "object", "properties": { "enable_interim_results": {"type": "boolean"}, "interval": {"type": "number"} } } } recognition_config_schema = { "type": "object", "definitions": definitions, "properties": { "encoding": {"$ref": "#/definitions/AudioEncoding"}, "sample_rate_hertz": {"type": "number"}, "language_code": {"type": "string"}, "max_alternatives": {"type": "number"}, "speech_contexts": { "type": "array", "items": { "$ref": "#/definitions/SpeechContext" } }, "enable_automatic_punctuation": {"type": "boolean"}, "enable_denormalization": {"type": "boolean"}, "enable_rescoring": {"type": "boolean"}, "model": {"type": "string"}, "num_channels": {"type": "number"}, "do_not_perform_vad": {"type": "boolean"}, "vad_config": {"$ref": "#/definitions/VoiceActivityDetectionConfig"}, "profanity_filter": {"type": "boolean"} }, "required": [ "sample_rate_hertz", "num_channels", "encoding", ], "additionalProperties": False } streaming_recognition_config_schema = { "type": "object", "definitions": definitions, "properties": { "config": recognition_config_schema, "single_utterance": {"type": "boolean"}, "interim_results_config": {"$ref": "#/definitions/InterimResultsConfig"} }, "additionalProperties": False } long_running_recognition_config_schema = { "type": "object", "definitions": definitions, "properties": { "config": recognition_config_schema, "group": {"type": "string"} }, "additionalProperties": False }