content
stringlengths
7
1.05M
def gen_counter(cnt=None): res = 0 while True: yield res res += 1 if cnt is None else cnt if __name__=='__main__': cnt = gen_counter() print(next(cnt)) print(next(cnt)) print(next(cnt)) print(next(cnt)) print(next(cnt)) cnt = gen_counter(5) print(next(cnt)) print(next(cnt)) print(next(cnt)) print(next(cnt)) print(next(cnt))
# # PySNMP MIB module NBS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:07:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Unsigned32, enterprises, iso, NotificationType, TimeTicks, Counter32, MibIdentifier, Bits, Counter64, Gauge32, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Unsigned32", "enterprises", "iso", "NotificationType", "TimeTicks", "Counter32", "MibIdentifier", "Bits", "Counter64", "Gauge32", "ModuleIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") nbsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 629, 250)) if mibBuilder.loadTexts: nbsMib.setLastUpdated('201309170000Z') if mibBuilder.loadTexts: nbsMib.setOrganization('NBS') nbs = ObjectIdentity((1, 3, 6, 1, 4, 1, 629)) if mibBuilder.loadTexts: nbs.setStatus('current') class Unsigned16(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 65535) class Unsigned64(TextualConvention, Counter64): status = 'current' class WritableU64(TextualConvention, OctetString): status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8) fixedLength = 8 class NbsTcTemperature(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(-2147483648, 1000) class NbsTcMilliVolt(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(-1, 1000000) class NbsTcMilliAmp(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(-1, 1000000) class NbsTcMicroAmp(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(-1, 2147483647) class NbsTcMilliDb(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(-2147483648, 100000) class NbsTcMilliWatts(TextualConvention, Integer32): status = 'current' class NbsTcMHz(TextualConvention, Unsigned32): status = 'current' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(1, 4294967295) class NbsTcStatusSimple(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("notSupported", 1), ("bad", 2), ("good", 3), ("notInstalled", 4)) class NbsTcStatusLevel(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6)) namedValues = NamedValues(("notSupported", 1), ("statusLowError", 2), ("statusLowWarning", 3), ("statusGood", 4), ("statusHighWarning", 5), ("statusHighError", 6)) class NbsTcPartIndex(TextualConvention, Unsigned32): status = 'current' class NbsTcStagingCommit(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("notSupported", 1), ("supported", 2), ("revertToCommitted", 3), ("apply", 4)) mibBuilder.exportSymbols("NBS-MIB", NbsTcStatusLevel=NbsTcStatusLevel, NbsTcPartIndex=NbsTcPartIndex, NbsTcStagingCommit=NbsTcStagingCommit, NbsTcMilliVolt=NbsTcMilliVolt, NbsTcTemperature=NbsTcTemperature, NbsTcMilliWatts=NbsTcMilliWatts, WritableU64=WritableU64, NbsTcMHz=NbsTcMHz, NbsTcStatusSimple=NbsTcStatusSimple, Unsigned16=Unsigned16, nbsMib=nbsMib, PYSNMP_MODULE_ID=nbsMib, nbs=nbs, NbsTcMilliAmp=NbsTcMilliAmp, NbsTcMicroAmp=NbsTcMicroAmp, Unsigned64=Unsigned64, NbsTcMilliDb=NbsTcMilliDb)
""" Date Created: 2018-03-08 Date Modified: 2018-03-08 Version: 1 Contract Hash: 1aa965c53c373ef9d3be065bdb36b234cdcab66a Available on NEO TestNet: False Available on CoZ TestNet: False Available on MainNet: False Example: Test Invoke: build /path/to/add.py test 0202 02 False False 2 5 Expected Result: 2 Operation Count: 51 GAS Consumption: 0.045 """ def Main(a, b): """ :param a: First input number of concern :param b: Second input number of concern :type a: int :type b: int :return: The smallest value of the 2 input numbers :rtype: int """ result = min(a, b) return result
def test_calculator_add_returns_correct_result(): result = calc_add(2,2) assert result == 4 # def calc_add(x,y): # pass # return x+y # if isinstance(x, number_types) and isinstance(y, number_types): # return x + y # else: # raise ValueError("Non-numeric input given") # def test_calculator_returns_error_message_if_both_args_not_numbers(): # try: # calc_add("two", "three") # except ValueError: # print("Exception caught") # assert True, "Fail: ValueError exception not caught" # except: # assert False, "Fail: Exception other than ValueError caught" # else: # assert False, "Fail: No exception caught" # def test_calculator_returns_error_message_if_both_args_not_numbers(): # with pytest.raises(ValueError): # calc_add("two", "three") # def test_calculator_returns_error_message_if_x_arg_not_number(): # with pytest.raises(ValueError): # calc_add("two", 3) # def test_calculator_returns_error_message_if_y_arg_not_number( ): # with pytest.raises(ValueError): # calc_add(2, "three")
def getGroupCount(line): #print("Line "+line) curSet = set(()) for curChar in line: curSet.add(curChar) #print("Set: "+str(curSet)) return len(curSet) filename = "inputs\\2020\\input-day6.txt" with open(filename) as f: lines = f.readlines() group = "" sum = 0 for line in lines: if len(line.strip()) == 0: sum += getGroupCount(group.strip()) group = "" else: group += line.strip() sum += getGroupCount(group.strip()) print("Sum: "+str(sum))
def up_array(arr): if not arr: return None else: string = '' for item in arr: if not str(item).isdigit() or item > 9: return None else: string += str(item) total = [] for char in str(int(string)+1): total.append(int(char)) return total
# -*- coding: utf-8 -*- """ Created on Thu Nov 12 10:39:07 2020 @author: BK """
# ## https://leetcode.com/problems/longest-substring-without-repeating-characters/ # class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if s is None: raise ValueError('Parameter should be a String.') if len(s) < 2: return len(s) start = last_max_len = 0 for idx in range(len(s) - 1): if s[idx + 1] in s[start : idx + 1]: if idx - start + 1 > last_max_len: last_max_len = idx - start + 1 start = start + s[start : idx + 1].index(s[idx + 1]) + 1 final_seq_len = len(s) - start return final_seq_len if final_seq_len > last_max_len else last_max_len s = Solution(); s.lengthOfLongestSubstring('dvdf')
#@title Biblioteca de funções execute este trecho após o cabeçalho # -*- coding: utf-8 -*- def login_Twitter(chave_consumidor, segredo_consumidor, token_acesso, token_acesso_segredo): #gerando objeto de autenticação autenticacao = tw.OAuthHandler(chave_consumidor, segredo_consumidor) #gerando tokens autenticacao.set_access_token(token_acesso, token_acesso_segredo) #Conectando ao twitter return tw.API(autenticacao, wait_on_rate_limit=True) def search_tweets(twitter, term, startDay, finalDay, maxItens): tweets = tw.Cursor(twitter.search, q=term, lang='pt', since=startDay, until=finalDay).items(maxItens) tweetsList = [tweet.text for tweet in tweets] return tweetsList def extract_nouns_list(tweets, out): counter = 0 leitorMAX = int(len(tweets)) #deixa o texto todo em mundo e particiona ele em lista de palavras words_in_tweet = [tweet.lower().split() for tweet in tweets] listNouns = ['NOUN'] nouns_in_tweet = [] #elimina pontuações e extrai apenas os substantivos for tweet in words_in_tweet: doc = sp(str(tweet)) tweet_no_punct = [ token.orth_ for token in doc if not token.is_punct and token.pos_ in listNouns] nouns_in_tweet.append(tweet_no_punct) counter+=1 out.update(progress('Extraindo substantivos...', counter, leitorMAX)) return nouns_in_tweet def count_words_frequency(wordsList): bagOfWords = list(itertools.chain(*wordsList)) #Create counter words_frequency = collections.Counter(bagOfWords) return words_frequency def plot_popular_words(wordsList, itensAmount, title): popular_words = pd.DataFrame(wordsList.most_common(itensAmount), columns=['words', 'frequency']) fig, ax = plt.subplots(figsize=(8, 8)) # Plot horizontal bar graph popular_words.sort_values(by='frequency').plot.barh(x='words', y='frequency', ax=ax, color="purple") ax.set_title(title) plt.show() def extract_named_entities(tweetsList, out): counter = 0 leitorMAX = int(len(tweetsList)) namedEntities = [] for tweet in tweetsList: doc = sp(str(tweet)) tweetEntities = [str(entity) for entity in doc.ents] namedEntities.append(tweetEntities) counter+=1 out.update(progress('Identificando entidades...', counter, leitorMAX)) return namedEntities def process_tweet_querie(term, startDay, finalDay, podium): API_KEY = 'BP7tNDh2UPbELpR1sQyiRtY6G' API_SECRET_KEY = 'XIjfoFhscRr4LqU7sheOYZ6DCOQXtBSZF1AEtaGGbrfVYndi20' token_acesso = '129916291-pUvGqrqwofqVHsNgvRIg7UkWR3yQW4Bdn54h5oHW' token_acesso_segredo = 'SzOnefG2Ss7at73XxFKmDYkJ4mr0bd5WHbWsn2PnWiHum' BEARER_TOKEN = 'AAAAAAAAAAAAAAAAAAAAAM0iQQEAAAAAZk1UJWFH97BC%2FlG8gJuHyAVe40c%3DK0kchtFbdTtVeG6Di8PvNYJuRQ6wwRiVkkfUQv11sCt3JCaA1w' counter = 1 leitorMAX = 8 out = display(progress('Conectando ao Twitter', counter, leitorMAX), display_id=True) outTask = display(progress('...', 0, 1), display_id=True) twitterConn = login_Twitter(API_KEY, API_SECRET_KEY, token_acesso, token_acesso_segredo) counter+=1 out.update(progress('Coleta de tweets...', counter, leitorMAX)) tweetsList = search_tweets(twitterConn, term, startDay, finalDay, 2000) title = (f'Pesquisa de Tweets por Termos\n' f'Termos usados: {term}\n' f'Data de início: {startDay} | Data final: {finalDay}\n' f'{len(tweetsList)} tweets foram coletados\n' f'As {podium} mais usadas no período') counter+=1 out.update(progress('Extração de Substantivos', counter, leitorMAX)) nounsInTweets = extract_nouns_list(tweetsList, outTask) counter+=1 out.update(progress('Cálculo de Frequência de Substantivos', counter, leitorMAX)) nounsFrequency = count_words_frequency(nounsInTweets) counter+=1 out.update(progress('Identificação de entidades', counter, leitorMAX)) entitiesInTweets = extract_named_entities(tweetsList, outTask) counter+=1 out.update(progress('Cálculo de Frequência de Entidades', counter, leitorMAX)) entitiesFrequency = count_words_frequency(entitiesInTweets) title = (f'Pesquisa de Tweets por Termos\n' f'Termos usados: {term}\n' f'Data de início: {startDay} | Data final: {finalDay}\n' f'{len(tweetsList)} tweets foram coletados\n' f'Os {podium} termos mais usadas no período') counter+=1 out.update(progress('Plotagem de frequência de substantivos', counter, leitorMAX)) plot_popular_words(nounsFrequency, podium, title) title = (f'Pesquisa de Tweets por Termos\n' f'Termos usados: {term}\n' f'Data de início: {startDay} | Data final: {finalDay}\n' f'{len(tweetsList)} tweets foram coletados\n' f'As {podium} entidades mais mencionadas no período') counter+=1 out.update(progress('Plotagem de frequência de entidades', counter, leitorMAX)) plot_popular_words(entitiesFrequency, podium, title) #função para desenhar a barra de progresso def progress(message, value, max=100): progresso = ((value * 100) / max) return HTML(""" <span> {message} </span> <br> <progress value='{value}' max='{max}', style='width: 99%' > {value} </progress> <span> {value} | {max} :: {progresso} % :: </span> """.format(value=value, max=max, progresso=progresso, message=message))
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direction_same, obj[16]: Distance # {"feature": "Occupation", "instances": 85, "metric_value": 0.9879, "depth": 1} if obj[10]<=19: # {"feature": "Education", "instances": 80, "metric_value": 0.971, "depth": 2} if obj[9]<=2: # {"feature": "Restaurant20to50", "instances": 60, "metric_value": 0.9183, "depth": 3} if obj[14]<=2.0: # {"feature": "Maritalstatus", "instances": 56, "metric_value": 0.9403, "depth": 4} if obj[7]>0: # {"feature": "Age", "instances": 37, "metric_value": 0.9868, "depth": 5} if obj[6]<=4: # {"feature": "Time", "instances": 33, "metric_value": 0.9993, "depth": 6} if obj[2]<=3: # {"feature": "Bar", "instances": 25, "metric_value": 0.9896, "depth": 7} if obj[12]>0.0: # {"feature": "Coupon", "instances": 14, "metric_value": 0.8631, "depth": 8} if obj[3]>0: # {"feature": "Income", "instances": 13, "metric_value": 0.7793, "depth": 9} if obj[11]<=3: # {"feature": "Distance", "instances": 10, "metric_value": 0.8813, "depth": 10} if obj[16]<=2: # {"feature": "Coffeehouse", "instances": 8, "metric_value": 0.9544, "depth": 11} if obj[13]>1.0: # {"feature": "Coupon_validity", "instances": 5, "metric_value": 0.7219, "depth": 12} if obj[4]>0: return 'False' elif obj[4]<=0: # {"feature": "Passanger", "instances": 2, "metric_value": 1.0, "depth": 13} if obj[0]<=1: # {"feature": "Weather", "instances": 2, "metric_value": 1.0, "depth": 14} if obj[1]<=0: # {"feature": "Gender", "instances": 2, "metric_value": 1.0, "depth": 15} if obj[5]<=0: # {"feature": "Children", "instances": 2, "metric_value": 1.0, "depth": 16} if obj[8]<=0: # {"feature": "Direction_same", "instances": 2, "metric_value": 1.0, "depth": 17} if obj[15]<=0: return 'True' else: return 'True' else: return 'True' else: return 'True' else: return 'True' else: return 'True' else: return 'True' elif obj[13]<=1.0: # {"feature": "Gender", "instances": 3, "metric_value": 0.9183, "depth": 12} if obj[5]<=0: return 'True' elif obj[5]>0: return 'False' else: return 'False' else: return 'True' elif obj[16]>2: return 'False' else: return 'False' elif obj[11]>3: return 'False' else: return 'False' elif obj[3]<=0: return 'True' else: return 'True' elif obj[12]<=0.0: # {"feature": "Income", "instances": 11, "metric_value": 0.9457, "depth": 8} if obj[11]<=6: # {"feature": "Distance", "instances": 6, "metric_value": 0.9183, "depth": 9} if obj[16]<=1: return 'False' elif obj[16]>1: # {"feature": "Coupon", "instances": 3, "metric_value": 0.9183, "depth": 10} if obj[3]>0: return 'True' elif obj[3]<=0: return 'False' else: return 'False' else: return 'True' elif obj[11]>6: return 'True' else: return 'True' else: return 'True' elif obj[2]>3: # {"feature": "Coffeehouse", "instances": 8, "metric_value": 0.8113, "depth": 7} if obj[13]>0.0: return 'True' elif obj[13]<=0.0: # {"feature": "Passanger", "instances": 3, "metric_value": 0.9183, "depth": 8} if obj[0]<=1: return 'False' elif obj[0]>1: return 'True' else: return 'True' else: return 'False' else: return 'True' elif obj[6]>4: return 'True' else: return 'True' elif obj[7]<=0: # {"feature": "Gender", "instances": 19, "metric_value": 0.7425, "depth": 5} if obj[5]>0: # {"feature": "Coffeehouse", "instances": 11, "metric_value": 0.9457, "depth": 6} if obj[13]<=1.0: # {"feature": "Distance", "instances": 6, "metric_value": 0.9183, "depth": 7} if obj[16]<=2: # {"feature": "Passanger", "instances": 5, "metric_value": 0.7219, "depth": 8} if obj[0]<=1: return 'False' elif obj[0]>1: # {"feature": "Time", "instances": 2, "metric_value": 1.0, "depth": 9} if obj[2]>2: return 'False' elif obj[2]<=2: return 'True' else: return 'True' else: return 'False' elif obj[16]>2: return 'True' else: return 'True' elif obj[13]>1.0: return 'True' else: return 'True' elif obj[5]<=0: return 'True' else: return 'True' else: return 'True' elif obj[14]>2.0: return 'True' else: return 'True' elif obj[9]>2: # {"feature": "Coffeehouse", "instances": 20, "metric_value": 0.971, "depth": 3} if obj[13]>1.0: # {"feature": "Gender", "instances": 15, "metric_value": 0.9968, "depth": 4} if obj[5]>0: # {"feature": "Income", "instances": 11, "metric_value": 0.9457, "depth": 5} if obj[11]<=5: # {"feature": "Direction_same", "instances": 9, "metric_value": 0.7642, "depth": 6} if obj[15]<=0: # {"feature": "Distance", "instances": 8, "metric_value": 0.5436, "depth": 7} if obj[16]>1: return 'False' elif obj[16]<=1: return 'True' else: return 'True' elif obj[15]>0: return 'True' else: return 'True' elif obj[11]>5: return 'True' else: return 'True' elif obj[5]<=0: return 'True' else: return 'True' elif obj[13]<=1.0: return 'False' else: return 'False' else: return 'False' elif obj[10]>19: return 'False' else: return 'False'
###Database #database typy Option:(mongodb, mysql, redis) DB_TYPE = 'mongdb' #database ip DB_HOST = 'localhost' #database port DB_PORT = '1' #username #USERNAME = None #passward #PASSWARD = None #database name DB_DBNAME = 'quickspy' ###
x = 1 while True: x = input("Number:\n> ") if int(x) == 0: break
#!/usr/bin/env python # coding: utf-8 # # *section 4: Strings* # # ### writer : Faranak Alikhah 1954128 # ### 12.Check Subset: # # # In[ ]: num_testCase=int(input()) for i in range(num_testCase): num_testCase1=int(input()) a=set(input().split()) num_testCase2=int(input()) b=set(input().split()) print(a.issubset(b)) #
# Exercise 105 - Parsing and Generating Dictionaries '''Write a program that has a grades() function that can receive multiple grades from students and will return a dictionary with the following information: - Number of notes - The highest grade - The lowest grade - The class average - The situation (optional) Also add the docstrings of this function for query by the developer.'''
# Test case for PR#183; print of a recursive PyStringMap causes a JVM stack # overflow. g = globals() print(g)
########################################################################### # # Copyright 2019 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################### CUSTOM_DIMENSION_SCHEMA = [{ 'name': 'accountName', 'type': 'STRING' }, { 'name': 'accountId', 'type': 'STRING' }, { 'name': 'propertyName', 'type': 'STRING' }, { 'name': 'propertyId', 'type': 'STRING' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'index', 'type': 'STRING' }, { 'name': 'scope', 'type': 'STRING' }, { 'name': 'active', 'type': 'STRING' }, { 'name': 'created', 'type': 'TIMESTAMP' }, { 'name': 'updated', 'type': 'TIMESTAMP' }, { 'name': 'date', 'type': 'DATE' }, { 'name': 'selfLink', 'type': 'STRING' }] CUSTOM_METRIC_SCHEMA = [{ 'name': 'accountName', 'type': 'STRING' }, { 'name': 'accountId', 'type': 'STRING' }, { 'name': 'propertyName', 'type': 'STRING' }, { 'name': 'propertyId', 'type': 'STRING' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'index', 'type': 'STRING' }, { 'name': 'scope', 'type': 'STRING' }, { 'name': 'active', 'type': 'STRING' }, { 'name': 'created', 'type': 'TIMESTAMP' }, { 'name': 'updated', 'type': 'TIMESTAMP' }, { 'name': 'date', 'type': 'DATE' }, { 'name': 'selfLink', 'type': 'STRING' }, { 'name': 'type', 'type': 'STRING' }, { 'name': 'min_value', 'type': 'INTEGER' }, { 'name': 'max_value', 'type': 'INTEGER' }] VIEW_SCHEMA = [{ 'name': 'date', 'type': 'DATE' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'selfLink', 'type': 'STRING' }, { 'name': 'accountId', 'type': 'STRING' }, { 'name': 'webPropertyId', 'type': 'STRING' }, { 'name': 'accountName', 'type': 'STRING' }, { 'name': 'webPropertyName', 'type': 'STRING' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'currency', 'type': 'STRING' }, { 'name': 'timezone', 'type': 'STRING' }, { 'name': 'websiteUrl', 'type': 'STRING' }, { 'name': 'defaultPage', 'type': 'STRING' }, { 'name': 'excludeQueryParameters', 'type': 'STRING' }, { 'name': 'siteSearchQueryParameters', 'type': 'STRING' }, { 'name': 'stripSiteSearchQueryParameters', 'type': 'BOOLEAN' }, { 'name': 'siteSearchCategoryParameters', 'type': 'STRING' }, { 'name': 'stripSiteSearchCategoryParameters', 'type': 'BOOLEAN' }, { 'name': 'type', 'type': 'STRING' }, { 'name': 'created', 'type': 'TIMESTAMP' }, { 'name': 'updated', 'type': 'TIMESTAMP' }, { 'name': 'eCommerceTracking', 'type': 'BOOLEAN' }, { 'name': 'enhancedECommerceTracking', 'type': 'BOOLEAN' }, { 'name': 'botFilteringEnabled', 'type': 'BOOLEAN' }, { 'name': 'starred', 'type': 'BOOLEAN' }] GOAL_SCHEMA = [{ 'name': 'date', 'type': 'DATE' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'accountId', 'type': 'STRING' }, { 'name': 'webPropertyId', 'type': 'STRING' }, { 'name': 'internalWebPropertyId', 'type': 'STRING' }, { 'name': 'profileId', 'type': 'STRING' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'accountName', 'type': 'STRING' }, { 'name': 'webPropertyName', 'type': 'STRING' }, { 'name': 'profileName', 'type': 'STRING' }, { 'name': 'value', 'type': 'FLOAT' }, { 'name': 'active', 'type': 'BOOLEAN' }, { 'name': 'type', 'type': 'STRING' }, { 'name': 'created', 'type': 'TIMESTAMP' }, { 'name': 'updated', 'type': 'TIMESTAMP' }, { 'name': 'urlDestinationDetails', 'type': 'RECORD', 'fields': [{ 'name': 'url', 'type': 'STRING' }, { 'name': 'caseSensitive', 'type': 'BOOLEAN' }, { 'name': 'matchType', 'type': 'STRING' }, { 'name': 'firstStepRequired', 'type': 'BOOLEAN' }, { 'name': 'steps', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{ 'name': 'number', 'type': 'INTEGER' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'url', 'type': 'STRING' }] }] }, { 'name': 'visitTimeOnSiteDetails', 'type': 'RECORD', 'fields': [{ 'name': 'comparisonType', 'type': 'STRING' }, { 'name': 'comparisonValue', 'type': 'STRING' }] }, { 'name': 'visitNumPagesDetails', 'type': 'RECORD', 'fields': [{ 'name': 'comparisonType', 'type': 'STRING' }, { 'name': 'comparisonValue', 'type': 'STRING' }] }, { 'name': 'eventDetails', 'type': 'RECORD', 'fields': [{ 'name': 'useEventValue', 'type': 'BOOLEAN' }, { 'name': 'eventConditions', 'mode': 'REPEATED', 'type': 'RECORD', 'fields': [{ 'name': 'type', 'type': 'STRING' }, { 'name': 'matchType', 'type': 'STRING' }, { 'name': 'expression', 'type': 'STRING' }, { 'name': 'comparisonType', 'type': 'STRING' }, { 'name': 'comparisonValue', 'type': 'STRING' }] }] }] GOOGLE_ADS_LINK_SCHEMA = [{ 'name': 'date', 'type': 'DATE' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'kind', 'type': 'STRING' }, { 'name': 'selfLink', 'type': 'STRING' }, { 'name': 'entity', 'type': 'RECORD', 'fields': [{ 'name': 'webPropertyRef', 'type': 'RECORD', 'fields': [{ 'name': 'id', 'type': 'STRING' }, { 'name': 'kind', 'type': 'STRING' }, { 'name': 'href', 'type': 'STRING' }, { 'name': 'accountId', 'type': 'STRING' }, { 'name': 'internalWebPropertyId', 'type': 'STRING' }, { 'name': 'name', 'type': 'STRING' }] }] }, { 'name': 'adWordsAccounts', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{ 'name': 'kind', 'type': 'STRING' }, { 'name': 'customerId', 'type': 'STRING' }, { 'name': 'autoTaggingEnabled', 'type': 'BOOLEAN' }] }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'profileIds', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{ 'name': 'id', 'type': 'STRING' }] }] REMARKETING_AUDIENCE_SCHEMA = [{ 'name': 'date', 'type': 'DATE' }, { 'name': 'kind', 'type': 'STRING' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'accountId', 'type': 'STRING' }, { 'name': 'webPropertyId', 'type': 'STRING' }, { 'name': 'webPropertyName', 'type': 'STRING' }, { 'name': 'accountName', 'type': 'STRING' }, { 'name': 'internalWebPropertyId', 'type': 'STRING' }, { 'name': 'created', 'type': 'TIMESTAMP' }, { 'name': 'updated', 'type': 'TIMESTAMP' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'description', 'type': 'STRING' }, { 'name': 'linkedAdAccounts', 'mode': 'REPEATED', 'type': 'RECORD', 'fields': [{ 'name': 'kind', 'type': 'STRING' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'accountId', 'type': 'STRING' }, { 'name': 'webPropertyId', 'type': 'STRING' }, { 'name': 'internalWebPropertyId', 'type': 'STRING' }, { 'name': 'remarketingAudienceId', 'type': 'STRING' }, { 'name': 'linkedAccountId', 'type': 'STRING' }, { 'name': 'type', 'type': 'STRING' }, { 'name': 'status', 'type': 'STRING' }, { 'name': 'eligibleForSearch', 'type': 'BOOLEAN' }] }, { 'name': 'linkedViews', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{ 'name': 'id', 'type': 'STRING' }] }, { 'name': 'audienceType', 'type': 'STRING' }, { 'name': 'audienceDefinition', 'type': 'RECORD', 'fields': [{ 'name': 'includeConditions', 'type': 'RECORD', 'fields': [{ 'name': 'kind', 'type': 'STRING' }, { 'name': 'isSmartList', 'type': 'BOOLEAN' }, { 'name': 'segment', 'type': 'STRING' }, { 'name': 'membershipDurationDays', 'type': 'INTEGER' }, { 'name': 'daysToLookBack', 'type': 'INTEGER' }] }] }, { 'name': 'stateBasedAudienceDefinition', 'type': 'RECORD', 'fields': [{ 'name': 'includeConditions', 'type': 'RECORD', 'fields': [{ 'name': 'kind', 'type': 'STRING' }, { 'name': 'isSmartList', 'type': 'BOOLEAN' }, { 'name': 'segment', 'type': 'STRING' }, { 'name': 'membershipDurationDays', 'type': 'INTEGER' }, { 'name': 'daysToLookBack', 'type': 'INTEGER' }] }, { 'name': 'excludeConditions', 'type': 'RECORD', 'fields': [{ 'name': 'segment', 'type': 'STRING' }, { 'name': 'exclusionDuration', 'type': 'STRING' }] }] }] ACCOUNT_SUMMARIES_SCHEMA = [{ 'name': 'date', 'type': 'DATE' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'kind', 'type': 'STRING' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'starred', 'type': 'BOOLEAN' }, { 'name': 'webProperties', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{ 'name': 'kind', 'type': 'STRING' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'internalWebPropertyId', 'type': 'STRING' }, { 'name': 'level', 'type': 'STRING' }, { 'name': 'websiteUrl', 'type': 'STRING' }, { 'name': 'starred', 'type': 'BOOLEAN' }, { 'name': 'profiles', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [ { 'name': 'kind', 'type': 'STRING' }, { 'name': 'id', 'type': 'STRING' }, { 'name': 'name', 'type': 'STRING' }, { 'name': 'type', 'type': 'STRING' }, { 'name': 'starred', 'type': 'BOOLEAN' }, ] }] }]
def score_hand(player_one: list, player_two: list): if len(player_one) != 7 or len(player_two) != 7: raise RuntimeError('invalid hands') # pairs player_one_pairs = player_one[1] player_two_pairs = player_two[1] player_one_has_pairs = len(player_one_pairs) player_two_has_pairs = len(player_two_pairs) if player_one_has_pairs and not player_two_has_pairs: return 1 elif not player_one_has_pairs and player_two_has_pairs: return -1 elif player_one_has_pairs and player_two_has_pairs: make_list_same_size(player_one_pairs, player_two_pairs) player_one_pairs, player_two_pairs = get_high_values(player_one_pairs, player_two_pairs) player_one_pairs = player_one_pairs if len(player_one_pairs) < 3 else player_one_pairs[:2] player_two_pairs = player_two_pairs if len(player_two_pairs) < 3 else player_two_pairs[:2] # get highest two pairs if len(player_one_pairs) != len(player_two_pairs): return 1 if len(player_one_pairs) > len(player_two_pairs) else -1 for player_one_pair_value, player_two_pair_value in zip(player_one_pairs, player_two_pairs): if player_one_pair_value > player_two_pair_value: return 1 elif player_one_pair_value < player_two_pair_value: return -1 # high cards player_one_high_cards = player_one[0] player_two_high_cards = player_two[0] for player_one_card, player_two_card in zip(player_one_high_cards, player_two_high_cards): player_one_card_value = get_card_value(player_one_card) player_two_card_value = get_card_value(player_two_card) if player_one_card_value == player_two_card_value: continue elif player_one_card_value > player_two_card_value: return 1 else: return -1 return 0 def get_high_values(player_one_pairs, player_two_pairs): player_one_values = [] player_two_values = [] for player_one_pair, player_two_pair in zip(player_one_pairs, player_two_pairs): player_one_has_pairs = len(player_one_pair) player_two_has_pairs = len(player_two_pair) player_one_current_value = get_card_value(player_one_pair[0]) if player_one_has_pairs else 0 player_two_current_value = get_card_value(player_two_pair[0]) if player_two_has_pairs else 0 if player_one_current_value: player_one_values.append(player_one_current_value) if player_two_current_value: player_two_values.append(player_two_current_value) player_one_values.sort(reverse=True) player_two_values.sort(reverse=True) return player_one_values, player_two_values def make_list_same_size(list_one: list, list_two: list) -> None: length_list_one = len(list_one) length_list_two = len(list_two) while length_list_one != length_list_two: if length_list_one > length_list_two: list_two.append([]) length_list_two += 1 else: list_one.append([]) length_list_one += 1 def get_card_value(card): return int(card[1:])
''' Title : Zipped! Subdomain : Built-Ins Domain : Python Author : codeperfectplus Created : 17 January 2020 ''' # Enter your code here. Read input from STDIN. Print output to STDOUT n, x = map(int, input().split()) sheet = [] for _ in range(x): sheet.append(map(float, input().split()) ) for i in zip(*sheet): print( sum(i)/len(i) )
class Solution: def minIncrementForUnique(self, A: List[int]) -> int: ans = 0 minAvailable = 0 A.sort() for a in A: ans += max(minAvailable - a, 0) minAvailable = max(minAvailable, a) + 1 return ans
# # PySNMP MIB module HPN-ICF-ARP-RATELIMIT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-ARP-RATELIMIT-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:37:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion") hpnicfCommon, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfCommon") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") iso, Gauge32, NotificationType, ObjectIdentity, Integer32, Unsigned32, ModuleIdentity, TimeTicks, Counter64, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Bits, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "NotificationType", "ObjectIdentity", "Integer32", "Unsigned32", "ModuleIdentity", "TimeTicks", "Counter64", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Bits", "Counter32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") hpnicfARPRatelimit = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110)) hpnicfARPRatelimit.setRevisions(('2013-10-14 18:00', '2009-12-08 19:12',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hpnicfARPRatelimit.setRevisionsDescriptions(('Add hpnicfARPRatelimitConfigTable.', 'The initial version of this MIB file.',)) if mibBuilder.loadTexts: hpnicfARPRatelimit.setLastUpdated('201310141800Z') if mibBuilder.loadTexts: hpnicfARPRatelimit.setOrganization('') if mibBuilder.loadTexts: hpnicfARPRatelimit.setContactInfo('') if mibBuilder.loadTexts: hpnicfARPRatelimit.setDescription('This MIB file defines the ARP packet rate limit configuration. The ARP packet rate limit feature monitors and controls the rate of ARP packets delivered to the CPU on a device. The current version supports the monitoring feature only.') hpnicfARPRatelimitObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1)) hpnicfARPRatelimitTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 1)) hpnicfARPRatelimitConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 2)) hpnicfARPRatelimitTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 1, 0)) hpnicfARPRatelimitOverspeedTrap = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 1, 0, 1)).setObjects(("HPN-ICF-ARP-RATELIMIT-MIB", "hpnicfARPRatelimitTrapVer"), ("HPN-ICF-ARP-RATELIMIT-MIB", "hpnicfARPRatelimitTrapCount"), ("HPN-ICF-ARP-RATELIMIT-MIB", "hpnicfARPRatelimitTrapMsg")) if mibBuilder.loadTexts: hpnicfARPRatelimitOverspeedTrap.setStatus('current') if mibBuilder.loadTexts: hpnicfARPRatelimitOverspeedTrap.setDescription('If the rate of ARP packets delivered to the CPU on a device exceeds the threshold, a trap message is generated and sent to the remote monitoring device.') hpnicfARPRatelimitTrapObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 1, 1)) hpnicfARPRatelimitTrapVer = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 1, 1, 1), Unsigned32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfARPRatelimitTrapVer.setStatus('current') if mibBuilder.loadTexts: hpnicfARPRatelimitTrapVer.setDescription('The version of trap information.') hpnicfARPRatelimitTrapCount = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 1, 1, 2), Unsigned32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfARPRatelimitTrapCount.setStatus('current') if mibBuilder.loadTexts: hpnicfARPRatelimitTrapCount.setDescription('Number of cells in the trap message. A trap message may contain multiple cells, each of which indicates that the rate information of ARP packets exceeds the threshold.') hpnicfARPRatelimitTrapMsg = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 254))).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfARPRatelimitTrapMsg.setStatus('current') if mibBuilder.loadTexts: hpnicfARPRatelimitTrapMsg.setDescription("This object is the cell section in a trap message sent from a monitored device. This object can contain multiple cells. This object is in the format of '<cell1><cell2>...'. Each cell consists of 17 octets in the format of '<TrapOrigin><IfIndex><OverSpeedValue><Threshold><Interval>'. <TrapOrigin> indicates the source of the trap message and has size of 1 octet. It only supports the following values. 1 - Global. 2 - Interface. <IfIndex> is the index of the interface where the rate of ARP packet exceeds the threshold and has size of 4 octets. It is 0xFFFFFFFF when <TrapOrigin> is 1(Global). <OverSpeedValue> indicates the rate that ARP packets are actually delivered and has size of 4 octets. <Threshold> indicates the threshold that ARP packets can be delivered to CPU and has size of 4 octets. <Interval> indicates the interval that a trap message is sent out and has size of 4 octets.") hpnicfARPRatelimitConfigTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 2, 1), ) if mibBuilder.loadTexts: hpnicfARPRatelimitConfigTable.setStatus('current') if mibBuilder.loadTexts: hpnicfARPRatelimitConfigTable.setDescription('The table is used to configure ARP packet rate limit on interfaces.') hpnicfARPRatelimitConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 2, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: hpnicfARPRatelimitConfigEntry.setStatus('current') if mibBuilder.loadTexts: hpnicfARPRatelimitConfigEntry.setDescription('The entry of hpnicfARPRatelimitConfigTable.') hpnicfARPRatelimitValue = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 110, 1, 2, 1, 1, 1), Unsigned32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfARPRatelimitValue.setStatus('current') if mibBuilder.loadTexts: hpnicfARPRatelimitValue.setDescription('Configure ARP packet rate limit. Support for the value range depends on the device model. If the object is set to 0, the ARP packet rate limit will be disabled.') mibBuilder.exportSymbols("HPN-ICF-ARP-RATELIMIT-MIB", hpnicfARPRatelimitTrap=hpnicfARPRatelimitTrap, hpnicfARPRatelimitTrapObjects=hpnicfARPRatelimitTrapObjects, hpnicfARPRatelimitValue=hpnicfARPRatelimitValue, hpnicfARPRatelimitConfig=hpnicfARPRatelimitConfig, hpnicfARPRatelimitConfigTable=hpnicfARPRatelimitConfigTable, hpnicfARPRatelimitTrapMsg=hpnicfARPRatelimitTrapMsg, hpnicfARPRatelimitTrapVer=hpnicfARPRatelimitTrapVer, PYSNMP_MODULE_ID=hpnicfARPRatelimit, hpnicfARPRatelimitConfigEntry=hpnicfARPRatelimitConfigEntry, hpnicfARPRatelimit=hpnicfARPRatelimit, hpnicfARPRatelimitOverspeedTrap=hpnicfARPRatelimitOverspeedTrap, hpnicfARPRatelimitObjects=hpnicfARPRatelimitObjects, hpnicfARPRatelimitTraps=hpnicfARPRatelimitTraps, hpnicfARPRatelimitTrapCount=hpnicfARPRatelimitTrapCount)
expected_output = {'current-eta-records': 0, 'excess-packets-received': 60, 'excess-syn-received': 0, 'total-eta-fnf': 2, 'total-eta-idp': 2, 'total-eta-records': 4, 'total-eta-splt': 2, 'total-packets-out-of-order': 0, 'total-packets-received': 80, 'total-packets-retransmitted': 0}
class SomeSingleton(object): __instance__ = None def __new__(cls, *args,**kwargs): if SomeSingleton.__instance__ is None: SomeSingleton.__instance__ = object.__new__(cls) return SomeSingleton.__instance__ def __init__(self,f=0,y=0): self.f = f self.y= y def some_func(self,arg): pass if __name__== "__main__": s = SomeSingleton("343","43443")
class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 hw = 0 while n != 0: if n % 2 == 1: hw += 1 n //= 2 return hw
annee = int(input (f"Saisissez une année\n")) if (annee%4 != 0): print ("ce n'est pas une annee bissextile") else: if (annee%100 == 0 and annee%400 != 0): print ("ce n'est une annee bissextile") else : print ("c'est une annee bissextile")
# -*- coding: utf-8 -*- """ Created on Fri Jul 5 03:41:18 2019 @author: srishti """ print("Hello")
# import os # BANK_URL = os.environ['BANK_URL'] # TRANSACTION_URL = os.environ['TRANSACTION_URL'] # UNDERWRITER_URL = os.environ['UNDERWRITER_URL'] # USER_URL = os.environ['USER_URL'] # applications_url = f"http://{UNDERWRITER_URL}/applications" # registration_url = f"http://{USER_URL}/users/registration" # login_url = f"http://{USER_URL}/login" # # Requires bearer token # bank_url = f"http://{BANK_URL}/banks" # branch_url = f"http://{BANK_URL}/branches" # transaction_url = f"http://{TRANSACTION_URL}/transactions" # Kubernetes ingress applications_url = "http://localhost/applications" registration_url = "http://localhost/users/registration" login_url = "http://localhost/login" # Requires bearer token bank_url = "http://localhost/banks" branch_url = "http://localhost/branches" transaction_url = "http://localhost/transactions"
# noinspection PyShadowingBuiltins,PyUnusedLocal def compute(x, y): """The problem sets the parameters as integers in the range 0-100. We'll raise an exception if we receive a type other than int, or if the value of that int is not in the right range""" if type(x) != int or type(y) != int: raise TypeError('The types of both arguments must be ints') if x < 0 or x > 100 or y < 0 or y > 100: raise ValueError('The value of each argument must be in the range 0-100') return x+y
for _ in range(int(input())): a=input() b=input() s={} ans=0 for i in range(26): s[a[i]]=i+1 temp=[] for j in b: temp.append(s[j]) for k in range(len(temp)-1): ans+=abs(temp[k]-temp[k+1]) print(ans)
def isPalindrome(str): result = False if str == str[::-1]: result = True return result print("Please enter a string: ") x = input() flag = isPalindrome(x) if flag: print(x, "is a Palindrome") else: print(x, "is NOT a Palindrome")
""" Faça uma "fabrica decoradora" que retorna um decorador que decora funções com um único argumento. A fábrica deverá receber um argumento, um tipo, e retornar um decorador em que a função verifica se o argumento passado é do tipo correto, senão levanta um TypeError. """ def decorador(função, tipo): def nova_função(arg): if type(arg) != tipo: raise TypeError else: return função(arg) return nova_função
""" File: similarity.py Name: Calvin Chen ---------------------------- This program compares short dna sequence, s2, with sub sequences of a long dna sequence, s1 The way of approaching this task is the same as what people are doing in the bio industry. """ def main(): """ First, enter a long DNA sequence and a short DNA sequence. Second, print out the best match. """ long_seq = input('Please give me a DNA sequence to search: ') long_seq = long_seq.upper() short_seq = input('What DNA sequence would you like to match? ') short_seq = short_seq.upper() print('The best match is ' + best_match(long_seq, short_seq)) def best_match(long_seq, short_seq): """ First, know the len of long_seq and short_seq, and know how many times the long_seq string can loop in order to find out the best match string. Second, for each loop we count how many characters that look the same in each sub string(sub the long_seq) and assigns the counts to the max_same. Third, we return the sub string that includes the most same alphabet to the ans. :param long_seq: string, the DNA string that you will find which part is similar to short_seq. :param short_seq: string, the DNA string that you want to match. :return: ans: string, the best match string in the long_seq DNA string. """ l = len(long_seq) s = len(short_seq) same = 0 max_same = 0 ans = '' for i in range(l - s + 1): sub_l = long_seq[i:i+s] same = 0 for j in range(s): if sub_l[j] == short_seq[j]: same += 1 if same > max_same: max_same = same ans = sub_l return ans ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == '__main__': main()
class Node: def __init__(self, val): self.val = val self.next = None def add(self, val): if not self.next: self.next = Node(val) else: self.next.add(val) def remove(self, val): if self.next.val == val: self.next = self.next.next else: self.next.remove(val) def __str__(self): return str(self.val) class LinkedList: def __init__(self): self.head = None self.length = 0 def push(self, val): if not self.head: self.head = Node(val) else: self.head.add(val) self.length += 1 def add_first(self, val): if not self.head: self.head = Node(val) else: aux = Node(val) aux.next = self.head self.head = aux self.length += 1 def get_length(self): return self.length def remove(self, val): if self.head: if self.head.val == val: self.head = self.head.next elif self.head.next.val == val: self.head.next = self.head.next.next else: self.head.remove(val) self.length -= 1 def remove_by_index(self, index): if self.head: aux = self.head if index == 0: self.head = self.head.next else: while index > 1 and aux: aux = aux.next index -= 1 if index <= 1 and aux.next: aux.next = aux.next.next self.length -= 1 def sort(self, criteria, asc=True): self.head = criteria.sort(self, asc) def count_elements(self): aux = self.head result = {} while aux: if aux.val in result.keys(): result[aux.val] += 1 else: result[aux.val] = 1 aux = aux.next return result def __str__(self): aux = self.head result = '' if aux: result = aux.__str__() while aux.next: aux = aux.next result += ', ' + aux.__str__() return result
""" @author: magician @file: getattr_demo.py @date: 2020/1/14 """ class LazyDB(object): """ LazyDB """ def __init__(self): self.exists = 5 def __getattr__(self, name): value = 'Value for %s' % name setattr(self, name, value) return value class LoggingLazyDB(LazyDB): """ LoggingLazyDB """ def __getattr__(self, name): print('Called __getattr__(%s)' % name) return super().__getattr__(name) class ValidateDB(object): """ ValidateDB """ def __init__(self): self.exists = 5 def __getattribute__(self, name): print('Called __getattribute__(%s)' % name) try: return super().__getattribute__(name) except AttributeError: value = 'Value for %s' % name setattr(self, name, value) return value class MissingPropertyDB(object): """ MissingPropertyDB """ def __getattr__(self, name): if name == 'bad_name': raise AttributeError('%s is missing' % name) class SavingDB(object): """ SavingDB """ def __setattr__(self, name, value): """ Save some data to the DB log @param name: @param value: @return: """ super().__setattr__(name, value) class LoggingSavingDB(SavingDB): """ LoggingSavingDB """ def __setattr__(self, name, value): print('Called __setattr__(%s, %r)' % (name, value)) super().__setattr__(name, value) class BrokenDictionaryDB(object): """ BrokenDictionaryDB """ def __init__(self, data): self._data = data def __getattribute__(self, name): print('Called __getattribute__(%s)' % name) return self._data[name] class DictionaryDB(object): """ DictionaryDB """ def __init__(self, data): self._data = data def __getattribute__(self, name): data_dict = super().__getattribute__('_data') return data_dict[name] if __name__ == '__main__': data = LazyDB() print('Before: ', data.__dict__) print('foo: ', data.foo) print('After: ', data.__dict__) data = LoggingLazyDB() print('exists: ', data.exists) print('foo: ', data.foo) print('foo: ', data.foo) data = ValidateDB() print('exists: ', data.exists) print('foo: ', data.foo) print('foo: ', data.foo) data = MissingPropertyDB() try: data.bad_name except Exception as e: print(e) data = LoggingLazyDB() print('Before: ', data.__dict__) print('foo exists: ', hasattr(data, 'foo')) print('After: ', data.__dict__) print('foo exists: ', hasattr(data, 'foo')) data = ValidateDB() print('foo exists: ', hasattr(data, 'foo')) print('foo exists: ', hasattr(data, 'foo')) data = LoggingSavingDB() print('Before: ', data.__dict__) data.foo = 5 print('After: ', data.__dict__) data.foo = 7 print('Finally: ', data.__dict__) data = BrokenDictionaryDB({'foo': 3}) try: data.foo except Exception as e: print(e) data = DictionaryDB({'foo': 3}) print(data.foo)
# File: factorial_recursion.py # Purpose: Example: FActorial using recursion # Programmer: Amal Shehu # Course: Practice # Date: Sunday 28th August 2016, 11:10 PM num = int(input("Enter a number")) # Convert to an int def factorial(num): if (num == 0): return else: return num*factorial(num-1) # Factorial using recursion result = factorial(num) print(result)
UNKNOWN_WORD = "<unk>" embedding_dimension = 50 min_count = 5 window_size = 3 sample = 1e-3 negative = 5 vocab_size = None train_words = None # Special parameters MIN_SENTENCE_LENGTH = 3
#!/usr/bin/python DNB_YEARLY_PERCENTAGE = 2.10 / 100 DNB_MONTHLY_PERCENTAGE = DNB_YEARLY_PERCENTAGE / 12 DNB_FEE = 50 DNB_INITIAL_PAYMENT = 10000 NORDEA_YEARLY_PERCENTAGE = 2.15 / 100 NORDEA_MONTHLY_PERCENTAGE = NORDEA_YEARLY_PERCENTAGE / 12 NORDEA_FEE = 65 NORDEA_INITIAL_PAYMENT = 0 def months_until_paid_out(credit_sum, monthly_payment, initial_payment, monthly_percentage, monthly_fee): MAX_YEARS = 30 MAX_MONTHS = MAX_YEARS * 12 for month in range(1, MAX_MONTHS): if month == 1: credit_sum = credit_sum * (1 + monthly_percentage) - (monthly_payment - monthly_fee - initial_payment) else: credit_sum = credit_sum * (1 + monthly_percentage) - (monthly_payment - monthly_fee) if credit_sum < 0: print("You will pay out credit in approximately {} months. Sum left {}".format(month, credit_sum)) return print("You have to pay way much bigger monthly payment than {}".format(monthly_payment)) return if __name__ == "__main__": credit_sum = 3000000 monthly_payment = 12500 print("DNB: ") months_until_paid_out(credit_sum, monthly_payment, DNB_INITIAL_PAYMENT, DNB_MONTHLY_PERCENTAGE, DNB_FEE) print("NORDEA: ") months_until_paid_out(credit_sum, monthly_payment, NORDEA_INITIAL_PAYMENT, NORDEA_MONTHLY_PERCENTAGE, NORDEA_FEE)
text="ANCHE TU BRUTO FIGLIO MIO?"; s=4; result=""; text=text.upper(); for i in range(len(text)): c = text[i]; if(c.isupper()): result+=chr((ord(c)+s-65)%26+65); else: result+=chr((ord(c)+s-97)%26+97); print(result);
# -*- encoding: utf-8 -*- ''' @project : LeetCode @File : diameterOfBinaryTree.py @Contact : [email protected] @Desc : @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2020-03-10 zhan 1.0 None ''' # 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: TreeNode) -> int: if root == None: return 0 ans = self.divideConquer(root) return ans[0] def divideConquer(self,root): if root.left == None and root.right == None: return 0,1 if root.left: leftDiameter, leftDepth = self.divideConquer(root.left) else: leftDiameter, leftDepth = -1, 0 if root.right: rightDiameter, rightDepth = self.divideConquer(root.right) else: rightDiameter, rightDepth = -1, 0 diameter = max(leftDiameter,rightDiameter,leftDepth+rightDepth) return diameter, max(leftDepth,rightDepth) + 1 if __name__ == '__main__': [1, 2, 3, 4, 5] leftChild = TreeNode(2) leftChild.left = TreeNode(4) leftChild.right = TreeNode(5) root = TreeNode(1) root.left = leftChild root.right = TreeNode(3) ans = Solution().diameterOfBinaryTree(root) print(ans)
#!/usr/bin/env python # -- coding: utf-8 -- """ Copyright (c) 2019. All rights reserved. Created by C. L. Wang on 2020/1/9 """ dlatents_dir = 'latent_representations' generated_dir = 'generated_images' result_dir = 'results'
render = ez.Node() aspect2D = ez.Node() camera = ez.Camera(parent=render) camera.y = -20 # Create collision shapes: # Collision Sphere: sphere = ez.collision.shapes.Sphere(0.25, parent=render) sphere.parent = None sphere.parent = render # Collide from mask 2: ez.collision.set_mask(sphere, ez.mask[2]) # Set what sphere will collide to: ez.collision.set_from_mask(sphere, ez.mask[1]) sphere.pos = 0, 0 , 0 # Show the shape so we can see what it is doing, for dubugging: sphere.show() sphere.name = "Sphere" # Collision Capsule: capsule = ez.collision.shapes.Capsule((0,0,0), (0,0,1), 0.25, parent=render) ez.collision.set_mask(capsule, ez.mask[1]) capsule.pos = -4, 0, 0 capsule.show() capsule.name = "Capsule" # Collision Box: box = ez.collision.shapes.Box((0.5, 0.25, 1), origin=(0, 0, 0.5), parent=render) ez.collision.set_mask(box, ez.mask[1]) box.pos = 4, 0, 0 box.show() box.name = "Box" # Rays, they are only used for hitting other objects: pos = -2, 0 , -1 to_pos = 0, 0, 2 segment = ez.collision.rays.Segment( pos, to_pos, parent=render) ez.collision.set_from_mask(segment, ez.mask[2]) segment.show() segment.name = "Segment" from_pos = 1, 0, 1 towards = 0, 0, -1 ray = ez.collision.rays.Ray( from_pos, towards, parent=render ) ez.collision.set_from_mask(ray, ez.mask[2]) ray.show() ray.name = "Ray" pos = 2, 0, 0 direction = 0, 0, 1 line = ez.collision.rays.Line( pos, direction, parent=render) ez.collision.set_from_mask(line, ez.mask[2]) line.show() line.name = "line" # Create a collision handler and add colliders: handler = ez.collision.Handler() handler.add_collider(sphere) handler.add_collider(segment) handler.add_collider(ray) handler.add_collider(line) def input(event): device, name, state = event if name == 'escape' and state == 0: ez.set_scene(ez['menu']) def logic(dt): hits = handler.get_collisions(render) if hits: for hit in hits: from_name = hit['FROM'].name into_name = hit['INTO'].name text = ez['text'] text.text = "W - move left" text.text += "\nD - move right\n" text.text += from_name+" HIT "+into_name+" AT "+str(hit['POS']) if ez.is_button_down('a'): if sphere.x > -5: sphere.x -= 2*dt if ez.is_button_down('d'): if sphere.x < 5: sphere.x += 2*dt def enter(): ez.window.background_color = 0, 0, 0 L, R, T, B = ez.window.get_aspect2D_edges() text = ez['text'] text.text = "A - move left" text.text += "\nD - move right" text.x = L+0.01 text.y = T-0.08 text.parent = aspect2D def exit(): pass
while True: senha=int(input('digite sua senha : ')) if senha==2: print('acesso permitido') break else: print('senha invalida, tente novamente')
#!/usr/bin/env python3 def myFunc(x, y): if not isinstance(x, (int, float)): raise TypeError('x has wrong type') if not isinstance(y, (int, float)): raise TypeError('y has wrong type') else: print(x + y) myFunc(1, 3)
phonetic_alphabet = {"alpha": "A", "adam": "A", "boy": "B", "bravo": "B", "charlie": "C", "delta": "D", "david": "D", "echo": "E", "edward": "E", "foxtrot": "F", "frank": "F", "golf": "G", "george": "G", "hotel": "H", "henry": "H", "india": "I", "ida": "I", "aida": "I", "juliette": "J", "john": "J", "kilo": "K", "king": "K", "lima": "L", "lincoln": "L", "mike": "M", "mary": "M", "marry": "M", "november": "N", "norah": "N", "nora": "N", "oscar": "O", "ocean": "O", "papa": "P", "paul": "P", "quebec": "Q", "queen": "Q", "romeo": "R", "robert": "R", "sierra": "S", "sam": "S", "tango": "T", "tom": "T", "uniform": "U", "union": "U", "victor": "V", "vector": "V", "whiskey": "W", "william": "W", "x-ray": "X","yankee": "Y", "young": "Y", "zulu": "Z", "zebra": "Z", "neiner": "9", "niner": "9", "neither": "9", "alfa": "A" } states = { 'alaska': 'AK', 'alabama': 'AL', 'arkansas': 'AR', 'american samoa': 'AS', 'arizona': 'AZ', 'california': 'CA', 'colorado': 'CO', 'connecticut': 'CT', 'district of columbia': 'DC', 'delaware': 'DE', 'florida': 'FL', 'georgia': 'GA', 'guam': 'GU', 'hawaii': 'HI', 'iowa': 'IA', 'idaho': 'ID', 'illinois': 'IL', 'indiana': 'IN', 'kansas': 'KS', 'kentucky': 'KY', 'louisiana': 'LA', 'massachusetts': 'MA', 'maryland': 'MD', 'maine': 'ME', 'main': 'ME', 'michigan': 'MI', 'minnesota': 'MN', 'missouri': 'MO', 'northern mariana islands': 'MP', 'mississippi': 'MS', 'montana': 'MT', 'national': 'NA', 'north carolina': 'NC', 'north dakota': 'ND', 'nebraska': 'NE', 'new hampshire': 'NH', 'new jersey': 'NJ', 'new mexico': 'NM', 'nevada': 'NV', 'new york': 'NY', 'ohio': 'OH', 'oklahoma': 'OK', 'oregon': 'OR', 'pennsylvania': 'PA', 'puerto rico': 'PR', 'rhode island': 'RI', 'south carolina': 'SC', 'south dakota': 'SD', 'tennessee': 'TN', 'texas': 'TX', 'utah': 'UT', 'virginia': 'VA', 'virgin islands': 'VI', 'vermont': 'VT', 'washington': 'WA', 'wisconsin': 'WI', 'west virginia': 'WV', 'wyoming': 'WY' }
#ref Exercício Python 094 - Unindo dicionários e listas do Curso em vídeo dici = {} lista = [] mulher = [] mmedi = [] m = 0 while True: dici['nome'] = str(input(f'Qual o nome ? ')) dici['sexo'] = str(input(f'Qual o sexo do {dici["nome"]} ? ')) dici['idade'] = int(input(f'Qual a idade do {dici["nome"]} ? ')) lista.append(dici.copy()) print(dici) resp = str(input('Deseja continuar ? (S/N) ')) if resp[0] in 'Nn': break print(lista) print(f'Ao total teve {len(lista)} pessoa(s) cadastrada(s).') for c in lista: m += c['idade'] m = m // len(lista) for c in lista: if c['sexo'] == 'Femi': mulher.append(c['nome']) if c['idade'] > m: mmedi.append(c['nome']) print(f'A média de idade das {len(lista)} pessoa(s) é {m}') print(f'A lista com o nome de todas as mulheres: {mulher}') print(f'A lista com a(s) pessoa(s) com idade acima da média é: {mmedi}')
def decrypt(ciphertext, s): pltext = "" for i in range(len(ciphertext)): char = ciphertext[i] if (char.isupper()): pltext += chr((ord(char) - s-65) % 26 + 65) else: pltext += chr((ord(char) - s - 97) % 26 + 97) return pltext ciphertext = "EXXEGOEXSRGI" s = 4 print("Cipher : " + ciphertext) print("Shift : " + str(s)) print("Plain text: " + decrypt(ciphertext,s))
# -*- coding: utf-8 -*- """ Programa que recebe como entrada dois arquivos: O primeiro arquivo contém nomes de alunos O segundo arquivo contém as notas dos alunos E será gerado um terceiro arquivo contendo as médias. """ def acertarNotas(aluno,nota): f1 = open(aluno,"r") # Abre no modo leitura o arquivo com os nomes f2 = open(nota,"r") # Abre no modo leitura o arquivo com as notas listanota = [] # Cria uma lista a ser preenchida com as notas texto = f1.readlines() # Lê todas as linahs do arquivo nota for i in texto: notas = f2.readline().split() # separa as notas em linha em lista de strings valores = [float(val) for val in notas] # Transforma as notas em valores float media = sum(valores) / len(valores) # Soma os valores e cria uma média sobre eles todos= i+" "+str(notas)+" "+str(media)+"\n" # Cria uma lista de nomes concatenados com suas médias listanota.append(todos) # Adiciona a lista de notas f1.close() f2.close() arquivo=open('listamedias','w') # Cria uma arquivo para salvar as execuções realizadas arquivo.writelines(listanota) # Transcreve as informações no arquivo arquivo.close() return acertarNotas("aluno.csv","nota.csv") # Chama afunção criada com os arquivos externos
############################################################################### # Copyright (c) 2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory # Written by Francesco Di Natale, [email protected]. # # LLNL-CODE-734340 # All rights reserved. # This file is part of MaestroWF, Version: 1.0.0. # # For details, see https://github.com/LLNL/maestrowf. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ############################################################################### """Module that defines containers for storing various types of information.""" class Record(object): """A container class for holding general information.""" def __init__(self): """Initialize an empty Record.""" self._info = {} def get(self, key, default=None): """ Get information by key in a record. :param key: The key to look up in a Record's stored information. :param default: The default value to return if the key is not found (Default: None). :returns: The information labeled by parameter key. Default if key does not exist. """ return self._info.get(key, default)
# A non-empty array A consisting of N integers is given. # A permutation is a sequence containing each element from 1 to N once, and only once. # For example, array A such that: # A[0] = 4 # A[1] = 1 # A[2] = 3 # A[3] = 2 # is a permutation, but array A such that: # A[0] = 4 # A[1] = 1 # A[2] = 3 # is not a permutation, because value 2 is missing. # The goal is to check whether array A is a permutation. # Write a function that, given an array A, returns 1 if array A is a permutation and 0 if it is not. # Write an efficient algorithm for the following assumptions: # N is an integer within the range [1..100,000]; # each element of array A is an integer within the range [1..1,000,000,000]. # O(n)t | O(n)s def permCheck(A): memo = {} limit = len(A) for element in A: if not 1 <= element <= limit: return 0 else: if element in memo: return 0 else: memo[element] = True return 1
# Sequência de Collatz mais longa # Considere a seguinte sequência iterativa definida para os números inteiros positivos: # \begin{align} # n &\rightarrow n/2 (n\text{ é par}) \\ # n & \rightarrow 3n+1 (n\text{ é ímpar}) # \end{align} # Usando a regra acima e começando com o número 13, geramos a seguinte sequência: # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # Percebe-se que essa sequência (começando em 13 e terminando em 1) contém 10 termos. Apesar de ainda não ter sido provado (Problema de Collatz), acredita-se que a sequência sempre termina em 1, independentemente do número inicial. # Faça um programa que determina qual número positivo inicial menor que 1000 gera a sequência de Collatz mais longa. Seu programa deve imprimir esse número. # Nota: Uma vez que a sequência começa os números podem passar de 1000. # Adaptado de https://projecteuler.net/problem=14 def is_odd (number): return bool(number % 2) max_n = 0 count = 0 n0 = 0 n = n0 while n0 < 1000: counting = 0 n0 += 1 n = n0 while n > 1: if is_odd(n): n = 3 * n + 1 else: n = n / 2 counting += 1 if counting > count: max_n = n0 count = counting print(max_n)
ITCH_BASE = "itch.io" ITCH_URL = f"https://{ITCH_BASE}" ITCH_API = f"https://api.{ITCH_BASE}" # Extracts https://user.itch.io/name to {'author': 'user', 'game': 'name'} ITCH_GAME_URL_REGEX = r"^https:\/\/(?P<author>[\w\d\-_]+).itch.io\/(?P<game>[\w\d\-_]+)$" ITCH_BROWSER_TYPES = [ "games", "tools", "game-assets", "comics", "books", "physical-games", "soundtracks", "game-mods", "misc", ]
""" Tile providers. This file is autogenerated! It is a python representation of the leaflet providers defined by the leaflet-providers.js extension to Leaflet (https://github.com/leaflet-extras/leaflet-providers). Credit to the leaflet-providers.js project (BSD 2-Clause "Simplified" License) and the Leaflet Providers contributors. Generated by parse_leaflet_providers.py at 2019-08-01 from leaflet-providers at commit 9eb968f8442ea492626c9c8f0dac8ede484e6905 (Bumped version to 1.8.0). """ class Bunch(dict): """A dict with attribute-access""" def __getattr__(self, key): try: return self.__getitem__(key) except KeyError: raise AttributeError(key) def __dir__(self): return self.keys() class TileProvider(Bunch): """ A dict with attribute-access and that can be called to update keys """ def __call__(self, **kwargs): new = TileProvider(self) # takes a copy preserving the class new.update(kwargs) return new providers = Bunch( OpenStreetMap = Bunch( Mapnik = TileProvider( url = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', max_zoom = 19, attribution = '(C) OpenStreetMap contributors', name = 'OpenStreetMap.Mapnik' ), DE = TileProvider( url = 'https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png', max_zoom = 18, attribution = '(C) OpenStreetMap contributors', name = 'OpenStreetMap.DE' ), CH = TileProvider( url = 'https://tile.osm.ch/switzerland/{z}/{x}/{y}.png', max_zoom = 18, attribution = '(C) OpenStreetMap contributors', bounds = [[45, 5], [48, 11]], name = 'OpenStreetMap.CH' ), France = TileProvider( url = 'https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', max_zoom = 20, attribution = '(C) Openstreetmap France | (C) OpenStreetMap contributors', name = 'OpenStreetMap.France' ), HOT = TileProvider( url = 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', max_zoom = 19, attribution = '(C) OpenStreetMap contributors, Tiles style by Humanitarian OpenStreetMap Team hosted by OpenStreetMap France', name = 'OpenStreetMap.HOT' ), BZH = TileProvider( url = 'https://tile.openstreetmap.bzh/br/{z}/{x}/{y}.png', max_zoom = 19, attribution = '(C) OpenStreetMap contributors, Tiles courtesy of Breton OpenStreetMap Team', bounds = [[46.2, -5.5], [50, 0.7]], name = 'OpenStreetMap.BZH' ) ), OpenSeaMap = TileProvider( url = 'https://tiles.openseamap.org/seamark/{z}/{x}/{y}.png', attribution = 'Map data: (C) OpenSeaMap contributors', name = 'OpenSeaMap' ), OpenPtMap = TileProvider( url = 'http://openptmap.org/tiles/{z}/{x}/{y}.png', max_zoom = 17, attribution = 'Map data: (C) OpenPtMap contributors', name = 'OpenPtMap' ), OpenTopoMap = TileProvider( url = 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', max_zoom = 17, attribution = 'Map data: (C) OpenStreetMap contributors, SRTM | Map style: (C) OpenTopoMap (CC-BY-SA)', name = 'OpenTopoMap' ), OpenRailwayMap = TileProvider( url = 'https://{s}.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png', max_zoom = 19, attribution = 'Map data: (C) OpenStreetMap contributors | Map style: (C) OpenRailwayMap (CC-BY-SA)', name = 'OpenRailwayMap' ), OpenFireMap = TileProvider( url = 'http://openfiremap.org/hytiles/{z}/{x}/{y}.png', max_zoom = 19, attribution = 'Map data: (C) OpenStreetMap contributors | Map style: (C) OpenFireMap (CC-BY-SA)', name = 'OpenFireMap' ), SafeCast = TileProvider( url = 'https://s3.amazonaws.com/te512.safecast.org/{z}/{x}/{y}.png', max_zoom = 16, attribution = 'Map data: (C) OpenStreetMap contributors | Map style: (C) SafeCast (CC-BY-SA)', name = 'SafeCast' ), Thunderforest = Bunch( OpenCycleMap = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'cycle', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.OpenCycleMap' ), Transport = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'transport', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.Transport' ), TransportDark = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'transport-dark', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.TransportDark' ), SpinalMap = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'spinal-map', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.SpinalMap' ), Landscape = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'landscape', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.Landscape' ), Outdoors = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'outdoors', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.Outdoors' ), Pioneer = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'pioneer', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.Pioneer' ), MobileAtlas = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'mobile-atlas', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.MobileAtlas' ), Neighbourhood = TileProvider( url = 'https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}', attribution = '(C) Thunderforest, (C) OpenStreetMap contributors', variant = 'neighbourhood', apikey = '<insert your api key here>', max_zoom = 22, name = 'Thunderforest.Neighbourhood' ) ), OpenMapSurfer = Bunch( Roads = TileProvider( url = 'https://maps.heigit.org/openmapsurfer/tiles/{variant}/webmercator/{z}/{x}/{y}.png', max_zoom = 19, variant = 'roads', attribution = 'Imagery from GIScience Research Group @ University of Heidelberg | Map data (C) OpenStreetMap contributors', name = 'OpenMapSurfer.Roads' ), Hybrid = TileProvider( url = 'https://maps.heigit.org/openmapsurfer/tiles/{variant}/webmercator/{z}/{x}/{y}.png', max_zoom = 19, variant = 'hybrid', attribution = 'Imagery from GIScience Research Group @ University of Heidelberg | Map data (C) OpenStreetMap contributors', name = 'OpenMapSurfer.Hybrid' ), AdminBounds = TileProvider( url = 'https://maps.heigit.org/openmapsurfer/tiles/{variant}/webmercator/{z}/{x}/{y}.png', max_zoom = 18, variant = 'adminb', attribution = 'Imagery from GIScience Research Group @ University of Heidelberg | Map data (C) OpenStreetMap contributors', name = 'OpenMapSurfer.AdminBounds' ), ContourLines = TileProvider( url = 'https://maps.heigit.org/openmapsurfer/tiles/{variant}/webmercator/{z}/{x}/{y}.png', max_zoom = 18, variant = 'asterc', attribution = 'Imagery from GIScience Research Group @ University of Heidelberg | Map data ASTER GDEM', min_zoom = 13, name = 'OpenMapSurfer.ContourLines' ), Hillshade = TileProvider( url = 'https://maps.heigit.org/openmapsurfer/tiles/{variant}/webmercator/{z}/{x}/{y}.png', max_zoom = 18, variant = 'asterh', attribution = 'Imagery from GIScience Research Group @ University of Heidelberg | Map data ASTER GDEM, SRTM', name = 'OpenMapSurfer.Hillshade' ), ElementsAtRisk = TileProvider( url = 'https://maps.heigit.org/openmapsurfer/tiles/{variant}/webmercator/{z}/{x}/{y}.png', max_zoom = 19, variant = 'elements_at_risk', attribution = 'Imagery from GIScience Research Group @ University of Heidelberg | Map data (C) OpenStreetMap contributors', name = 'OpenMapSurfer.ElementsAtRisk' ) ), Hydda = Bunch( Full = TileProvider( url = 'https://{s}.tile.openstreetmap.se/hydda/{variant}/{z}/{x}/{y}.png', max_zoom = 18, variant = 'full', attribution = 'Tiles courtesy of OpenStreetMap Sweden -- Map data (C) OpenStreetMap contributors', name = 'Hydda.Full' ), Base = TileProvider( url = 'https://{s}.tile.openstreetmap.se/hydda/{variant}/{z}/{x}/{y}.png', max_zoom = 18, variant = 'base', attribution = 'Tiles courtesy of OpenStreetMap Sweden -- Map data (C) OpenStreetMap contributors', name = 'Hydda.Base' ), RoadsAndLabels = TileProvider( url = 'https://{s}.tile.openstreetmap.se/hydda/{variant}/{z}/{x}/{y}.png', max_zoom = 18, variant = 'roads_and_labels', attribution = 'Tiles courtesy of OpenStreetMap Sweden -- Map data (C) OpenStreetMap contributors', name = 'Hydda.RoadsAndLabels' ) ), MapBox = TileProvider( url = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}{r}.png?access_token={accessToken}', attribution = '(C) Mapbox (C) OpenStreetMap contributors Improve this map', subdomains = 'abcd', id = 'mapbox.streets', accessToken = '<insert your access token here>', name = 'MapBox' ), Stamen = Bunch( Toner = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 20, variant = 'toner', ext = 'png', name = 'Stamen.Toner' ), TonerBackground = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 20, variant = 'toner-background', ext = 'png', name = 'Stamen.TonerBackground' ), TonerHybrid = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 20, variant = 'toner-hybrid', ext = 'png', name = 'Stamen.TonerHybrid' ), TonerLines = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 20, variant = 'toner-lines', ext = 'png', name = 'Stamen.TonerLines' ), TonerLabels = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 20, variant = 'toner-labels', ext = 'png', name = 'Stamen.TonerLabels' ), TonerLite = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 20, variant = 'toner-lite', ext = 'png', name = 'Stamen.TonerLite' ), Watercolor = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 1, max_zoom = 16, variant = 'watercolor', ext = 'jpg', name = 'Stamen.Watercolor' ), Terrain = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 18, variant = 'terrain', ext = 'png', name = 'Stamen.Terrain' ), TerrainBackground = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 18, variant = 'terrain-background', ext = 'png', name = 'Stamen.TerrainBackground' ), TopOSMRelief = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 20, variant = 'toposm-color-relief', ext = 'jpg', bounds = [[22, -132], [51, -56]], name = 'Stamen.TopOSMRelief' ), TopOSMFeatures = TileProvider( url = 'https://stamen-tiles-{s}.a.ssl.fastly.net/{variant}/{z}/{x}/{y}{r}.{ext}', attribution = 'Map tiles by Stamen Design, CC BY 3.0 -- Map data (C) OpenStreetMap contributors', subdomains = 'abcd', min_zoom = 0, max_zoom = 20, variant = 'toposm-features', ext = 'png', bounds = [[22, -132], [51, -56]], opacity = 0.9, name = 'Stamen.TopOSMFeatures' ) ), Esri = Bunch( WorldStreetMap = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'World_Street_Map', attribution = 'Tiles (C) Esri -- Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012', name = 'Esri.WorldStreetMap' ), DeLorme = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'Specialty/DeLorme_World_Base_Map', attribution = 'Tiles (C) Esri -- Copyright: (C)2012 DeLorme', min_zoom = 1, max_zoom = 11, name = 'Esri.DeLorme' ), WorldTopoMap = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'World_Topo_Map', attribution = 'Tiles (C) Esri -- Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community', name = 'Esri.WorldTopoMap' ), WorldImagery = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'World_Imagery', attribution = 'Tiles (C) Esri -- Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community', name = 'Esri.WorldImagery' ), WorldTerrain = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'World_Terrain_Base', attribution = 'Tiles (C) Esri -- Source: USGS, Esri, TANA, DeLorme, and NPS', max_zoom = 13, name = 'Esri.WorldTerrain' ), WorldShadedRelief = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'World_Shaded_Relief', attribution = 'Tiles (C) Esri -- Source: Esri', max_zoom = 13, name = 'Esri.WorldShadedRelief' ), WorldPhysical = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'World_Physical_Map', attribution = 'Tiles (C) Esri -- Source: US National Park Service', max_zoom = 8, name = 'Esri.WorldPhysical' ), OceanBasemap = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'Ocean_Basemap', attribution = 'Tiles (C) Esri -- Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri', max_zoom = 13, name = 'Esri.OceanBasemap' ), NatGeoWorldMap = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'NatGeo_World_Map', attribution = 'Tiles (C) Esri -- National Geographic, Esri, DeLorme, NAVTEQ, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, iPC', max_zoom = 16, name = 'Esri.NatGeoWorldMap' ), WorldGrayCanvas = TileProvider( url = 'https://server.arcgisonline.com/ArcGIS/rest/services/{variant}/MapServer/tile/{z}/{y}/{x}', variant = 'Canvas/World_Light_Gray_Base', attribution = 'Tiles (C) Esri -- Esri, DeLorme, NAVTEQ', max_zoom = 16, name = 'Esri.WorldGrayCanvas' ) ), OpenWeatherMap = Bunch( Clouds = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'clouds', name = 'OpenWeatherMap.Clouds' ), CloudsClassic = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'clouds_cls', name = 'OpenWeatherMap.CloudsClassic' ), Precipitation = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'precipitation', name = 'OpenWeatherMap.Precipitation' ), PrecipitationClassic = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'precipitation_cls', name = 'OpenWeatherMap.PrecipitationClassic' ), Rain = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'rain', name = 'OpenWeatherMap.Rain' ), RainClassic = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'rain_cls', name = 'OpenWeatherMap.RainClassic' ), Pressure = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'pressure', name = 'OpenWeatherMap.Pressure' ), PressureContour = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'pressure_cntr', name = 'OpenWeatherMap.PressureContour' ), Wind = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'wind', name = 'OpenWeatherMap.Wind' ), Temperature = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'temp', name = 'OpenWeatherMap.Temperature' ), Snow = TileProvider( url = 'http://{s}.tile.openweathermap.org/map/{variant}/{z}/{x}/{y}.png?appid={apiKey}', max_zoom = 19, attribution = 'Map data (C) OpenWeatherMap', apiKey = '<insert your api key here>', opacity = 0.5, variant = 'snow', name = 'OpenWeatherMap.Snow' ) ), HERE = Bunch( normalDay = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalDay' ), normalDayCustom = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day.custom', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalDayCustom' ), normalDayGrey = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day.grey', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalDayGrey' ), normalDayMobile = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day.mobile', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalDayMobile' ), normalDayGreyMobile = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day.grey.mobile', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalDayGreyMobile' ), normalDayTransit = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day.transit', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalDayTransit' ), normalDayTransitMobile = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day.transit.mobile', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalDayTransitMobile' ), normalNight = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.night', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalNight' ), normalNightMobile = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.night.mobile', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalNightMobile' ), normalNightGrey = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.night.grey', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalNightGrey' ), normalNightGreyMobile = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.night.grey.mobile', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalNightGreyMobile' ), normalNightTransit = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.night.transit', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalNightTransit' ), normalNightTransitMobile = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.night.transit.mobile', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.normalNightTransitMobile' ), reducedDay = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'reduced.day', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.reducedDay' ), reducedNight = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'reduced.night', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.reducedNight' ), basicMap = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day', max_zoom = 20, type = 'basetile', language = 'eng', format = 'png8', size = '256', name = 'HERE.basicMap' ), mapLabels = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'normal.day', max_zoom = 20, type = 'labeltile', language = 'eng', format = 'png', size = '256', name = 'HERE.mapLabels' ), trafficFlow = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'traffic', variant = 'normal.day', max_zoom = 20, type = 'flowtile', language = 'eng', format = 'png8', size = '256', name = 'HERE.trafficFlow' ), carnavDayGrey = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'carnav.day.grey', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.carnavDayGrey' ), hybridDay = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'aerial', variant = 'hybrid.day', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.hybridDay' ), hybridDayMobile = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'aerial', variant = 'hybrid.day.mobile', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.hybridDayMobile' ), hybridDayTransit = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'aerial', variant = 'hybrid.day.transit', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.hybridDayTransit' ), hybridDayGrey = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'aerial', variant = 'hybrid.grey.day', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.hybridDayGrey' ), pedestrianDay = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'pedestrian.day', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.pedestrianDay' ), pedestrianNight = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'base', variant = 'pedestrian.night', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.pedestrianNight' ), satelliteDay = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'aerial', variant = 'satellite.day', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.satelliteDay' ), terrainDay = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'aerial', variant = 'terrain.day', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.terrainDay' ), terrainDayMobile = TileProvider( url = 'https://{s}.{base}.maps.api.here.com/maptile/2.1/{type}/{mapID}/{variant}/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}', attribution = 'Map (C) 1987-2019 HERE', subdomains = '1234', mapID = 'newest', app_id = '<insert your app_id here>', app_code = '<insert your app_code here>', base = 'aerial', variant = 'terrain.day.mobile', max_zoom = 20, type = 'maptile', language = 'eng', format = 'png8', size = '256', name = 'HERE.terrainDayMobile' ) ), FreeMapSK = TileProvider( url = 'http://t{s}.freemap.sk/T/{z}/{x}/{y}.jpeg', min_zoom = 8, max_zoom = 16, subdomains = '1234', bounds = [[47.204642, 15.996093], [49.830896, 22.576904]], attribution = '(C) OpenStreetMap contributors, vizualization CC-By-SA 2.0 Freemap.sk', name = 'FreeMapSK' ), MtbMap = TileProvider( url = 'http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png', attribution = '(C) OpenStreetMap contributors & USGS', name = 'MtbMap' ), CartoDB = Bunch( Positron = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'light_all', name = 'CartoDB.Positron' ), PositronNoLabels = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'light_nolabels', name = 'CartoDB.PositronNoLabels' ), PositronOnlyLabels = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'light_only_labels', name = 'CartoDB.PositronOnlyLabels' ), DarkMatter = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'dark_all', name = 'CartoDB.DarkMatter' ), DarkMatterNoLabels = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'dark_nolabels', name = 'CartoDB.DarkMatterNoLabels' ), DarkMatterOnlyLabels = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'dark_only_labels', name = 'CartoDB.DarkMatterOnlyLabels' ), Voyager = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'rastertiles/voyager', name = 'CartoDB.Voyager' ), VoyagerNoLabels = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'rastertiles/voyager_nolabels', name = 'CartoDB.VoyagerNoLabels' ), VoyagerOnlyLabels = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'rastertiles/voyager_only_labels', name = 'CartoDB.VoyagerOnlyLabels' ), VoyagerLabelsUnder = TileProvider( url = 'https://{s}.basemaps.cartocdn.com/{variant}/{z}/{x}/{y}{r}.png', attribution = '(C) OpenStreetMap contributors (C) CARTO', subdomains = 'abcd', max_zoom = 19, variant = 'rastertiles/voyager_labels_under', name = 'CartoDB.VoyagerLabelsUnder' ) ), HikeBike = Bunch( HikeBike = TileProvider( url = 'https://tiles.wmflabs.org/{variant}/{z}/{x}/{y}.png', max_zoom = 19, attribution = '(C) OpenStreetMap contributors', variant = 'hikebike', name = 'HikeBike.HikeBike' ), HillShading = TileProvider( url = 'https://tiles.wmflabs.org/{variant}/{z}/{x}/{y}.png', max_zoom = 15, attribution = '(C) OpenStreetMap contributors', variant = 'hillshading', name = 'HikeBike.HillShading' ) ), BasemapAT = Bunch( basemap = TileProvider( url = 'https://maps{s}.wien.gv.at/basemap/{variant}/normal/google3857/{z}/{y}/{x}.{format}', max_zoom = 20, attribution = 'Datenquelle: basemap.at', subdomains = ['', '1', '2', '3', '4'], format = 'png', bounds = [[46.35877, 8.782379], [49.037872, 17.189532]], variant = 'geolandbasemap', name = 'BasemapAT.basemap' ), grau = TileProvider( url = 'https://maps{s}.wien.gv.at/basemap/{variant}/normal/google3857/{z}/{y}/{x}.{format}', max_zoom = 19, attribution = 'Datenquelle: basemap.at', subdomains = ['', '1', '2', '3', '4'], format = 'png', bounds = [[46.35877, 8.782379], [49.037872, 17.189532]], variant = 'bmapgrau', name = 'BasemapAT.grau' ), overlay = TileProvider( url = 'https://maps{s}.wien.gv.at/basemap/{variant}/normal/google3857/{z}/{y}/{x}.{format}', max_zoom = 19, attribution = 'Datenquelle: basemap.at', subdomains = ['', '1', '2', '3', '4'], format = 'png', bounds = [[46.35877, 8.782379], [49.037872, 17.189532]], variant = 'bmapoverlay', name = 'BasemapAT.overlay' ), highdpi = TileProvider( url = 'https://maps{s}.wien.gv.at/basemap/{variant}/normal/google3857/{z}/{y}/{x}.{format}', max_zoom = 19, attribution = 'Datenquelle: basemap.at', subdomains = ['', '1', '2', '3', '4'], format = 'jpeg', bounds = [[46.35877, 8.782379], [49.037872, 17.189532]], variant = 'bmaphidpi', name = 'BasemapAT.highdpi' ), orthofoto = TileProvider( url = 'https://maps{s}.wien.gv.at/basemap/{variant}/normal/google3857/{z}/{y}/{x}.{format}', max_zoom = 20, attribution = 'Datenquelle: basemap.at', subdomains = ['', '1', '2', '3', '4'], format = 'jpeg', bounds = [[46.35877, 8.782379], [49.037872, 17.189532]], variant = 'bmaporthofoto30cm', name = 'BasemapAT.orthofoto' ) ), nlmaps = Bunch( standaard = TileProvider( url = 'https://geodata.nationaalgeoregister.nl/tiles/service/wmts/{variant}/EPSG:3857/{z}/{x}/{y}.png', min_zoom = 6, max_zoom = 19, bounds = [[50.5, 3.25], [54, 7.6]], attribution = 'Kaartgegevens (C) Kadaster', variant = 'brtachtergrondkaart', name = 'nlmaps.standaard' ), pastel = TileProvider( url = 'https://geodata.nationaalgeoregister.nl/tiles/service/wmts/{variant}/EPSG:3857/{z}/{x}/{y}.png', min_zoom = 6, max_zoom = 19, bounds = [[50.5, 3.25], [54, 7.6]], attribution = 'Kaartgegevens (C) Kadaster', variant = 'brtachtergrondkaartpastel', name = 'nlmaps.pastel' ), grijs = TileProvider( url = 'https://geodata.nationaalgeoregister.nl/tiles/service/wmts/{variant}/EPSG:3857/{z}/{x}/{y}.png', min_zoom = 6, max_zoom = 19, bounds = [[50.5, 3.25], [54, 7.6]], attribution = 'Kaartgegevens (C) Kadaster', variant = 'brtachtergrondkaartgrijs', name = 'nlmaps.grijs' ), luchtfoto = TileProvider( url = 'https://geodata.nationaalgeoregister.nl/luchtfoto/rgb/wmts/1.0.0/2016_ortho25/EPSG:3857/{z}/{x}/{y}.png', min_zoom = 6, max_zoom = 19, bounds = [[50.5, 3.25], [54, 7.6]], attribution = 'Kaartgegevens (C) Kadaster', name = 'nlmaps.luchtfoto' ) ), NASAGIBS = Bunch( ModisTerraTrueColorCR = TileProvider( url = 'https://map1.vis.earthdata.nasa.gov/wmts-webmerc/{variant}/default/{time}/{tilematrixset}{max_zoom}/{z}/{y}/{x}.{format}', attribution = 'Imagery provided by services from the Global Imagery Browse Services (GIBS), operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ.', bounds = [[-85.0511287776, -179.999999975], [85.0511287776, 179.999999975]], min_zoom = 1, max_zoom = 9, format = 'jpg', time = '', tilematrixset = 'GoogleMapsCompatible_Level', variant = 'MODIS_Terra_CorrectedReflectance_TrueColor', name = 'NASAGIBS.ModisTerraTrueColorCR' ), ModisTerraBands367CR = TileProvider( url = 'https://map1.vis.earthdata.nasa.gov/wmts-webmerc/{variant}/default/{time}/{tilematrixset}{max_zoom}/{z}/{y}/{x}.{format}', attribution = 'Imagery provided by services from the Global Imagery Browse Services (GIBS), operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ.', bounds = [[-85.0511287776, -179.999999975], [85.0511287776, 179.999999975]], min_zoom = 1, max_zoom = 9, format = 'jpg', time = '', tilematrixset = 'GoogleMapsCompatible_Level', variant = 'MODIS_Terra_CorrectedReflectance_Bands367', name = 'NASAGIBS.ModisTerraBands367CR' ), ViirsEarthAtNight2012 = TileProvider( url = 'https://map1.vis.earthdata.nasa.gov/wmts-webmerc/{variant}/default/{time}/{tilematrixset}{max_zoom}/{z}/{y}/{x}.{format}', attribution = 'Imagery provided by services from the Global Imagery Browse Services (GIBS), operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ.', bounds = [[-85.0511287776, -179.999999975], [85.0511287776, 179.999999975]], min_zoom = 1, max_zoom = 8, format = 'jpg', time = '', tilematrixset = 'GoogleMapsCompatible_Level', variant = 'VIIRS_CityLights_2012', name = 'NASAGIBS.ViirsEarthAtNight2012' ), ModisTerraLSTDay = TileProvider( url = 'https://map1.vis.earthdata.nasa.gov/wmts-webmerc/{variant}/default/{time}/{tilematrixset}{max_zoom}/{z}/{y}/{x}.{format}', attribution = 'Imagery provided by services from the Global Imagery Browse Services (GIBS), operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ.', bounds = [[-85.0511287776, -179.999999975], [85.0511287776, 179.999999975]], min_zoom = 1, max_zoom = 7, format = 'png', time = '', tilematrixset = 'GoogleMapsCompatible_Level', variant = 'MODIS_Terra_Land_Surface_Temp_Day', opacity = 0.75, name = 'NASAGIBS.ModisTerraLSTDay' ), ModisTerraSnowCover = TileProvider( url = 'https://map1.vis.earthdata.nasa.gov/wmts-webmerc/{variant}/default/{time}/{tilematrixset}{max_zoom}/{z}/{y}/{x}.{format}', attribution = 'Imagery provided by services from the Global Imagery Browse Services (GIBS), operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ.', bounds = [[-85.0511287776, -179.999999975], [85.0511287776, 179.999999975]], min_zoom = 1, max_zoom = 8, format = 'png', time = '', tilematrixset = 'GoogleMapsCompatible_Level', variant = 'MODIS_Terra_Snow_Cover', opacity = 0.75, name = 'NASAGIBS.ModisTerraSnowCover' ), ModisTerraAOD = TileProvider( url = 'https://map1.vis.earthdata.nasa.gov/wmts-webmerc/{variant}/default/{time}/{tilematrixset}{max_zoom}/{z}/{y}/{x}.{format}', attribution = 'Imagery provided by services from the Global Imagery Browse Services (GIBS), operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ.', bounds = [[-85.0511287776, -179.999999975], [85.0511287776, 179.999999975]], min_zoom = 1, max_zoom = 6, format = 'png', time = '', tilematrixset = 'GoogleMapsCompatible_Level', variant = 'MODIS_Terra_Aerosol', opacity = 0.75, name = 'NASAGIBS.ModisTerraAOD' ), ModisTerraChlorophyll = TileProvider( url = 'https://map1.vis.earthdata.nasa.gov/wmts-webmerc/{variant}/default/{time}/{tilematrixset}{max_zoom}/{z}/{y}/{x}.{format}', attribution = 'Imagery provided by services from the Global Imagery Browse Services (GIBS), operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ.', bounds = [[-85.0511287776, -179.999999975], [85.0511287776, 179.999999975]], min_zoom = 1, max_zoom = 7, format = 'png', time = '', tilematrixset = 'GoogleMapsCompatible_Level', variant = 'MODIS_Terra_Chlorophyll_A', opacity = 0.75, name = 'NASAGIBS.ModisTerraChlorophyll' ) ), NLS = TileProvider( url = 'https://nls-{s}.tileserver.com/nls/{z}/{x}/{y}.jpg', attribution = 'National Library of Scotland Historic Maps', bounds = [[49.6, -12], [61.7, 3]], min_zoom = 1, max_zoom = 18, subdomains = '0123', name = 'NLS' ), JusticeMap = Bunch( income = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'income', name = 'JusticeMap.income' ), americanIndian = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'indian', name = 'JusticeMap.americanIndian' ), asian = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'asian', name = 'JusticeMap.asian' ), black = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'black', name = 'JusticeMap.black' ), hispanic = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'hispanic', name = 'JusticeMap.hispanic' ), multi = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'multi', name = 'JusticeMap.multi' ), nonWhite = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'nonwhite', name = 'JusticeMap.nonWhite' ), white = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'white', name = 'JusticeMap.white' ), plurality = TileProvider( url = 'http://www.justicemap.org/tile/{size}/{variant}/{z}/{x}/{y}.png', attribution = 'Justice Map', size = 'county', bounds = [[14, -180], [72, -56]], variant = 'plural', name = 'JusticeMap.plurality' ) ), Wikimedia = TileProvider( url = 'https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}{r}.png', attribution = 'Wikimedia', min_zoom = 1, max_zoom = 19, name = 'Wikimedia' ), GeoportailFrance = Bunch( parcels = TileProvider( url = 'https://wxs.ign.fr/{apikey}/geoportail/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE={style}&TILEMATRIXSET=PM&FORMAT={format}&LAYER={variant}&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}', attribution = 'Geoportail France', bounds = [[-75, -180], [81, 180]], min_zoom = 2, max_zoom = 20, apikey = 'choisirgeoportail', format = 'image/png', style = 'bdparcellaire', variant = 'CADASTRALPARCELS.PARCELS', name = 'GeoportailFrance.parcels' ), ignMaps = TileProvider( url = 'https://wxs.ign.fr/{apikey}/geoportail/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE={style}&TILEMATRIXSET=PM&FORMAT={format}&LAYER={variant}&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}', attribution = 'Geoportail France', bounds = [[-75, -180], [81, 180]], min_zoom = 2, max_zoom = 18, apikey = 'choisirgeoportail', format = 'image/jpeg', style = 'normal', variant = 'GEOGRAPHICALGRIDSYSTEMS.MAPS', name = 'GeoportailFrance.ignMaps' ), maps = TileProvider( url = 'https://wxs.ign.fr/{apikey}/geoportail/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE={style}&TILEMATRIXSET=PM&FORMAT={format}&LAYER={variant}&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}', attribution = 'Geoportail France', bounds = [[-75, -180], [81, 180]], min_zoom = 2, max_zoom = 18, apikey = 'choisirgeoportail', format = 'image/jpeg', style = 'normal', variant = 'GEOGRAPHICALGRIDSYSTEMS.MAPS.SCAN-EXPRESS.STANDARD', name = 'GeoportailFrance.maps' ), orthos = TileProvider( url = 'https://wxs.ign.fr/{apikey}/geoportail/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE={style}&TILEMATRIXSET=PM&FORMAT={format}&LAYER={variant}&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}', attribution = 'Geoportail France', bounds = [[-75, -180], [81, 180]], min_zoom = 2, max_zoom = 19, apikey = 'choisirgeoportail', format = 'image/jpeg', style = 'normal', variant = 'ORTHOIMAGERY.ORTHOPHOTOS', name = 'GeoportailFrance.orthos' ) ), OneMapSG = Bunch( Default = TileProvider( url = 'https://maps-{s}.onemap.sg/v3/{variant}/{z}/{x}/{y}.png', variant = 'Default', min_zoom = 11, max_zoom = 18, bounds = [[1.56073, 104.11475], [1.16, 103.502]], attribution = '![](https://docs.onemap.sg/maps/images/oneMap64-01.png) New OneMap | Map data (C) contributors, Singapore Land Authority', name = 'OneMapSG.Default' ), Night = TileProvider( url = 'https://maps-{s}.onemap.sg/v3/{variant}/{z}/{x}/{y}.png', variant = 'Night', min_zoom = 11, max_zoom = 18, bounds = [[1.56073, 104.11475], [1.16, 103.502]], attribution = '![](https://docs.onemap.sg/maps/images/oneMap64-01.png) New OneMap | Map data (C) contributors, Singapore Land Authority', name = 'OneMapSG.Night' ), Original = TileProvider( url = 'https://maps-{s}.onemap.sg/v3/{variant}/{z}/{x}/{y}.png', variant = 'Original', min_zoom = 11, max_zoom = 18, bounds = [[1.56073, 104.11475], [1.16, 103.502]], attribution = '![](https://docs.onemap.sg/maps/images/oneMap64-01.png) New OneMap | Map data (C) contributors, Singapore Land Authority', name = 'OneMapSG.Original' ), Grey = TileProvider( url = 'https://maps-{s}.onemap.sg/v3/{variant}/{z}/{x}/{y}.png', variant = 'Grey', min_zoom = 11, max_zoom = 18, bounds = [[1.56073, 104.11475], [1.16, 103.502]], attribution = '![](https://docs.onemap.sg/maps/images/oneMap64-01.png) New OneMap | Map data (C) contributors, Singapore Land Authority', name = 'OneMapSG.Grey' ), LandLot = TileProvider( url = 'https://maps-{s}.onemap.sg/v3/{variant}/{z}/{x}/{y}.png', variant = 'LandLot', min_zoom = 11, max_zoom = 18, bounds = [[1.56073, 104.11475], [1.16, 103.502]], attribution = '![](https://docs.onemap.sg/maps/images/oneMap64-01.png) New OneMap | Map data (C) contributors, Singapore Land Authority', name = 'OneMapSG.LandLot' ) ) )
class Solution: """ @param words: the n strings @param target: the target string @return: The ans """ def the_longest_common_prefix(self, words, target): # write your code here ans = 0 for word in words: same = 0 for j in range(0, len(target)): if j > len(word) - 1 or target[j] != word[j]: break same += 1 ans = max(ans, same) return ans
# list to csv def listToCSV(obj): csv = '' for x in obj: csv += str(x) csv += ',' return csv[:-1] # csv to list def CSVToList(csv): obj = csv.split(',') li = [] for x in obj: li.append(int(x)) return li # 更新数据库 def update_db(obj, d): if not isinstance(d, dict): raise TypeError for i in d: setattr(obj, i, d[i])
class DogeyError(Exception): """ The base Dogey Exception, expect this as the main type of Dogey-specific errors such as InvalidCredentialsError. """ pass class DogeyCommandError(Exception): def __init__(self, command_name: str, message: str, *args): """ The basic Dogey exception for commands, expect this in on_command_error. Args: command_name (str): The name of the command. message (str): The message of the exception. """ assert isinstance(command_name, str) assert isinstance(message, str) self.command_name = command_name self.message = message super().__init__(command_name, message, *args) class InvalidCredentialsError(Exception): """An invalid token/refresh token has been passed to the Dogey client. """ pass class InstanceAlreadyCreated(DogeyError): """A Dogey instance has already been created, multiple calls to .start will cause this. """ pass class MissingRequiredArgument(DogeyCommandError): def __init__(self, command_name: str, argument: str): """A required argument is missing. Args: command_name (str): The command name. argument (str): The required argument. """ assert isinstance(argument, str) self.command_name = command_name self.argument = argument super().__init__(command_name, f'"{argument}" is a required argument that is missing.') class CommandNotFound(DogeyCommandError): def __init__(self, command_name: str): """A command can not be found. Args: command_name (str): The command name. """ assert isinstance(command_name, str) self.command_name = command_name super().__init__(command_name, f'The command could not be found.') class TooManyArguments(DogeyCommandError): def __init__(self, command_name: str): """Too many arguments have been passed to a command. Args: command_name (str): The command name. """ assert isinstance(command_name, str) self.command_name = command_name super().__init__(command_name, f'Too many arguments have been passed.')
""" * * Author: Juarez Paulino(coderemite) * Email: [email protected] * """ n=int(input()) o=dict(zip('tminp',[0,1,1,2,3])) a=sorted(enumerate([input().split()for _ in[0]*n]),key=lambda x:(o[x[1][1][2]],x[0])) for x in a:print(x[1][0])
sys_name = "XSS'OR" sys_copyright = "@evilcos.me" def sys(req): return { 'sys_name': sys_name, 'sys_copyright': sys_copyright, }
instrument_familes = { 'Strings': ['Guitar', 'Banjo', 'Sitar'], 'Percussion': ['Conga', 'Cymbal', 'Cajon'], 'woodwinds': ['Flute', 'Oboe', 'Clarinet'] } class KeyError(Exception): def __init__(self, key): self.key = key def __str__(self) -> str: return f"Key {self.key} does not exist" def print_instrument_families() -> None: # print out instrument families for family in ['Strings', 'Percussion', 'woodwinds']: try: print('Some instruments in the ' + family + 'family are: ' + ', '.join(instrument_familes[family])) except: raise KeyError(family) print_instrument_families()
#Ejercicio 1 ''' Ejemplo del profesor Convertir esta funsión de O(n^2) a una funsión de O(n) ''' def greatestNumber(array): for i in array: isIValTheGreatest = True for j in array: if j > i: isIValTheGreatest = False if isIValTheGreatest: return i ''' Función de O(n) ''' def theGreatestNumber(array): #Esta función solo usará un for para recorrer y comparar los elementos del array y encontrar el de mayor valor #Complejidad temporal/algorítmica: O(n) mayor = array[0] for i in range (len(array)): if array[i] > mayor: mayor = array[i] return mayor ''' Caso prueba ''' print(theGreatestNumber([1, 12, 3, 4, 5, 6, 7, 8, 9, 10]))
def intersection(l1, l2): res = [v for v in l1 if v in l2] return res def divide_into_primes(num, base=2, seq=None): if seq is None: seq = [] if num == 1: return seq for i in range(base, num+1): if not num % i: seq.append(i) return divide_into_primes(int(num/i), i, seq) x = divide_into_primes(2340) print(x) y = divide_into_primes(11230) print(y) common = intersection(x, y) print(common) # TODO there are issues with repeated elements
#!/usr/bin/env python # Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module contains all WORC-related Exceptions """ # pylint: disable=too-many-ancestors # Because fo inheriting from FastrError and a common exception causes this # exception, even though this behaviour is desired class WORCError(Exception): """ This is the base class for all WORC related exceptions. Catching this class of exceptions should ensure a proper execution of WORC. """ pass class WORCNotImplementedError(WORCError, NotImplementedError): """ This function/method has not been implemented on purpose (e.g. should be overwritten in a sub-class) """ pass class WORCIOError(WORCError, IOError): """ IOError in WORC """ pass class WORCTypeError(WORCError, TypeError): """ TypeError in the WORC system """ pass class WORCValueError(WORCError, ValueError): """ ValueError in the WORC system """ pass class WORCKeyError(WORCError, KeyError): """ KeyError in the WORC system """ pass class WORCAssertionError(WORCError, AssertionError): """ AssertionError in the WORC system """ pass class WORCIndexError(WORCError, IndexError): """ IndexError in the WORC system """ pass
def check(cmd, mf): m = mf.findNode('uuid') if m: return dict(expected_missing_imports=set(['netbios', 'win32wnet']))
s = set() for _ in range(int(input())): s.add(input()) print (len(s)) # one line solution print ( len(set([str(input()) for _ in range(int(input()))])) ) # https://www.hackerrank.com/challenges/py-set-add/problem
params = input().split(" ") params = [int(param) for param in params] if params[0] == params[1]: for i in range(1, params[0] + 1): print(input()) exit(0) else: all_gnomes = set(range(1, params[0] + 1)) remaining_gnomes = [] sorted = True prev_gnome = -1 for _ in range(params[1]): current_gnome = int(input()) remaining_gnomes.append(current_gnome) all_gnomes.remove(current_gnome) if sorted and prev_gnome > current_gnome: sorted = False elif sorted: prev_gnome = current_gnome if sorted: print('\n'.join([str(i) for i in range(1, params[0] + 1)])) exit(0) else: missing = False for missing_gnome in all_gnomes: for remaining_gnome in remaining_gnomes: if missing_gnome < remaining_gnome: print(missing_gnome) missing = True break else: print(remaining_gnome) remaining_gnomes = remaining_gnomes[1:] if missing: missing = False continue else: print(missing_gnome) remaining_gnomes = [str(gnome) for gnome in remaining_gnomes] print('\n'.join(remaining_gnomes))
""" Write a program that, given an ASCII binary matrix of 0's and 1's like this: 0000000000000000 0000000000000000 0000011001110000 0000001111010000 0000011001110000 0000011011100000 0000000000110000 0000101000010000 0000000000000000 0000000000000000 0000000000000000 Outputs the smallest cropped sub-matrix that still contains all 1's (that is, remove all borders of 0's): 01100111 00111101 01100111 01101110 00000011 10100001 """ def main(): matrix = ("0000000000000000\n" "0000000000000000\n" "0000011001110000\n" "0000001111010000\n" "0000011001110000\n" "0000011011100000\n" "0000000000110000\n" "0000101000010000\n" "0000000000000000\n" "0000000000000000\n" "0000000000000000") matrix = matrix.split('\n') top = -1 bottom = 0 right = 0 left = len(matrix[0]) for n, m in enumerate(matrix): if '1' in m: if top == -1: top = n bottom = n left_find = m.find('1') right_find = m.rfind('1') if left_find < left: left = left_find if right_find > right: right = right_find for m in matrix[top:bottom+1]: print(m[left:right+1]) if __name__ == "__main__": main()
pointer=-1 lock=0 def setSeq(data) : if lock == 1: exit(2) globals()['pointer']=-1 globals()['data']=data.split(',') globals()['lock']=1 def raw_input() : globals()['pointer']+=1 try: return data[pointer] except IndexError: exit(0) def open(path,mode) : exit(3)
result = 0 for i in range(1000): if i%3==0 or i%5==0: result += i print(result)
#!/usr/bin/python3 year = int(input("请输入年:")) month = int(input("请输入月份:")) day = int(input("请输入几号:")) leapyear = [0,31,29,31,30,31,30,31,31,30,31,30,31] normalyear = [0,31,28,31,30,31,30,31,31,30,31,30,31] days = 0 i = month if year%4 == 0: for temp in range(0,i,1): days += leapyear[temp] print("今年是闰年, ",end="") else: for temp in range(0,i,1): days += normalyear[temp] days = days + day print('这是这一年的第%d天'%days)
""" Get input from user via console or command line ----------------------------------------------- Output: (string) """ name = input('What is your name? ') print('Hello {}!'.format(name))
text = input() sum = 0 for symbol in text: if symbol == "a": sum += 1 elif symbol == "e": sum += 2 elif symbol == "i": sum += 3 elif symbol == "o": sum += 4 elif symbol == "u": sum += 5 print(sum)
""" Remove Item There are several methods to remove items from a list: """ thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist)
debt = 95000 interest_percent = .059 yearly_salary = None hourly_salary = 20 debt_repayment_percent = .2 debt_repayment_length = 0 work_days = 261 work_hours = 8 interest = 0 if yearly_salary and hourly_salary is not None: if yearly_salary != hourly_salary * work_days * work_hours: raise ValueError('only yearly or hourly salary can be defined') if yearly_salary is None: yearly_salary = hourly_salary * (work_days * work_hours) else: hourly_salary = yearly_salary / (work_days * work_hours) while debt > 0: debt_repayment_length += 1 debt *= 1 + interest_percent * (1 / 12) interest += debt * (1 + interest_percent * (1 / 12)) - debt debt -= yearly_salary / 12 * debt_repayment_percent print(f'{debt_repayment_length} months, paying ${round(interest)} in interest')
max_len = 79 str_plier = 2 foo = "Oh oh oh oh you don't know, Joe."*str_plier curr_len = len(foo) if curr_len > max_len: print("Danger, Will Robinson!!!") print("Your sentiment is {} ".format(curr_len-max_len)+"characters too long!") else: print("What a lovely sentiment!\n"+ foo+"\nIn only {} characters!".format(curr_len))
#!/usr/bin/env python3 # compute nim values using negamax and a dictionary # that holds values already computed RBH 2019 # version 2.0 December 2020 new features # - verbose option, showing win/loss value once it is known # - move initialization of the start position outside the main loop # - tidying, e.g. pad variable instead of ' ' def get_piles(): while True: raw = input('nim game pile sizes (eg. 3 5 7) ') try: dim = tuple( int(x) for x in raw.split() ) if len(dim) > 0 and all(d >= 0 for d in dim): return dim except ValueError: pass print('invalid, try again') def win_loss(b): return 'win' if b else 'loss' """ sd dictionary(state: boolean), true if player-to-move wins """ def winning(nim_psn, sd, depth, verbose): # tuple, dictionary, recursion depth, verbose mode (True/False) pad = ' ' if nim_psn in sd: if depth==0: print('solved before search') if verbose: print(pad*depth, nim_psn, win_loss(sd[nim_psn]), 'dict') return sd[nim_psn] # nim_psn not in dictionary, so update before we return if verbose: print(pad*depth, nim_psn) psn = tuple(sorted(nim_psn)) for j in range(len(psn)): # each pile for k in range(psn[j]): # number of stones that will remain in that pile child = tuple(sorted(psn[:j] + (k,) + psn[j+1:])) if not winning(child, sd, depth+1, verbose): if verbose: print(pad*depth, nim_psn, win_loss(True), 'losing child') sd.update({ nim_psn: True }) # update before return if depth == 0: print('\nwin: move to ',child, len(sd), 'states') # show a winning move return True if verbose: print(pad*depth, nim_psn, win_loss(False), 'no win') sd.update({ nim_psn: False }) # update before return if depth == 0: print('\nloss,', len(sd), 'states') return False v = get_piles() S = dict() empty = tuple([0]*len(v))# position (0 0 ... ) S.update({empty: False}) # position (0 0 ... ) loses w = winning(v, S, 0, True)
TEMPERATURE = 0x01 GAS = 0x02 VOLTAGE = 0x04 DELAY = 0x10 TEST_SUCCESS = 0x3F ERROR_RELAY_OPEN = 0x04 ERROR_RELAY_CLOSED = 0x08 MODE_CONFIG = 0x80 MODE_RUN = 0x40 MODE_ERROR = 0xC0 MODE_TIMEOUT = 0x00 WRITE = 0x20 def print_status(state): if(state&MODE_ERROR == MODE_ERROR): print("ERROR MODE") elif(state&MODE_ERROR == MODE_TIMEOUT): print("TIMEOUT") elif(state&MODE_ERROR == MODE_CONFIG): print("CONFIG MODE") elif(state&MODE_ERROR == MODE_RUN): print("RUN MODE") if(state&TEST_SUCCESS == 0x00): print("OK") if(state&WRITE): print("WRITE OPERATION:") if(state&TEMPERATURE): print("TEMPERATURE") if(state&GAS): print("GAS LEVEL") if(state&ERROR_RELAY_OPEN): print("VOLTAGE LEVEL") if(state&ERROR_RELAY_CLOSED): print("VOLTAGE LEVEL") if(state&DELAY): print("DELAY") else: if(state&TEMPERATURE): print("TEMPERATURE EXCEEDED") if(state&GAS): print("GAS LEVEL EXCEEDED") if(state&ERROR_RELAY_OPEN): print("RELAY STUCK OPEN") if(state&ERROR_RELAY_CLOSED): print("RELAY STUCK CLOSED") def mode_is_run(state): return (state&MODE_ERROR == MODE_RUN) def mode_is_config(state): return (state&MODE_ERROR == MODE_CONFIG) def mode_is_timeout(state): return (state&MODE_ERROR == MODE_TIMEOUT)
# TODO write docs class SceneDrawer(object): def __init__(self, device, register): self.device = device self.background_color = "black" self.entity_register = register def draw(self, scene): for entity in scene.entities: if entity.drawer is not None: entity.drawer.draw(entity) else: self.entity_register.add_drawer_support(entity) entity.drawer.draw(entity)
# -*- coding: utf-8 -*- """ Solution to Project Euler problem 16 Author: Jaime Liew https://github.com/jaimeliew1/Project_Euler_Solutions """ def run(): n = pow(2,1000) digitSum = sum(int(i) for i in str(n)) return digitSum if __name__ == "__main__": print(run())
""" Loop. The loop() function causes draw() to execute repeatedly. If noLoop is called in setup() the draw() is only executed once. In this example click the mouse to execute loop(), which will cause the draw() to execute repeatedly. """ y = 100 def setup(): """ The statements in the setup() function run once when the program begins. """ size(640, 360) # Size should be the first statement stroke(255) # Set stroke color to white noLoop() y = height * 0.5 def draw(): """ The statements in draw() are run until the program is stopped. Each statement is run in sequence and after the last line is read, the first line is run again. """ global y background(0) # Set the background to black line(0, y, width, y) y = y - 1 if y < 0: y = height def mousePressed(): loop()
"""align.py Aligning two sequences. The elements of the sequences are stings or string like elements, it is not clear to me what interface for the class is expected in the latter case. Originally written by Alex Plotnick. """ def align(a, b, d=-5, s=lambda x,y: x==y, key=lambda x: x, gap=None): """Find the globally optimal alignment between the two sequences a and b using gap penalty d and similarity function s, and return the aligned sequences. The similarity function is applied to the result of key(x) and key(y) for each x in a and y in b, and should return an integer; key defaults to the identity function. This implementation uses the Needleman-Wunsch algorithm.""" m = len(a) + 1 n = len(b) + 1 # Rather than keeping a separate traceback matrix, we'll store (score, fun) # tuples in the alignment matrix, where fun is one of the following three # traceback functions. trace = [m-1, n-1] # decoding starts in the lower right-hand corner def diag(): trace[0] -= 1; trace[1] -= 1; return a[trace[0]], b[trace[1]] def up(): trace[0] -= 1; return a[trace[0]], gap def left(): trace[1] -= 1; return gap, b[trace[1]] # Initialize the alignment matrix. f = [[None]*n for _ in range(m)] f[0][0] = (0, lambda: None) for i in range(1, m): f[i][0] = (d*i, up) for j in range(1, n): f[0][j] = (d*j, left) # Compute the optimal alignment. for i in range(1, m): for j in range(1, n): f[i][j] = max((f[i-1][j-1][0] + s(key(a[i-1]), key(b[j-1])), diag), (f[i-1][j][0] + d, up), # a[i] -> gap (f[i][j-1][0] + d, left), # b[j] -> gap key=lambda x: x[0]) # Decoding is now just a matter of running the stored traceback functions # until we get back to the upper left-hand corner. aligned_a = []; aligned_b = [] while trace != [0, 0]: next_a, next_b = f[trace[0]][trace[1]][1]() aligned_a.append(next_a) aligned_b.append(next_b) aligned_a.reverse(); aligned_b.reverse() if isinstance(a, str) and isinstance(b, str): # Be nice and coerce the results back to strings. def default_gap(x): return x if x is not None else "-" return ("".join(map(default_gap, aligned_a)), "".join(map(default_gap, aligned_b))) return aligned_a, aligned_b def levenshtein_distance(a, b): """Compute the Levenshtein edit distance between the sequences a and b.""" m = len(a) + 1 n = len(b) + 1 d = [[0]*n for _ in range(m)] for i in range(m): d[i][0] = i # deletion for j in range(n): d[0][j] = j # insertion for i in range(1, m): for j in range(1, n): if a[i-1] == b[j-1]: d[i][j] = d[i-1][j-1] else: d[i][j] = min(d[i-1][j] + 1, # deletion d[i][j-1] + 1, # insertion d[i-1][j-1] + 1) # substitution return d[m-1][n-1] class Word(object): def __init__(self, string): self.text = string def x__str__(self): return self.text def x__getitem__(self, i): return self.text[i] def x__len__(self): return len(self.text) if __name__ == '__main__': s0 = ['door', 'knob'] s1 = ['door', 'knobs', 'are', 'out'] s2 = ['doors', 'knobs', 'are', 'in'] s3 = ['door', 's', 'knobs', 'were', 'in'] s4 = ['door\'s', 'knobs', 'are', 'in'] for x, y in [(s0, s1), (s1, s2), (s2, s3), (s2, s4), (s3, s4)]: print("\nAligning") print(' ', x) print(' ', y) result = align(x, y) print(' ==>') print(' ', ''.join(["%-20s" % e for e in result[0]])) print(' ', ''.join(["%-20s" % e for e in result[1]])) s1 = "hello this is jim lehrer with the newshour on pbs we have news about the tomato it has been observed recently that they dont taste good anymore".split() s2 = 'Hello, this is Jim Lehrer, with the newshour on BBC: "We have news about the tomato it has been observed recently that they don\'t taste good anymore.'.split() s1 = [Word(w) for w in s1] s2 = [Word(w) for w in s2] for x in align(s1, s2): print('>>>', ' '.join([str(w) for w in x])) first, second = align(s1, s2) #print(' ', ''.join(["%-10s" % str(e) for e in first])) #print(' ', ''.join(["%-10s" % e for e in second])) for x in zip(first, second): print(str(x[0].text), str(x[1].text))
content = '''package main import ( "context" "github.com/qsock/qim/lib/proto/ret" ) type Server struct{} func (*Server) Ping(ctx context.Context, req *ret.NoArgs) (*ret.NoArgs, error) { return new(ret.NoArgs), nil }''' def gen(name, srv_dir) : with open(srv_dir+"/handle.go", "w") as f: f.write(content)
a = float(input('Primeiro Segmento: ')) b = float(input('Segundo Segmento: ')) c = float(input('Terceiro Segmento: ')) if (a + b) > c and (a + c) > b and (b + c) > a: print('Os segmentos acima PODEM FORMAR um triângulo', end=' ') if a == b == c: print('EQUILÁTERO!') elif a == b or a == c or c == b: print('ISÓSCELES!') else: print('ESCALENO!') else: print('Os segmentos acima NÃO PODEM FORMAR um triângulo!')
# Source : https://leetcode.com/problems/symmetric-tree/ # Author : penpenps # Time : 2019-07-09 # Revert right node firstly, then compare with left node # Time Complexity: O(n) # Space Complexity: O(n) # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: # Revert TreeNode def revert(node): if not node: return node.left, node.right = node.right, node.left revert(node.left) revert(node.right) def isEqual(left, right): if not left and not right: return True if not left or not right: return False if left.val != right.val: return False return isEqual(left.left, right.left) and isEqual(left.right, right.right) if not root: return True revert(root.right) return isEqual(root.left, root.right)
#!/usr/bin/python3 class MyList(list): """extended version of list """ def print_sorted(self): """prints the list in ascending order """ copy = self[:] copy.sort() print(copy)
altura= float(input('Quanto de altura a parede possui?')) largura= float(input('Quanto de largura a parede possui?')) area= largura * altura litros= area/2 print('Sua parede possui uma área de {},portanto, você precisará de {}litros de tinta para pinta-la'.format(area,litros))
#Desafio: Aprimore o desafio anterior, mostrando no final: # A) A soma de todos os valores pares digitados. # B) A soma dos valores da terceira coluna. # C) O maior valor da segunda linha. matriz = [[], [], []] par = soma = maior = 0 for n in range(0, 3): for i in range(0, 3): num = int(input(f'Digite um valor para[{n}, {i}]: ')) if num % 2 == 0: par += num if i == 2: soma += num if n == 1 and num > maior: maior = num matriz[n].append(num) print('=-' * 25) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') print('') print('=-' * 25) print(f'A soma dos valores pares é {par}') print(f'A soma dos valores da terceira coluna é {soma}') print(f'O maior valor da segunda linha é {maior}')
""" """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': self.ans = None def recurse(node): if not node: return False left = recurse(node.left) right = recurse(node.right) mid = node == p or node == q print(node.val, mid+left+right) if mid+left+right >= 2: self.ans = node return mid or left or right recurse(root) return self.ans def lowestCommonAncestor(self, root, p, q): if root == None or root == p or root == q: return root # Find p/q in left subtree l = self.lowestCommonAncestor(root.left, p, q) # Find p/q in right subtree r = self.lowestCommonAncestor(root.right, p, q) # If p and q found in left and right subtree of this node, then this node is LCA if l and r: return root # Else return the node which returned a node from it's subtree such that one of it's ancestor will be LCA return l if l else r
result = [ {0: 0, 1: 'var 1'}, {0: 0, 1: 'var 2'} ]
result = 0 """ i = 0 while i < 4: nr = int(input("Please give me the number: ")) result += nr i += 1 print("The result of adding numbers is: ", result) """ for i in range(1000): if (i%2 == 0): print(i, " is even number") print("The result of adding numbers is: ", result)
# Desafio 52 - Aula 13 : Programa que leia um numero e diga se é um numero PRIMO. conta = 0 primo = int(input('Me diga um numero: ')) for c in range(1, primo+1): if primo % c == 0 : print('\033[34m', end='') conta += 1 else: print('\033[m', end='') print(f'{c}', end=' ') if conta == 2: print(f'\n\033[mO numero {primo} é primo!') else: print(f'\n\033[mO numero {primo} não é primo!')
# https://github.com/lord63-forks/python-patterns/blob/patch-3/lazy_evaluation.py def lazy_property(fn): """Decorator that makes a property lazy-evaluated.""" attr_name = '_lazy_' + fn.__name__ @property def _lazy_property(self): if not hasattr(self, attr_name): setattr(self, attr_name, fn(self)) return getattr(self, attr_name) return _lazy_property class Person(object): def __init__(self, name, occupation): self.name = name self.occupation = occupation @lazy_property def relatives(self): # Get all relatives, let's assume that it costs much time. relatives = "Many relatives." return relatives def main(): Jhon = Person('Jhon', 'Coder') print("Name: {0} Occupation: {1}".format(Jhon.name, Jhon.occupation)) print("Before we access `relatives`:") print(Jhon.__dict__) print("Jhon's relatives: {0}".format(Jhon.relatives)) print("After we've accessed `relatives`:") print(Jhon.__dict__) if __name__ == '__main__': main()
description = 'memograph readout' group = 'optional' devices = dict( t_in_fak40 = device('nicos_mlz.devices.memograph.MemographValue', hostname = 'memograph02.care.frm2', group = 1, valuename = 'T_in MIRA', description = 'inlet temperature memograph', fmtstr = '%.2F', warnlimits = (-1, 17.5), #-1 no lower value unit = 'degC', ), t_out_fak40 = device('nicos_mlz.devices.memograph.MemographValue', hostname = 'memograph02.care.frm2', group = 1, valuename = 'T_out MIRA', description = 'outlet temperature memograph', pollinterval = 30, maxage = 60, fmtstr = '%.2F', unit = 'degC', ), p_in_fak40 = device('nicos_mlz.devices.memograph.MemographValue', hostname = 'memograph02.care.frm2', group = 1, valuename = 'P_in MIRA', description = 'inlet pressure memograph', pollinterval = 30, maxage = 60, fmtstr = '%.2F', unit = 'bar', ), p_out_fak40 = device('nicos_mlz.devices.memograph.MemographValue', hostname = 'memograph02.care.frm2', group = 1, valuename = 'P_out MIRA', description = 'outlet pressure memograph', pollinterval = 30, maxage = 60, fmtstr = '%.2F', unit = 'bar', ), flow_in_fak40 = device('nicos_mlz.devices.memograph.MemographValue', hostname = 'memograph02.care.frm2', group = 1, valuename = 'FLOW_in MIRA', description = 'inlet flow memograph', pollinterval = 30, maxage = 60, fmtstr = '%.2F', warnlimits = (0.2, 100), #100 no upper value unit = 'l/min', ), flow_out_fak40 = device('nicos_mlz.devices.memograph.MemographValue', hostname = 'memograph02.care.frm2', group = 1, valuename = 'FLOW_out MIRA', description = 'outlet flow memograph', pollinterval = 30, maxage = 60, fmtstr = '%.2F', unit = 'l/min', ), leak_fak40 = device('nicos_mlz.devices.memograph.MemographValue', hostname = 'memograph02.care.frm2', group = 1, valuename = 'Leak MIRA', description = 'leakage memograph', pollinterval = 30, maxage = 60, fmtstr = '%.2F', warnlimits = (-1, 1), #-1 no lower value unit = 'l/min', ), cooling_fak40 = device('nicos_mlz.devices.memograph.MemographValue', hostname = 'memograph02.care.frm2', group = 1, valuename = 'Cooling MIRA', description = 'cooling memograph', pollinterval = 30, maxage = 60, fmtstr = '%.2F', unit = 'kW', ), )
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: print(S[0]) stack = [] for i in S: if i=="#": if len(stack)==0: continue stack.pop() else: stack.append(i) S="" while len(stack)!=0: c = stack.pop(0) S+=str(c) print(S) for i in T: if i=="#": if len(stack)==0: continue stack.pop() else: stack.append(i) T="" while len(stack)!=0: c = stack.pop(0) T+=str(c) print(T) return T==S
# Tram, Minh # mqt0029 # 1001540029 # 2019-05-13 #---------#---------#---------#---------#---------#--------# class InternalError( Exception ) : pass class LexicalError( Exception ) : pass class SemanticError( Exception ) : pass class SyntacticError( Exception ) : pass #---------#---------#---------#---------#---------#--------#
def coord(x,y): if x > 0 and y > 0: i = "I" elif x > 0 and y < 0: i = "IV" elif x < 0 and y < 0: i = "III" elif x < 0 and y > 0: i = "II" print(f"O ponto ({x:.0f}, {y:.0f}) pertence ao quadrante: {i}") print(" ") def main(): a = float(input("Digite um valor para x: ")) b = float(input("Digite um valor para y: ")) print("") coord(a,b) main() #-------------- #~~phelipes2000
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class HardWare(object): def power_on(self): print('上电') def bootloader(self): print('bootloader 启动') def power_off(self): print('断电') class OperatingSystem(object): def load_kernel(self): print('加载内核') def load_image(self): print('加载镜像') def exit_os(self): print('退出操作系统') class SoftWare(object): def load_app(self): print('加载应用程序') def exit_app(self): print('退出应用程序') class Computer(object): def __init__(self): self.hw = HardWare() self.os = OperatingSystem() self.sw = SoftWare() def boot(self): self.hw.power_on() self.hw.bootloader() self.os.load_kernel() self.os.load_image() self.sw.load_app() def shut_down(self): self.sw.exit_app() self.os.exit_os() self.hw.power_off() if __name__ == '__main__': computer = Computer() print('开机') computer.boot() print('\n关机') computer.shut_down()
# -*- coding: utf-8 -*- """ Created on 31 Dec 2020 12:18:55 @author: jiahuei """ __version__ = "0.4.0"
#!/usr/bin/env python3 m = int(input()) if m < 100: print("00") elif m <= 5000: print(str(m//100).zfill(2)) elif m <= 30000: print(m//1000 + 50) elif m <= 70000: print((m//1000 - 30)//5 + 80) else: print(89)
# to compute modular power # Iterative Function to calculate # (x^y)%p in O(log y) def power(x, y, p) : res = 1 # Initialize result # Update x if it is more # than or equal to p x = x % p while (y > 0) : # If y is odd, multiply # x with result if ((y & 1) == 1) : res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res
"""Utility class for formatting Slack Messages.""" def wrap_slack_code(str): """Format code.""" return f"`{str}`" def wrap_code_block(str): """Format code block.""" return f"```\n{str}\n```" def wrap_quote(str): """Format quote.""" return f"> {str}\n" def wrap_emph(str): """Format emph.""" return f"*{str}*"
""" Programa 2 Descrição: Este programa pede a entrada de dados pelo usuário até que o dado seja do tipo adequado. Autor: Nelson S. dos Santos Versão: 0.0.1 """ # Entrada # Atribuição de variáveis: usuários do sistema usuario1 = "nelson" usuario2 = "joao" usuario3 = "juan" usuario4 = "nathan" while True: usuario = input("\nQual o seu nome de usuário?") if usuario == usuario1: print(f"\nBenvindo ao sistema, {usuario1}") break elif usuario == usuario2: print(f"\nBenvindo ao sistema, {usuario2}") break elif usuario == usuario2: print(f"\nBenvindo ao sistema, {usuario3}") break elif usuario == usuario2: print(f"\nBenvindo ao sistema, {usuario4}") break else: print("\nUsuário inválido. Tente novamente!") # Processamento # Saída
#print excepation information as a msg in program try: print(10/0) except ZeroDivisionError as msg: print("the type of error:",msg.__class__)